コード例 #1
0
ファイル: test_rpdf.py プロジェクト: zari277/pwtools
def test_rpdf():
    have_vmd = os.system('which vmd > /dev/null 2>&1') == 0
    for name in ['rand_3d', 'aln_ibrav0_sc', 'aln_ibrav2_sc']:
        print(("name: %s" % name))
        dd = 'files/rpdf'
        if name == 'rand_3d':
            # 2 Trajectory = 2 selections
            cell = np.loadtxt(pj(dd, name + '.cell.txt'))
            coords_frac = [
                load_old(pj(dd, name + '.coords0.txt')),
                load_old(pj(dd, name + '.coords1.txt'))
            ]
            trajs = [
                crys.Trajectory(coords_frac=cf, cell=cell)
                for cf in coords_frac
            ]
            for tr in trajs:
                assert tr.coords_frac.shape == (20, 10, 3)
                assert tr.nstep == 20
                assert tr.natoms == 10
        else:
            # one Structure
            struct = parse.CifFile(pj(dd, name + '.cif')).get_struct()
            trajs = [struct]
            cell = struct.cell

        ret = crys.rpdf(trajs, rmax=5.0, dr=0.05, pbc=True)

        # rpdf() -- compere w/ ref
        results = {
            'rad': ret[:, 0],
            'hist': ret[:, 1],
            'num_int': ret[:, 2],
            'rmax_auto': np.array(crys.rmax_smith(cell)),
        }
        for key, val in results.items():
            print(("    key: %s" % key))
            ref_fn = pj(dd, "result.%s.%s.txt" % (key, name))
            print(("    reference file: %s" % ref_fn))
            ref = np.loadtxt(ref_fn)
            if doplot:
                plt.figure()
                plt.plot(ref, '.-', label='ref')
                plt.plot(val, '.-', label='val')
                plt.legend()
                plt.title(key)
            else:
                # decimal=3 b/c ref data created w/ older implementation,
                # slight numerical noise
                np.testing.assert_array_almost_equal(ref, val, decimal=3)
                print(("    key: %s ... ok" % key))

        # API
        if name.startswith('aln_'):
            sy = np.array(trajs[0].symbols)
            ret1 = crys.rpdf(trajs, dr=0.1, amask=[sy == 'Al', sy == 'N'])
            ret2 = crys.rpdf(trajs, dr=0.1, amask=['Al', 'N'])
            aae(ret1, ret2)

    # API:
    #   [traj, traj]
    #   [traj]
    #   traj
    traj = crys.Trajectory(coords_frac=rand(100, 20, 3),
                           cell=np.identity(3) * 20,
                           symbols=['O'] * 5 + ['H'] * 15)
    ret1 = crys.rpdf([traj, traj], rmax=5.0, dr=0.05, pbc=True)
    ret2 = crys.rpdf([traj], rmax=5.0, dr=0.05, pbc=True)
    aae(ret1, ret2)
    ret3 = crys.rpdf(traj, rmax=5.0, dr=0.05, pbc=True)
    aae(ret1, ret3)

    # dmask
    ret = crys.rpdf(traj, rmax=5.0, dr=0.05, dmask='>=2.0')
    msk = ret[:, 0] >= 2.0
    imsk = np.invert(msk)
    assert (ret[msk, 1] > 0.0).any()
    assert (ret[imsk, 1] == 0.0).all()
    ret = crys.rpdf(traj, rmax=5.0, dr=0.05, dmask='{d}>=2.0')
    assert (ret[msk, 1] > 0.0).any()
    assert (ret[imsk, 1] == 0.0).all()
    ret = crys.rpdf(traj,
                    rmax=5.0,
                    dr=0.05,
                    dmask='({d} >= 1.0) & ({d} <= 3.0)')
    msk = (ret[:, 0] >= 1.0) & (ret[:, 0] <= 3.0)
    imsk = np.invert(msk)
    assert (ret[msk, 1] > 0.0).any()
    assert (ret[imsk, 1] == 0.0).all()

    if have_vmd:
        # slicefirst and API
        print("vmd_measure_gofr: slicefirst ...")
        traj = crys.Trajectory(coords_frac=rand(100, 20, 3),
                               cell=np.identity(3) * 20,
                               symbols=['O'] * 5 + ['H'] * 15)

        for first, last, step in [(0, -1, 1), (20, 80, 10)]:
            ret = []
            for sf in [True, False]:
                print("first=%i, last=%i, step=%i, slicefirst=%s" %
                      (first, last, step, sf))
                tmp = crys.vmd_measure_gofr(
                    traj,
                    dr=0.1,
                    rmax='auto',
                    sel=['all', 'all'],
                    slicefirst=sf,
                    first=first,
                    last=last,
                    step=step,
                    usepbc=1,
                    tmpdir=testdir,
                    verbose=False,
                )
                ret.append(tmp)

            assert np.allclose(ret[0][:, 0], ret[1][:, 0])
            assert np.allclose(ret[0][:, 1], ret[1][:, 1])
            assert np.allclose(ret[0][:, 2], ret[1][:, 2])

        # API call_vmd_measure_gofr()
        trajfn = pj(testdir, 'vmd_xsf_call_vmd_measure_gofr')
        data = io.write_axsf(trajfn, traj)
        ret = crys.call_vmd_measure_gofr(trajfn,
                                         dr=0.1,
                                         rmax=10,
                                         sel=['all', 'all'],
                                         fntype='xsf',
                                         first=0,
                                         last=-1,
                                         step=1,
                                         usepbc=1,
                                         datafn=None,
                                         scriptfn=None,
                                         logfn=None,
                                         tmpdir=testdir,
                                         verbose=False)

        # compare results, up to L/2 = rmax_auto = 10 = rmax_smith(cell)

        # all-all, hist will differ
        rmax = 10
        vmd = crys.vmd_measure_gofr(traj, dr=0.1, sel=['all', 'all'], rmax=10)
        pwt = crys.rpdf(traj, dr=0.1, amask=None, rmax=10)
        assert np.allclose(vmd[:-1, 0], pwt[:, 0])  # rad
        ##assert np.allclose(vmd[:-1,1], pwt[:,1]) # hist
        assert np.allclose(vmd[:-1, 2], pwt[:, 2])  # num_int

        # 2 selections, all ok
        sy = np.array(traj.symbols)
        vmd = crys.vmd_measure_gofr(traj,
                                    dr=0.1,
                                    sel=['name O', 'name H'],
                                    rmax=10)
        pwt = crys.rpdf(traj, dr=0.1, amask=[sy == 'O', sy == 'H'], rmax=10)
        assert np.allclose(vmd[:-1, 0], pwt[:, 0])  # rad
        assert np.allclose(vmd[:-1, 1], pwt[:, 1])  # hist
        assert np.allclose(vmd[:-1, 2], pwt[:, 2])  # num_int

        if doplot:
            plt.show()
