def test_write_gromacs():
    water = Molecule(
        [
            Atom("O", [0.0, 0.0, 0.0], export={"grotype": "OW"}),
            Atom("H", [0.1, 0.0, 0.0], export={"grotype": "HW1"}),
            Atom("H", [-0.03333, 0.09428, 0.0], export={"grotype": "HW2"}),
        ],
        export={"groname": "SOL"},
    )

    sys = System.empty(200, 3 * 200, box_vectors=np.eye(3) * 2.0)
    for i in range(200):
        sys.add(water.copy())

    df = datafile("/tmp/dummy.gro", mode="w")
    df.write("system", sys)

    with assert_raises(Exception):
        df = datafile("/tmp/dummy.gro")
        df.write("system", sys)

    df = datafile("/tmp/dummy.gro")
    sread = df.read("system")

    assert all(sread.type_array == sys.type_array)
Exemple #2
0
def test_bond_guessing():
    from chemlab.db import ChemlabDB, CirDB
    from chemlab.graphics import display_molecule
    from chemlab.io import datafile

    mol = datafile('tests/data/3ZJE.pdb').read('molecule')
    print(mol.r_array)
    mol.guess_bonds()
    assert mol.bonds.size > 0

    # We should find the bond guessing also for systems

    # System Made of two benzenes
    bz = datafile("tests/data/benzene.mol").read('molecule')
    bzbonds = bz.bonds
    bz.bonds = np.array([])

    # Separating the benzenes by large amount
    bz2 = bz.copy()
    bz2.r_array += 2.0

    s = System([bz, bz2])
    s.guess_bonds()
    assert_eqbonds(s.bonds, np.concatenate((bzbonds, bzbonds + 6)))

    # Separating benzenes by small amount
    bz2 = bz.copy()
    bz2.r_array += 0.15

    s = System([bz, bz2])
    s.guess_bonds()
    assert_eqbonds(s.bonds, np.concatenate((bzbonds, bzbonds + 6)))
Exemple #3
0
def rdffunc(args):

    import multiprocessing
    type_a, type_b = args.selection.split('-')
    syst = datafile(args.filename).read("system")
    sel_a = syst.type_array == type_a
    sel_b = syst.type_array == type_b
    
    df = datafile(args.trajectory)
    t, coords = df.read("trajectory")
    boxes = df.read("boxes")
    
    times = [int(tim) for tim in args.t.split(',')]
    ind = np.searchsorted(t, times)
    arguments = ((coords[i][sel_a], coords[i][sel_b], boxes[i]) for i in ind) 
    
    rds = map(get_rdf, arguments)
    
    for rd in rds:
        plot(rd[0], rd[1])
    
    ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    
    xlabel('Time(ps)')
    ylabel(args.selection)

    grid()
    show()
Exemple #4
0
def rdffunc(args):

    import multiprocessing
    type_a, type_b = args.selection.split('-')
    syst = datafile(args.filename).read("system")
    sel_a = syst.type_array == type_a
    sel_b = syst.type_array == type_b

    df = datafile(args.trajectory)
    t, coords = df.read("trajectory")
    boxes = df.read("boxes")

    times = [int(tim) for tim in args.t.split(',')]
    ind = np.searchsorted(t, times)
    arguments = ((coords[i][sel_a], coords[i][sel_b], boxes[i]) for i in ind)

    rds = map(get_rdf, arguments)

    for rd in rds:
        plot(rd[0], rd[1])

    ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    xlabel('Time(ps)')
    ylabel(args.selection)

    grid()
    show()
Exemple #5
0
def test_write_cml():
    df = datafile('tests/data/mol.cml')
    mol = df.read("molecule")
    
    df = datafile('/tmp/sadf.cml', 'w')
    df.write('molecule', mol)
    
def test_bond_guessing():
    from chemlab.db import ChemlabDB, CirDB
    from chemlab.graphics import display_molecule
    from chemlab.io import datafile

    mol = datafile('tests/data/3ZJE.pdb').read('molecule')
    print(mol.r_array)
    mol.guess_bonds()
    assert mol.bonds.size > 0

    # We should find the bond guessing also for systems

    # System Made of two benzenes
    bz = datafile("tests/data/benzene.mol").read('molecule')
    bzbonds = bz.bonds
    bz.bonds = np.array([])

    # Separating the benzenes by large amount
    bz2 = bz.copy()
    bz2.r_array += 2.0

    s = System([bz, bz2])
    s.guess_bonds()
    assert_eqbonds(s.bonds, np.concatenate((bzbonds, bzbonds + 6)))

    # Separating benzenes by small amount
    bz2 = bz.copy()
    bz2.r_array += 0.15

    s = System([bz, bz2])
    s.guess_bonds()
    assert_eqbonds(s.bonds, np.concatenate((bzbonds, bzbonds + 6)))
def test_read_xyz():
    df = datafile("tests/data/sulphoxide.xyz")
    mol1 = df.read("molecule")

    df = datafile("/tmp/t.xyz", mode="w")
    df.write("molecule", mol1)

    df = datafile("/tmp/t.xyz", mode="rb")
    mol2 = df.read("molecule")

    assert np.allclose(mol1.r_array, mol2.r_array)
    assert all(mol1.type_array == mol2.type_array)
Exemple #8
0
def test_read_xyz():
    df = datafile('tests/data/sulphoxide.xyz')
    mol1 = df.read('molecule')

    df = datafile('/tmp/t.xyz', mode="w")
    df.write('molecule', mol1)

    df = datafile('/tmp/t.xyz', mode="r")
    mol2 = df.read('molecule')

    assert np.allclose(mol1.r_array, mol2.r_array)
    assert all(mol1.type_array == mol2.type_array)
Exemple #9
0
def make_gromacs(simulation, directory, clean=False):
    """Create gromacs directory structure"""
    if clean is False and os.path.exists(directory):
        raise ValueError(
            'Cannot override {}, use option clean=True'.format(directory))
    else:
        shutil.rmtree(directory, ignore_errors=True)
        os.mkdir(directory)

    # Check custom simulation potential

    if simulation.potential.intermolecular.type == 'custom':

        for pair in simulation.potential.intermolecular.special_pairs:
            table = to_table(
                simulation.potential.intermolecular.pair_interaction(*pair),
                simulation.cutoff)
            fname1 = os.path.join(directory,
                                  'table_{}_{}.xvg'.format(pair[0], pair[1]))
            fname2 = os.path.join(directory,
                                  'table_{}_{}.xvg'.format(pair[1], pair[0]))

            with open(fname1, 'w') as fd:
                fd.write(table)

            with open(fname2, 'w') as fd:
                fd.write(table)

        ndx = {'System': np.arange(simulation.system.n_atoms, dtype='int')}
        for particle in simulation.potential.intermolecular.particles:
            idx = simulation.system.where(
                atom_name=particle)['atom'].nonzero()[0]
            ndx[particle] = idx

        with open(os.path.join(directory, 'index.ndx'), 'w') as fd:
            fd.write(to_ndx(ndx))

    # Parameter file
    mdpfile = to_mdp(simulation)
    with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd:
        fd.write(mdpfile)

    # Topology file
    topfile = to_top(simulation.system, simulation.potential)
    with open(os.path.join(directory, 'topol.top'), 'w') as fd:
        fd.write(topfile)

    # Simulation file
    datafile(os.path.join(directory, 'conf.gro'),
             'w').write('system', simulation.system)

    return directory
Exemple #10
0
def test_read_xyz():
    df = datafile('tests/data/sulphoxide.xyz')
    mol1 = df.read('molecule')
    
    
    df = datafile('/tmp/t.xyz', mode="w")
    df.write('molecule', mol1)
    
    df = datafile('/tmp/t.xyz', mode="r")
    mol2 = df.read('molecule')
    
    assert np.allclose(mol1.r_array, mol2.r_array)
    assert all(mol1.type_array == mol2.type_array)
Exemple #11
0
def test_traj_viewer():
    tv = QtTrajectoryViewer()

    s = datafile('tests/data/water.gro').read('system')
    ar = tv.add_renderer(BallAndStickRenderer, s.r_array, s.type_array, find_bonds(s))

    times, frames = datafile('tests/data/trajout.xtc').read('trajectory')

    def update(index):
        f = frames[index]
        ar.update_positions(f)
        tv.set_text(format_time(times[index]))
        tv.widget.update()

    tv.update_function(update, len(frames))
    tv.run()
Exemple #12
0
def test_read_cclib():
    try:
        import cclib
    except:
        raise SkipTest
    df = datafile('tests/data/cclib/water_mp2.out', format='gamess')

    # Reading a properties that does exist
    result1 = df.read('gbasis')
    result2 = [[
        ('S', [(130.7093214, 0.154328967295), (23.8088661, 0.535328142282),
               (6.4436083, 0.444634542185)]),
        ('S', [(5.0331513, -0.099967229187), (1.1695961, 0.399512826089),
               (0.380389, 0.70011546888)]),
        ('P', [(5.0331513, 0.155916274999), (1.1695961, 0.607683718598),
               (0.380389, 0.391957393099)])
    ],
               [('S', [(3.4252509, 0.154328967295),
                       (0.6239137, 0.535328142282),
                       (0.1688554, 0.444634542185)])],
               [('S', [(3.4252509, 0.154328967295),
                       (0.6239137, 0.535328142282),
                       (0.1688554, 0.444634542185)])]]

    assert result1 == result2
Exemple #13
0
def energy(args, output=None):
    ens = args.e
    fns = args.filenames
    
    datafiles = [datafile(fn) for fn in fns] 
    
    quants = datafiles[0].read('avail quantities')
    for i,e in enumerate(ens):
        if e not in quants:
            match = difflib.get_close_matches(e, quants)
            print 'Quantity %s not present, taking close match: %s' % (e, match[0])
            ens[i] = match[0]
    
    toplot = []
    for df in datafiles:
        for e in ens:
            plotargs = {}
            plotargs['points'] = df.read('quantity', e)
            plotargs['filename'] = df.fd.name
            plotargs['quantity'] = e
            
            toplot.append(plotargs)
    plots = []
    legends = []
    for arg in toplot:
        p, = plot(arg['points'][0], arg['points'][1])
        plots.append(p)
        legends.append(arg['filename'])
    xlabel('Time(ps)')
    ylabel(ens[0])
    
    ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    grid()
    figlegend(plots, legends, 'upper right')
    show()