コード例 #2
0
ファイル: rpdf_pw_data.py プロジェクト: elcorto/pwtools
                      tmask=val['tmask'],
                      amask=val['amask'],
                      )
        s1,s2,first,last = key.split(':')
        first = int(first)
        last = int(last)
        if s1 != 'all':
            s1 = "name %s" %s1
        if s2 != 'all':
            s2 = "name %s" %s2
        print "vmd ..."
        out_vmd = \
            crys.vmd_measure_gofr(traj, 
                                  dr=dr, 
                                  rmax='auto', 
                                  sel=[s1,s2],
                                  first=first,
                                  last=last,
                                  tmpdir=tmpdir,
                                  )
        print("rmax_auto: %f" %crys.rmax_smith(traj.cell[0,...]))
        plt.figure()
        plt.plot(out_pwt[:,0], out_pwt[:,1], 'b', label='pwtools')
        plt.plot(out_vmd[:,0], out_vmd[:,1], 'r', label='vmd')
        plt.plot(out_pwt[:,0], out_pwt[:,2], 'b')
        plt.plot(out_vmd[:,0], out_vmd[:,2], 'r')
        plt.title(key)
        plt.legend()
    
    plt.show()
コード例 #3
0
ファイル: test_rpdf.py プロジェクト: elcorto/pwtools
def test_rpdf():
    have_vmd = os.system("which vmd > /dev/null 2>&1") == 0
    for name in ["rand_3d", "aln_ibrav0_sc", "aln_ibrav2_sc"]:
        print ("name: %s" % name)
        dd = "files/rpdf"
        if name == "rand_3d":
            # 2 Trajectory = 2 selections
            cell = np.loadtxt(pj(dd, name + ".cell.txt"))
            coords_frac = [load_old(pj(dd, name + ".coords0.txt")), load_old(pj(dd, name + ".coords1.txt"))]
            trajs = [crys.Trajectory(coords_frac=cf, cell=cell) for cf in coords_frac]
            for tr in trajs:
                assert tr.coords_frac.shape == (20, 10, 3)
                assert tr.nstep == 20
                assert tr.natoms == 10
        else:
            # one Structure
            struct = parse.CifFile(pj(dd, name + ".cif")).get_struct()
            trajs = [struct]
            cell = struct.cell

        ret = crys.rpdf(trajs, rmax=5.0, dr=0.05, pbc=True)

        # rpdf() -- compere w/ ref
        results = {
            "rad": ret[:, 0],
            "hist": ret[:, 1],
            "num_int": ret[:, 2],
            "rmax_auto": np.array(crys.rmax_smith(cell)),
        }
        for key, val in results.iteritems():
            print ("    key: %s" % key)
            ref_fn = pj(dd, "result.%s.%s.txt" % (key, name))
            print ("    reference file: %s" % ref_fn)
            ref = np.loadtxt(ref_fn)
            if doplot:
                plt.figure()
                plt.plot(ref, ".-", label="ref")
                plt.plot(val, ".-", label="val")
                plt.legend()
                plt.title(key)
            else:
                # decimal=3 b/c ref data created w/ older implementation,
                # slight numerical noise
                np.testing.assert_array_almost_equal(ref, val, decimal=3)
                print ("    key: %s ... ok" % key)

        # API
        if name.startswith("aln_"):
            sy = np.array(trajs[0].symbols)
            ret1 = crys.rpdf(trajs, dr=0.1, amask=[sy == "Al", sy == "N"])
            ret2 = crys.rpdf(trajs, dr=0.1, amask=["Al", "N"])
            aae(ret1, ret2)

    # API:
    #   [traj, traj]
    #   [traj]
    #   traj
    traj = crys.Trajectory(coords_frac=rand(100, 20, 3), cell=np.identity(3) * 20, symbols=["O"] * 5 + ["H"] * 15)
    ret1 = crys.rpdf([traj, traj], rmax=5.0, dr=0.05, pbc=True)
    ret2 = crys.rpdf([traj], rmax=5.0, dr=0.05, pbc=True)
    aae(ret1, ret2)
    ret3 = crys.rpdf(traj, rmax=5.0, dr=0.05, pbc=True)
    aae(ret1, ret3)

    # dmask
    ret = crys.rpdf(traj, rmax=5.0, dr=0.05, dmask=">=2.0")
    msk = ret[:, 0] >= 2.0
    imsk = np.invert(msk)
    assert (ret[msk, 1] > 0.0).any()
    assert (ret[imsk, 1] == 0.0).all()
    ret = crys.rpdf(traj, rmax=5.0, dr=0.05, dmask="{d}>=2.0")
    assert (ret[msk, 1] > 0.0).any()
    assert (ret[imsk, 1] == 0.0).all()
    ret = crys.rpdf(traj, rmax=5.0, dr=0.05, dmask="({d} >= 1.0) & ({d} <= 3.0)")
    msk = (ret[:, 0] >= 1.0) & (ret[:, 0] <= 3.0)
    imsk = np.invert(msk)
    assert (ret[msk, 1] > 0.0).any()
    assert (ret[imsk, 1] == 0.0).all()

    if have_vmd:
        # slicefirst and API
        print "vmd_measure_gofr: slicefirst ..."
        traj = crys.Trajectory(coords_frac=rand(100, 20, 3), cell=np.identity(3) * 20, symbols=["O"] * 5 + ["H"] * 15)

        for first, last, step in [(0, -1, 1), (20, 80, 10)]:
            ret = []
            for sf in [True, False]:
                print "first=%i, last=%i, step=%i, slicefirst=%s" % (first, last, step, sf)
                tmp = crys.vmd_measure_gofr(
                    traj,
                    dr=0.1,
                    rmax="auto",
                    sel=["all", "all"],
                    slicefirst=sf,
                    first=first,
                    last=last,
                    step=step,
                    usepbc=1,
                    tmpdir=testdir,
                    verbose=False,
                )
                ret.append(tmp)

            assert np.allclose(ret[0][:, 0], ret[1][:, 0])
            assert np.allclose(ret[0][:, 1], ret[1][:, 1])
            assert np.allclose(ret[0][:, 2], ret[1][:, 2])

        # API call_vmd_measure_gofr()
        trajfn = pj(testdir, "vmd_xsf_call_vmd_measure_gofr")
        data = io.write_axsf(trajfn, traj)
        ret = crys.call_vmd_measure_gofr(
            trajfn,
            dr=0.1,
            rmax=10,
            sel=["all", "all"],
            fntype="xsf",
            first=0,
            last=-1,
            step=1,
            usepbc=1,
            datafn=None,
            scriptfn=None,
            logfn=None,
            tmpdir=testdir,
            verbose=False,
        )

        # compare results, up to L/2 = rmax_auto = 10 = rmax_smith(cell)

        # all-all, hist will differ
        rmax = 10
        vmd = crys.vmd_measure_gofr(traj, dr=0.1, sel=["all", "all"], rmax=10)
        pwt = crys.rpdf(traj, dr=0.1, amask=None, rmax=10)
        assert np.allclose(vmd[:-1, 0], pwt[:, 0])  # rad
        ##assert np.allclose(vmd[:-1,1], pwt[:,1]) # hist
        assert np.allclose(vmd[:-1, 2], pwt[:, 2])  # num_int

        # 2 selections, all ok
        sy = np.array(traj.symbols)
        vmd = crys.vmd_measure_gofr(traj, dr=0.1, sel=["name O", "name H"], rmax=10)
        pwt = crys.rpdf(traj, dr=0.1, amask=[sy == "O", sy == "H"], rmax=10)
        assert np.allclose(vmd[:-1, 0], pwt[:, 0])  # rad
        assert np.allclose(vmd[:-1, 1], pwt[:, 1])  # hist
        assert np.allclose(vmd[:-1, 2], pwt[:, 2])  # num_int

        if doplot:
            plt.show()