Exemple #14
0
def test_toon_shading():

    from chemlab.db import ChemlabDB, CirDB
    from chemlab.io import datafile
    from chemlab.graphics import colors
    from chemlab.core.molecule import guess_bonds
    
    cdb = ChemlabDB()
    
    #mol = cdb.get('molecule', 'example.norbornene')
    
    mol = datafile('tests/data/3ZJE.pdb').read('system')
    v = QtViewer()
    #v.widget.post_processing = FXAAEffect(v.widget)
    #v.widget.post_processing = SSAOEffect(v.widget, kernel_size=64, kernel_radius=1.0, ssao_power=2.0)
    

    v.widget.camera.autozoom(mol.r_array)
    #sr = v.add_renderer(AtomRenderer, mol.r_array,
    #                    mol.type_array, 'impostors',
    #                    shading='toon')
    #sr = v.add_renderer(AtomRenderer, mol.r_array,
    #                    mol.type_array, 'polygons',
    #                    shading='toon')
    
    ar = v.add_renderer(BallAndStickRenderer,
                        mol.r_array, mol.type_array,
                        guess_bonds(mol.r_array, mol.type_array),
                        shading='toon')
    
    v.run()
Exemple #15
0
def test_ball_and_stick_renderer():
    from collections import defaultdict
    from chemlab.io import datafile
    from chemlab.db.cirdb import CirDB

    v = QtViewer()
    v.add_post_processing(SSAOEffect, kernel_radius=0.15)

    #v.widget.background_color = black
    #mol = Molecule([Atom("O", [-0.499, 0.249, 0.0]),
    #                Atom("H", [-0.402, 0.249, 0.0]),
    #                Atom("H", [-0.532, 0.198, 0.10])])

    #mol.bonds = np.array([[0, 1],[0, 2]])

    #mol = CirDB().get("molecule", "moronic acid")
    mol = datafile('tests/data/3ZJE.pdb').read('molecule')
    mol.bonds = find_bonds(mol)

    ar = v.add_renderer(BallAndStickRenderer, mol.r_array, mol.type_array,
                        mol.bonds)

    # Try without bonds
    # ar2 = v.add_renderer(BallAndStickRenderer, mol.r_array + 0.5, mol.type_array, np.array([]))

    v.run()
Exemple #16
0
def test_merge_system():
    # take a protein
    from chemlab.io import datafile
    from chemlab.graphics import display_system

    from chemlab.db import ChemlabDB

    water = ChemlabDB().get("molecule", "example.water")

    prot = datafile("tests/data/3ZJE.pdb").read("system")

    # Take a box of water
    NWAT = 50000
    bsize = 20.0
    pos = np.random.random((NWAT, 3)) * bsize
    wat = water.copy()

    s = System.empty(NWAT, NWAT*3, box_vectors=np.eye(3)*bsize)
    for i in range(NWAT):
        wat.move_to(pos[i])
        s.add(wat)

    prot.r_array += 10
    s = merge_systems(s, prot, 0.5)

    display_system(s, 'ball-and-stick')
Exemple #17
0
def test_outline():
    from chemlab.db import ChemlabDB, CirDB
    from chemlab.io import datafile
    from chemlab.graphics.postprocessing.outline import OutlineEffect

    cdb = ChemlabDB()
    mol = cdb.get('molecule', 'example.norbornene')

    mol = datafile('tests/data/3ZJE.pdb').read('system')
    #mol = datafile('tests/data/water.gro').read('system')
    #mol = datafile('tests/data/benzene.mol').read('molecule')
    v = QtViewer()

    v.widget.camera.autozoom(mol.r_array)
    sr = v.add_renderer(AtomRenderer,
                        mol.r_array,
                        mol.type_array,
                        'impostors',
                        shading='toon')

    v.add_post_processing(OutlineEffect, 'depthnormal')
    v.add_post_processing(SSAOEffect, ssao_power=4.0)
    v.add_post_processing(FXAAEffect)
    v.add_post_processing(GammaCorrectionEffect)
    v.run()
Exemple #18
0
def test_newrdf():
    from chemlab.molsim.rdf import distance_histogram
        
    system = datafile("tests/data/rdf/cry.gro").read('system')
    #system = datafile("/home/gabriele/projects/LiCl/molfrac-0.39-48668/opt.gro").read('system')
    size = system.box_vectors[0,0]/2
    
    timer.start()
    rdf_old = rdf(system.r_array[system.type_array == 'Cl'],
                 system.r_array[system.type_array == 'Li'],
                 binsize=0.2,
                 cutoff=size,
                 periodic=system.box_vectors, normalize=False)
    timer.stop()
    
    timer.start()
    rdf_new = distance_histogram(system.r_array[system.type_array == 'Cl'],
                                 system.r_array[system.type_array == 'Li'],
                                 binsize=0.2,
                                 cutoff=size,
                                 periodic=system.box_vectors)
    timer.stop()
    1/0
    plot(rdf_new, 'r')
    plot(rdf_old[1], 'b')
    show()
Exemple #19
0
def test_bonds():
    # TODO: deprecate this shit
    from chemlab.io import datafile
    bz = datafile("tests/data/benzene.mol").read('molecule')
    na = Molecule([
        Atom('O', [0.0, 0.0, 0.0]),
        Atom('H', [0.0, 0.0, 0.0]),
        Atom('H', [0.0, 0.0, 0.0]),
    ])

    # Adding bonds
    s = System()
    with s.batch() as b:
        b.append(bz)

    assert_npequal(s.bonds, bz.bonds)
    assert_npequal(bz.bond_orders, [1, 2, 2, 1, 1, 2])
    assert_npequal(s.bond_orders, bz.bond_orders)

    s.add(bz)
    assert_npequal(
        s.type_array,
        ['C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'])
    eq_(s.dimensions['atom'], 12)
    assert_npequal(s.bonds, np.concatenate((bz.bonds, bz.bonds + 7)))

    # Reordering
    s.bonds = np.array([[0, 1], [6, 8]])
    s.reorder_molecules([1, 0])
    assert_eqbonds(s.bonds, np.array([[6, 7], [0, 2]]))

    # Selection
    ss = subsystem_from_molecules(s, [1])
    assert_npequal(ss.bonds, np.array([[0, 1]]))
Exemple #20
0
def test_pickers():
    from chemlab.graphics.pickers import SpherePicker
    from chemlab.io import datafile
    mol = datafile('/home/gabriele/projects/LiCl/interface/loafintjc-heat/equilibrium.gro').read('system')
    
    centers = [[0.0, 0.0, 0.0], [1.0, 0.0, 1.0]]
    radii = np.array([1.0, 0.5])
    colors = [[0, 255, 255, 100], [255, 255, 0, 100]]
    
    centers = mol.r_array
    radii = np.array([0.2]*mol.n_atoms)
    colors = np.array([[0, 255, 255, 255]]*mol.n_atoms)
    
    v = QtViewer()
    sr = v.add_renderer(SphereImpostorRenderer, centers, radii, colors, transparent=False)
    #sr = v.add_renderer(SphereImpostorRenderer, centers,
    #                    radii*1.5, [[255, 255, 255, 50]]*mol.n_atoms, transparent=True)

    
    sp = SpherePicker(v.widget, centers, radii)

    def on_click(evt):
        x, y = v.widget.screen_to_normalized(evt.x(), evt.y())
        print sp.pick(x, y)
    
    v.widget.clicked.connect(on_click)
    
    v.run()
Exemple #21
0
def test_bonds():
    # TODO: deprecate this shit
    from chemlab.io import datafile
    bz = datafile("tests/data/benzene.mol").read('molecule')
    na = Molecule([Atom('O', [0.0, 0.0, 0.0]),
                   Atom('H', [0.0, 0.0, 0.0]),
                   Atom('H', [0.0, 0.0, 0.0]), ])

    # Adding bonds
    s = System()
    with s.batch() as b:
        b.append(bz)

    assert_npequal(s.bonds, bz.bonds)
    assert_npequal(bz.bond_orders, [1, 2, 2, 1, 1, 2])
    assert_npequal(s.bond_orders, bz.bond_orders)

    s.add(bz)
    assert_npequal(s.type_array, ['C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C',
                                  'C', 'C', 'C'])
    eq_(s.dimensions['atom'], 12)
    assert_npequal(s.bonds, np.concatenate((bz.bonds, bz.bonds + 7)))

    # Reordering
    s.bonds = np.array([[0, 1], [6, 8]])
    s.reorder_molecules([1, 0])
    assert_eqbonds(s.bonds, np.array([[6, 7], [0, 2]]))

    # Selection
    ss = subsystem_from_molecules(s, [1])
    assert_npequal(ss.bonds, np.array([[0, 1]]))
Exemple #22
0
def test_ball_and_stick_renderer():
    from collections import defaultdict
    from chemlab.io import datafile
    from chemlab.db.cirdb import CirDB
    
    v = QtViewer()
    v.add_post_processing(SSAOEffect, kernel_radius = 0.15)
    
    #v.widget.background_color = black
    #mol = Molecule([Atom("O", [-0.499, 0.249, 0.0]),
    #                Atom("H", [-0.402, 0.249, 0.0]),
    #                Atom("H", [-0.532, 0.198, 0.10])])
    
    #mol.bonds = np.array([[0, 1],[0, 2]])
    
    #mol = CirDB().get("molecule", "moronic acid")
    mol = datafile('tests/data/3ZJE.pdb').read('molecule')
    mol.bonds = find_bonds(mol)
    
    ar = v.add_renderer(BallAndStickRenderer, mol.r_array, mol.type_array, mol.bonds)

    
    # Try without bonds
    # ar2 = v.add_renderer(BallAndStickRenderer, mol.r_array + 0.5, mol.type_array, np.array([]))
    
    v.run()
def test_merge_system():
    # take a protein
    from chemlab.io import datafile
    from chemlab.graphics import display_system

    from chemlab.db import ChemlabDB

    water = ChemlabDB().get("molecule", "example.water")

    prot = datafile("tests/data/3ZJE.pdb").read("system")

    # Take a box of water
    NWAT = 50000
    bsize = 20.0
    pos = np.random.random((NWAT, 3)) * bsize
    wat = water.copy()

    s = System.empty(NWAT, NWAT * 3, box_vectors=np.eye(3) * bsize)
    for i in range(NWAT):
        wat.move_to(pos[i])
        s.add(wat)

    prot.r_array += 10
    s = merge_systems(s, prot, 0.5)

    display_system(s, 'ball-and-stick')
Exemple #24
0
def load_trajectory(name, skip=1, format=None):
    '''Load a trajectory file into chemlab. You should call this
    command after you load a `~chemlab.core.System` through
    load_system or load_remote_system.

    '''
    df = datafile(name, format=format)
    dt, coords = df.read('trajectory', skip=skip)
    boxes = df.read('boxes')
    viewer.current_traj = coords
    viewer.frame_times = dt
    
    viewer.traj_controls.set_ticks(len(dt))
    
    def update(index):
        
        f = coords[index]        
        
        for fp in _frame_processors:
            f = fp(coords, index)

        # update the current representation
        viewer.representation.update_positions(f)
        viewer.representation.update_box(boxes[index])
        current_system().r_array = f
        current_system().box_vectors = boxes[index]
        viewer.traj_controls.set_time(dt[index])
        viewer.update()
    
    viewer.traj_controls.show()
    viewer.traj_controls.frame_changed.connect(update)