コード例 #4
0
ファイル: rpdf_ref.py プロジェクト: zari277/pwtools
            np.random.seed(3)
            natoms_O = 10
            natoms_H = 3
            symbols = ['O'] * natoms_O + ['H'] * natoms_H
            coords_in = np.random.rand(natoms_H + natoms_O, 3, 30)
            cell = np.identity(3) * 10
            sy = np.array(symbols)
            msk1 = sy == 'O'
            msk2 = sy == 'H'
            coords = [coords_in[msk1, ..., 10:], coords_in[msk1, ..., 10:]]
            np.savetxt(pj(dd, name + '.cell.txt'), cell)
            io.writetxt(pj(dd, name + '.coords0.txt'), coords[0])
            io.writetxt(pj(dd, name + '.coords1.txt'), coords[1])
        else:
            pp = parse.CifFile(pj(dd, name + '.cif'))
            pp.parse()
            coords = pp.coords
            cell = pp.cell
        rad, hist, num_int = crys.rpdf(
            coords,
            rmax=5.0,
            cell=cell,
            dr=0.05,
            pbc=True,
        )
        np.savetxt(pj(dd, "result.rad." + name + ".txt"), rad)
        np.savetxt(pj(dd, "result.hist." + name + ".txt"), hist)
        np.savetxt(pj(dd, "result.num_int." + name + ".txt"), num_int)
        np.savetxt(pj(dd, "result.rmax_auto." + name + ".txt"),
                   [crys.rmax_smith(cell)])