Exemple #25
0
def test_toon_shading():
    from chemlab.core.molecule import guess_bonds

    cdb = ChemlabDB()

    #mol = cdb.get('molecule', 'example.norbornene')

    mol = datafile('tests/data/3ZJE.pdb').read('system')
    v = QtViewer()
    #v.widget.post_processing = FXAAEffect(v.widget)
    #v.widget.post_processing = SSAOEffect(v.widget, kernel_size=64, kernel_radius=1.0, ssao_power=2.0)

    v.widget.camera.autozoom(mol.r_array)
    #sr = v.add_renderer(AtomRenderer, mol.r_array,
    #                    mol.type_array, 'impostors',
    #                    shading='toon')
    #sr = v.add_renderer(AtomRenderer, mol.r_array,
    #                    mol.type_array, 'polygons',
    #                    shading='toon')

    ar = v.add_renderer(BallAndStickRenderer,
                        mol.r_array,
                        mol.type_array,
                        guess_bonds(mol.r_array, mol.type_array),
                        shading='toon')

    v.run()
Exemple #26
0
def test_traj_viewer():
    tv = QtTrajectoryViewer()

    s = datafile('tests/data/water.gro').read('system')
    ar = tv.add_renderer(BallAndStickRenderer, s.r_array, s.type_array, find_bonds(s))

    times, frames = datafile('tests/data/trajout.xtc').read('trajectory')

    def update(index):
        f = frames[index]
        ar.update_positions(f)
        tv.set_text(format_time(times[index]))
        tv.widget.update()

    tv.update_function(update, len(frames))
    tv.run()
Exemple #27
0
def load_trajectory(name, skip=1, format=None):
    '''Load a trajectory file into chemlab. You should call this
    command after you load a `~chemlab.core.System` through
    load_system or load_remote_system.

    '''
    df = datafile(name, format=format)
    dt, coords = df.read('trajectory', skip=skip)
    boxes = df.read('boxes')
    viewer.current_traj = coords
    viewer.frame_times = dt

    viewer.traj_controls.set_ticks(len(dt))

    def update(index):

        f = coords[index]

        for fp in _frame_processors:
            f = fp(coords, index)

        # update the current representation
        viewer.representation.update_positions(f)
        viewer.representation.update_box(boxes[index])
        current_system().r_array = f
        current_system().box_vectors = boxes[index]
        viewer.traj_controls.set_time(dt[index])
        viewer.update()

    viewer.traj_controls.show()
    viewer.traj_controls.frame_changed.connect(update)
Exemple #28
0
def test_read_cclib():
    try:
        import cclib
    except:
        raise SkipTest
    df = datafile('tests/data/cclib/water_mp2.out', format='gamess')

    # Reading a properties that does exist
    result1 = df.read('gbasis')
    result2 = [[('S',
     [(130.7093214, 0.154328967295),
     (23.8088661, 0.535328142282),
     (6.4436083, 0.444634542185)]),
    ('S',
     [(5.0331513, -0.099967229187),
     (1.1695961, 0.399512826089),
     (0.380389, 0.70011546888)]),
    ('P',
     [(5.0331513, 0.155916274999),
     (1.1695961, 0.607683718598),
     (0.380389, 0.391957393099)])],
    [('S',
     [(3.4252509, 0.154328967295),
     (0.6239137, 0.535328142282),
     (0.1688554, 0.444634542185)])],
    [('S',
     [(3.4252509, 0.154328967295),
     (0.6239137, 0.535328142282),
     (0.1688554, 0.444634542185)])]]

    assert result1 == result2
Exemple #29
0
def load_molecule(name, format=None):
    '''Read a `~chemlab.core.Molecule` from a file.

    .. seealso:: `chemlab.io.datafile`
    
    '''    
    mol = datafile(name, format=format).read('molecule')
    display_system(System([mol]))
Exemple #30
0
def load_system(name, format=None):
    '''Read a `~chemlab.core.System` from a file.

    .. seealso:: `chemlab.io.datafile`
    
    '''
    mol = datafile(name).read('system')
    display_system(mol)
Exemple #31
0
def load_molecule(name, format=None):
    '''Read a `~chemlab.core.Molecule` from a file.

    .. seealso:: `chemlab.io.datafile`
    
    '''
    mol = datafile(name, format=format).read('molecule')
    display_system(System([mol]))
Exemple #32
0
def test_rdf_multi():
    gro_rdf = np.loadtxt("examples/gromacs_tutorial/rdf.xvg",
                         skiprows=13,
                         unpack=True)

    syst = datafile("examples/gromacs_tutorial/confout.gro").read('system')
    df = datafile("examples/gromacs_tutorial/traj.xtc")
    t, coords = df.read("trajectory")
    boxes = df.read("boxes")

    rd = rdf_multi(coords[:30], coords[:30], syst.type_array == 'O',
                   syst.type_array == 'O', boxes)

    plot(gro_rdf[0], gro_rdf[1], color='blue')
    #print len(rd[0]), len(rd[1])
    plot(rd[0], rd[1], 'red')
    show()
Exemple #33
0
def load_system(name, format=None):
    '''Read a `~chemlab.core.System` from a file.

    .. seealso:: `chemlab.io.datafile`
    
    '''
    mol = datafile(name).read('system')
    display_system(mol)
Exemple #34
0
def test_write_gromacs():
    water = Molecule([Atom('O', [0.0, 0.0, 0.0], export={'grotype': 'OW'}),
                      Atom('H', [0.1, 0.0, 0.0], export={'grotype': 'HW1'}),
                      Atom('H', [-0.03333, 0.09428, 0.0], export={'grotype': 'HW2'})],
                      export={'groname': 'SOL'})

    sys = System.empty(200, 3*200, box_vectors = np.eye(3)*2.0)
    for i in range(200):
        sys.add(water.copy())
    
    df = datafile('/tmp/dummy.gro', mode="w")
    df.write('system', sys)
    
    df = datafile('/tmp/dummy.gro')
    sread = df.read('system')
    
    assert all(sread.type_array == sys.type_array)
Exemple #35
0
def make_gromacs(simulation, directory, clean=False):
    """Create gromacs directory structure"""
    if clean is False and os.path.exists(directory):
        raise ValueError("Cannot override {}, use option clean=True".format(directory))
    else:
        shutil.rmtree(directory, ignore_errors=True)
        os.mkdir(directory)

    # Check custom simulation potential

    if simulation.potential.intermolecular.type == "custom":

        for pair in simulation.potential.intermolecular.special_pairs:
            table = to_table(simulation.potential.intermolecular.pair_interaction(*pair), simulation.cutoff)
            fname1 = os.path.join(directory, "table_{}_{}.xvg".format(pair[0], pair[1]))
            fname2 = os.path.join(directory, "table_{}_{}.xvg".format(pair[1], pair[0]))

            with open(fname1, "w") as fd:
                fd.write(table)

            with open(fname2, "w") as fd:
                fd.write(table)

        ndx = {"System": np.arange(simulation.system.n_atoms, dtype="int")}
        for particle in simulation.potential.intermolecular.particles:
            idx = simulation.system.where(atom_name=particle)["atom"].nonzero()[0]
            ndx[particle] = idx

        with open(os.path.join(directory, "index.ndx"), "w") as fd:
            fd.write(to_ndx(ndx))

    # Parameter file
    mdpfile = to_mdp(simulation)
    with open(os.path.join(directory, "grompp.mdp"), "w") as fd:
        fd.write(mdpfile)

    # Topology file
    topfile = to_top(simulation.system, simulation.potential)
    with open(os.path.join(directory, "topol.top"), "w") as fd:
        fd.write(topfile)

    # Simulation file
    datafile(os.path.join(directory, "conf.gro"), "w").write("system", simulation.system)

    return directory
Exemple #36
0
def test_rdf_multi():
    gro_rdf = np.loadtxt("examples/gromacs_tutorial/rdf.xvg",
                         skiprows=13,unpack=True)

    syst = datafile("examples/gromacs_tutorial/confout.gro").read('system')
    df = datafile("examples/gromacs_tutorial/traj.xtc")
    t, coords = df.read("trajectory")
    boxes = df.read("boxes")

    
    rd = rdf_multi(coords[:30], coords[:30],
                   syst.type_array == 'O',
                   syst.type_array == 'O',
                   boxes)
    
    plot(gro_rdf[0], gro_rdf[1], color='blue')
    #print len(rd[0]), len(rd[1])
    plot(rd[0], rd[1], 'red')
    show()
Exemple #37
0
def test_read_pdb_secondary():
    system = datafile('tests/data/pdb1g8p.ent', format='pdb').read('system')
    # assert np.all(system.secondary_structure[106:109] == 'S')
    
    eq_(system.sub(secondary_id=1).residue_name[0], 'VAL')
    assert_npequal(system.sub(secondary_id=1).residue_name, ['VAL', 'VAL', 'ASP', 'LEU'])
    
    helices = system.sub(secondary_structure='H')
    helix = helices.sub(secondary_id=helices.secondary_id[0])
    assert_npequal(helix.residue_name, ['PRO', 'PHE', 'SER', 'ALA', "ILE"])
Exemple #38
0
def test_write_gromacs():
    water = Molecule([
        Atom('O', [0.0, 0.0, 0.0], export={'grotype': 'OW'}),
        Atom('H', [0.1, 0.0, 0.0], export={'grotype': 'HW1'}),
        Atom('H', [-0.03333, 0.09428, 0.0], export={'grotype': 'HW2'})
    ],
                     export={'groname': 'SOL'})

    sys = System.empty(200, 3 * 200, box_vectors=np.eye(3) * 2.0)
    for i in range(200):
        sys.add(water.copy())

    df = datafile('/tmp/dummy.gro', mode="w")
    df.write('system', sys)

    df = datafile('/tmp/dummy.gro')
    sread = df.read('system')

    assert all(sread.type_array == sys.type_array)
Exemple #39
0
def run_gromacs(simulation, directory, clean=False):
    if clean is False and os.path.exists(directory):
        raise ValueError(
            'Cannot override {}, use option clean=True'.format(directory))
    else:
        shutil.rmtree(directory, ignore_errors=True)
        os.mkdir(directory)

    # Parameter file
    mdpfile = to_mdp(simulation)
    with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd:
        fd.write(mdpfile)

    # Topology file
    topfile = to_top(simulation.system, simulation.potential)
    with open(os.path.join(directory, 'topol.top'), 'w') as fd:
        fd.write(topfile)

    # Simulation file
    datafile(os.path.join(directory, 'conf.gro'),
             'w').write('system', simulation.system)

    process = subprocess.Popen(
        'cd {} && grompp_d && exec mdrun_d -v'.format(directory),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True)

    output_box = Textarea()
    output_box.height = '200px'
    output_box.font_family = 'monospace'
    output_box.color = '#AAAAAA'
    output_box.background_color = 'black'
    output_box.width = '800px'
    display(output_box)

    def output_function(text, output_box=output_box):
        output_box.value += text.decode('utf8')
        output_box.scroll_to_bottom()

    return AsyncCalculation(process, simulation, directory, output_function)