コード例 #5
0
ファイル: rpdf_ref.py プロジェクト: elcorto/pwtools
if __name__ == "__main__":

    for name in ["rand_3d", "aln_ibrav0_sc", "aln_ibrav2_sc"]:
        dd = "../files/rpdf"
        if name == "rand_3d":
            # important!
            np.random.seed(3)
            natoms_O = 10
            natoms_H = 3
            symbols = ["O"] * natoms_O + ["H"] * natoms_H
            coords_in = np.random.rand(natoms_H + natoms_O, 3, 30)
            cell = np.identity(3) * 10
            sy = np.array(symbols)
            msk1 = sy == "O"
            msk2 = sy == "H"
            coords = [coords_in[msk1, ..., 10:], coords_in[msk1, ..., 10:]]
            np.savetxt(pj(dd, name + ".cell.txt"), cell)
            io.writetxt(pj(dd, name + ".coords0.txt"), coords[0])
            io.writetxt(pj(dd, name + ".coords1.txt"), coords[1])
        else:
            pp = parse.CifFile(pj(dd, name + ".cif"))
            pp.parse()
            coords = pp.coords
            cell = pp.cell
        rad, hist, num_int = crys.rpdf(coords, rmax=5.0, cell=cell, dr=0.05, pbc=True)
        np.savetxt(pj(dd, "result.rad." + name + ".txt"), rad)
        np.savetxt(pj(dd, "result.hist." + name + ".txt"), hist)
        np.savetxt(pj(dd, "result.num_int." + name + ".txt"), num_int)
        np.savetxt(pj(dd, "result.rmax_auto." + name + ".txt"), [crys.rmax_smith(cell)])