Exemple #40
0
def test_read_edr():
    df = datafile('tests/data/ener.edr')
    #df.read('frames')
    
    dt, temp = df.read('quantity', 'Temperature')
    unit = df.read('units', 'Temperature')
    
    try:
        df.read('quantity', 'NonExistent')
    except:
        pass
def test_read_edr():
    df = datafile("tests/data/ener.edr")
    # df.read('frames')

    dt, temp = df.read("quantity", "Temperature")
    unit = df.read("units", "Temperature")

    try:
        df.read("quantity", "NonExistent")
    except:
        pass
Exemple #42
0
def run_gromacs(simulation, directory, clean=False):
    if clean is False and os.path.exists(directory):
        raise ValueError("Cannot override {}, use option clean=True".format(directory))
    else:
        shutil.rmtree(directory, ignore_errors=True)
        os.mkdir(directory)

    # Parameter file
    mdpfile = to_mdp(simulation)
    with open(os.path.join(directory, "grompp.mdp"), "w") as fd:
        fd.write(mdpfile)

    # Topology file
    topfile = to_top(simulation.system, simulation.potential)
    with open(os.path.join(directory, "topol.top"), "w") as fd:
        fd.write(topfile)

    # Simulation file
    datafile(os.path.join(directory, "conf.gro"), "w").write("system", simulation.system)

    process = subprocess.Popen(
        "cd {} && grompp_d && exec mdrun_d -v".format(directory),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
    )

    output_box = Textarea()
    output_box.height = "200px"
    output_box.font_family = "monospace"
    output_box.color = "#AAAAAA"
    output_box.background_color = "black"
    output_box.width = "800px"
    display(output_box)

    def output_function(text, output_box=output_box):
        output_box.value += text.decode("utf8")
        output_box.scroll_to_bottom()

    return AsyncCalculation(process, simulation, directory, output_function)
Exemple #43
0
def test_write_pdb():
    water = Molecule([Atom('O', [0.0, 0.0, 0.0], export={'grotype': 'OW'}),
                      Atom('H', [0.1, 0.0, 0.0], export={'grotype': 'HW1'}),
                      Atom('H', [-0.03333, 0.09428, 0.0], export={'grotype': 'HW2'})],
                      export={'groname': 'SOL'})

    sys = System.empty(200, 3*200, box_vectors = np.eye(3) * 2.0)
    for i in range(200):
        sys.add(water.copy())
    
    df = datafile('/tmp/dummy.gro', mode="w")
    df.write("system", sys)
Exemple #44
0
def test_ssao():
    cdb = ChemlabDB()
    mol = datafile('tests/data/3ZJE.pdb').read('system')
    v = QtViewer()

    v.widget.camera.autozoom(mol.r_array)
    v.widget.post_processing.append(SSAOEffect(v.widget, kernel_size=16,
                                               kernel_radius=3.0, ssao_power=2.7))
    sr = v.add_renderer(AtomRenderer, mol.r_array, mol.type_array, 'impostors')
    #ar = v.add_renderer(BallAndStickRenderer, mol.r_array, mol.type_array, [])
    v.widget.camera.orbit_y(90)

    v.run()
Exemple #45
0
def test_ball_and_stick_renderer():

    v = QtViewer()
    v.add_post_processing(SSAOEffect, kernel_radius=0.15)

    mol = datafile('tests/data/3ZJE.pdb').read('molecule')
    mol.bonds = find_bonds(mol)

    ar = v.add_renderer(BallAndStickRenderer, mol.r_array, mol.type_array,
                        mol.bonds)
    # ar2 = v.add_renderer(BallAndStickRenderer, mol.r_array + 0.5, mol.type_array, np.array([]))

    v.run()
Exemple #46
0
def test_write_gromacs():
    water = Molecule([Atom('O', [0.0, 0.0, 0.0], name="OW"),
                      Atom('H', [0.1, 0.0, 0.0], name='HW1'),
                      Atom('H', [-0.03333, 0.09428, 0.0], name='HW2')],
                      name='SOL')

    sys = System.empty()
    with sys.batch() as b:
        for i in range(200):
            b.append(water.copy())
    sys.box_vectors = [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
    
    df = datafile('/tmp/dummy.gro', mode="w")
    df.write('system', sys)

    with assert_raises(Exception):
        df = datafile('/tmp/dummy.gro')
        df.write('system', sys)

    df = datafile('/tmp/dummy.gro')
    sread = df.read('system')
    assert all(sread.type_array == sys.type_array)
Exemple #47
0
def test_camera_autozoom():
    v = QtViewer()
    mol = Molecule([Atom("O", [-0.499, 0.249, 0.0]),
                    Atom("H", [-0.402, 0.249, 0.0]),
                    Atom("H", [-0.532, 0.198, 0.10])])
    
    s = datafile('tests/data/3ZJE.pdb').read('system')

    # To add some interaction to it
    ar = v.add_renderer(AtomRenderer, s.r_array, s.type_array, "impostors")
    v.widget.camera.autozoom(s.r_array)

    v.run()
Exemple #48
0
def test_write_pdb():
    water = Molecule([Atom('O', [0.0, 0.0, 0.0], export={'pdb.type': 'O'}),
                      Atom('H', [0.1, 0.0, 0.0], export={'pdb.type': 'H'}),
                      Atom('H', [-0.03333, 0.09428, 0.0], export={'pdb.type': 'H'})],
                      export={'groname': 'SOL'})

    sys = System.empty(200, 3*200, box_vectors = np.eye(3) * 2.0)
    for i in range(200):
        water.r_array += 0.1
        sys.add(water.copy())
    
    df = datafile('/tmp/dummy.pdb', mode="w")
    df.write("system", sys)
Exemple #49
0
def test_ssao():
    cdb = ChemlabDB()
    mol = datafile('tests/data/3ZJE.pdb').read('system')
    v = QtViewer()

    v.widget.camera.autozoom(mol.r_array)
    v.widget.post_processing.append(SSAOEffect(v.widget, kernel_size=16,
                                               kernel_radius=3.0, ssao_power=2.7))
    sr = v.add_renderer(AtomRenderer, mol.r_array, mol.type_array, 'impostors')
    #ar = v.add_renderer(BallAndStickRenderer, mol.r_array, mol.type_array, [])
    v.widget.camera.orbit_y(90)

    v.run()
Exemple #50
0
def test_camera_autozoom():
    v = QtViewer()
    mol = Molecule([Atom("O", [-0.499, 0.249, 0.0]),
                    Atom("H", [-0.402, 0.249, 0.0]),
                    Atom("H", [-0.532, 0.198, 0.10])])
    from chemlab.io import datafile
    s = datafile('tests/data/3ZJE.pdb').read('system')
    
    # To add some interaction to it
    ar = v.add_renderer(AtomRenderer, s.r_array, s.type_array, "impostors")
    v.widget.camera.autozoom(s.r_array)
    
    v.run()
Exemple #51
0
def test_geom_cartoon():
    # For this test we need chemlab
    from chemlab.io import datafile
    system = datafile('tests/data/pdb1g8p.ent', format='pdb').read('system')

    cartoon = GeomProteinCartoon(Aes(xyz=system.r_array,
                                     types=system.atom_name,
                                     secondary_id=system.secondary_id,
                                     secondary_type=system.secondary_structure))

    reps = cartoon.produce(Aes())

    eq_(reps[0]['rep_type'], 'ribbon')
Exemple #52
0
def test_write_gromacs():
    water = Molecule([Atom('O', [0.0, 0.0, 0.0], name="OW"),
                      Atom('H', [0.1, 0.0, 0.0], name='HW1'),
                      Atom('H', [-0.03333, 0.09428, 0.0], name='HW2')],
                      name='SOL')

    sys = System.empty()
    with sys.batch() as b:
        for i in range(200):
            b.append(water.copy())
    sys.box_vectors = [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
    
    df = datafile('/tmp/dummy.gro', mode="w")
    df.write('system', sys)

    with assert_raises(Exception):
        df = datafile('/tmp/dummy.gro')
        df.write('system', sys)

    df = datafile('/tmp/dummy.gro')
    sread = df.read('system')
    assert all(sread.type_array == sys.type_array)
Exemple #53
0
def test_gamma():
    cdb = ChemlabDB()

    mol = datafile('tests/data/3ZJE.pdb').read('system')
    v = QtViewer()

    v.widget.camera.autozoom(mol.r_array)
    v.widget.camera.orbit_y(3.14/3)
    sr = v.add_renderer(AtomRenderer, mol.r_array, mol.type_array,
                        'impostors', shading='phong')

    v.add_post_processing(SSAOEffect, ssao_power=4.0)
    v.add_post_processing(GammaCorrectionEffect)
    v.run()
Exemple #54
0
def test_geom_cartoon():
    # For this test we need chemlab
    from chemlab.io import datafile
    system = datafile('tests/data/pdb1g8p.ent', format='pdb').read('system')

    cartoon = GeomProteinCartoon(
        Aes(xyz=system.r_array,
            types=system.atom_name,
            secondary_id=system.secondary_id,
            secondary_type=system.secondary_structure))

    reps = cartoon.produce(Aes())

    eq_(reps[0]['rep_type'], 'ribbon')
Exemple #55
0
 def add_molecule(self,
                  path,
                  renderer='ballandstick',
                  color='default',
                  cache=True):
     try:
         mol = self.molecules[path]
     except KeyError:
         mol = self.molecules[path] = datafile(path).read('molecule')
         mol.renderer = self.RENDERERS[renderer](self, mol.r_array,
                                                 mol.type_array, mol.bonds)
         # color_scheme=self.COLORS[color])
     self.renderers.append(mol.renderer)
     self.update()
Exemple #56
0
def test_write_pdb():
    water = Molecule([Atom('O', [0.0, 0.0, 0.0], export={'pdb.type': 'O'}),
                      Atom('H', [0.1, 0.0, 0.0], export={'pdb.type': 'H'}),
                      Atom('H', [-0.03333, 0.09428, 0.0], export={'pdb.type': 'H'})],
                      export={'groname': 'SOL'})

    sys = System.empty()
    with sys.batch() as b:
        for i in range(200):
            water.r_array += 0.1
            b.append(water.copy())

    df = datafile('/tmp/dummy.pdb', mode="w")
    df.write("system", sys)