コード例 #6
0
ファイル: rpdf_aln.py プロジェクト: zari277/pwtools
##    structs[name].savetxt()

    
    #------------------------------------------------------------------------
    # plotting
    #------------------------------------------------------------------------
    
    # For all structs, calculate rmax=5 (= rmax_auto for aln_ibrav0_sc for a
    # 2x2x2 cell) and rmax = 20 as well as pbc=True, False. Plot for 1 struct.
    plots = {}
    for struct in structs.values():
        cc = iter(['b', 'r', 'g', 'm'])
        mm = iter(['v', '^', '+', 'x'])
        for rmax in [5, 20]:
            for pbc in [True, False]:
                rmax_auto = crys.rmax_smith(struct.cell)
                out = \
                    crys.rpdf(struct, 
                              rmax=rmax, 
                              dr=0.05, 
                              pbc=pbc)
                pl = Plot()
                pl.name = struct.fnbase
                pl.rad = out[:,0]
                pl.hist = out[:,1]
                pl.num_int = out[:,2]
                pl.color = next(cc)                                                     
                pl.marker = next(mm)                                                     
                pl.leg_label = "pbc=%s, rmax=%i, rmax_auto=%.1f" %(pbc, rmax,
                                                                   rmax_auto)
                plots["%s-%i-%s" %(struct.fnbase, rmax, pbc)] = pl
コード例 #7
0
ファイル: rpdf_pw_data.py プロジェクト: zari277/pwtools
                      tmask=val['tmask'],
                      amask=val['amask'],
                      )
        s1, s2, first, last = key.split(':')
        first = int(first)
        last = int(last)
        if s1 != 'all':
            s1 = "name %s" % s1
        if s2 != 'all':
            s2 = "name %s" % s2
        print("vmd ...")
        out_vmd = \
            crys.vmd_measure_gofr(traj,
                                  dr=dr,
                                  rmax='auto',
                                  sel=[s1,s2],
                                  first=first,
                                  last=last,
                                  tmpdir=tmpdir,
                                  )
        print(("rmax_auto: %f" % crys.rmax_smith(traj.cell[0, ...])))
        plt.figure()
        plt.plot(out_pwt[:, 0], out_pwt[:, 1], 'b', label='pwtools')
        plt.plot(out_vmd[:, 0], out_vmd[:, 1], 'r', label='vmd')
        plt.plot(out_pwt[:, 0], out_pwt[:, 2], 'b')
        plt.plot(out_vmd[:, 0], out_vmd[:, 2], 'r')
        plt.title(key)
        plt.legend()

    plt.show()
コード例 #8
0
ファイル: rpdf_aln.py プロジェクト: elcorto/pwtools
##    structs[name].savetxt()

    
    #------------------------------------------------------------------------
    # plotting
    #------------------------------------------------------------------------
    
    # For all structs, calculate rmax=5 (= rmax_auto for aln_ibrav0_sc for a
    # 2x2x2 cell) and rmax = 20 as well as pbc=True, False. Plot for 1 struct.
    plots = {}
    for struct in structs.itervalues():
        cc = iter(['b', 'r', 'g', 'm'])
        mm = iter(['v', '^', '+', 'x'])
        for rmax in [5, 20]:
            for pbc in [True, False]:
                rmax_auto = crys.rmax_smith(struct.cell)
                out = \
                    crys.rpdf(struct, 
                              rmax=rmax, 
                              dr=0.05, 
                              pbc=pbc)
                pl = Plot()
                pl.name = struct.fnbase
                pl.rad = out[:,0]
                pl.hist = out[:,1]
                pl.num_int = out[:,2]
                pl.color = cc.next()                                                     
                pl.marker = mm.next()                                                     
                pl.leg_label = "pbc=%s, rmax=%i, rmax_auto=%.1f" %(pbc, rmax,
                                                                   rmax_auto)
                plots["%s-%i-%s" %(struct.fnbase, rmax, pbc)] = pl