Beispiel #1
0
def test():
    vdw = FFTVDWFunctional('vdW-DF', verbose=1)
    d = 3.9
    x = d / sqrt(3)
    L = 3.0 + 2 * 4.0
    dimer = Atoms('Ar2', [(0, 0, 0), (x, x, x)], cell=(L, L, L))
    dimer.center()
    calc = GPAW(h=0.2, xc='revPBE')
    dimer.set_calculator(calc)
    e2 = dimer.get_potential_energy()
    niter2 = calc.get_number_of_iterations()
    calc.write('Ar2.gpw')
    e2vdw = calc.get_xc_difference(vdw)
    e2vdwb = GPAW('Ar2.gpw').get_xc_difference(vdw)
    print e2vdwb - e2vdw
    assert abs(e2vdwb - e2vdw) < 1e-9
    del dimer[1]
    e = dimer.get_potential_energy()
    niter = calc.get_number_of_iterations()
    evdw = calc.get_xc_difference(vdw)

    E = 2 * e - e2
    Evdw = E + 2 * evdw - e2vdw
    print E, Evdw
    assert abs(E - -0.0048) < 6e-3, abs(E)
    assert abs(Evdw - +0.0223) < 3e-2, abs(Evdw)

    print e2, e
    equal(e2, -0.001581923, energy_tolerance)
    equal(e, -0.003224226, energy_tolerance)
Beispiel #2
0
def check_diff(g1, g2, gd, txt):
    #    print rank, txt, "shapes", g1.shape, g2.shape
    intd = gd.integrate(np.abs(g1 - g2))
    parprint(txt, "integrated diff=", intd, end="")
    maxd = np.max(np.abs(g1 - g2))
    parprint("max diff=", maxd)
    equal(intd, 0, 1.0e-8)
    equal(maxd, 0, 1.0e-9)
def test(gd1, gd2, pd1, pd2, R1, R2):
    a1 = gd1.zeros(dtype=pd1.dtype)
    a1[R1] = 1
    a2 = pd1.interpolate(a1, pd2)[0]
    x = a2[R2]
    
    a2 = gd2.zeros(dtype=pd2.dtype)
    a2[R2] = 1
    y = pd2.restrict(a2, pd1)[0][R1] * a2.size / a1.size

    equal(x, y, 1e-9)
    return x
def paired():
    xc = XC('vdW-DF')
    n = 0.3 * np.ones((1, N, N, N))
    n += 0.01 * np.cos(np.arange(N) * 2 * pi / N)
    v = 0.0 * n
    xc.calculate(gd, n, v)
    n2 = 1.0 * n
    i = 1
    n2[0, i, i, i] += 0.00002
    x = v[0, i, i, i] * gd.dv
    E2 = xc.calculate(gd, n2, v)
    n2[0, i, i, i] -= 0.00004
    E2 -= xc.calculate(gd, n2, v)
    x2 = E2 / 0.00004
    print(i, x, x2, x - x2, x / x2)
    equal(x, x2, 2e-11)
def polarized():
    xc = XC('vdW-DF')
    n = 0.04 * np.ones((2, N, N, N))
    n[1] = 0.3
    n[0] += 0.02 * np.sin(np.arange(N) * 2 * pi / N)
    n[1] += 0.2 * np.cos(np.arange(N) * 2 * pi / N)
    v = 0.0 * n
    xc.calculate(gd, n, v)
    n2 = 1.0 * n
    i = 1
    n2[0, i, i, i] += 0.00002
    x = v[0, i, i, i] * gd.dv
    E2 = xc.calculate(gd, n2, v)
    n2[0, i, i, i] -= 0.00004
    E2 -= xc.calculate(gd, n2, v)
    x2 = E2 / 0.00004
    print(i, x, x2, x - x2, x / x2)
    equal(x, x2, 1e-10)
def testSTM(calc):
    stm = SimpleStm(calc)
    stm.write_3D([1,0,0], f3dname) # single wf
    wf = stm.gd.integrate(stm.ldos)
##    print "wf=", wf

    if size == 1: # XXXX we have problem with reading plt in parallel
        stm2 = SimpleStm(f3dname)
        wf2 = stm2.gd.integrate(stm2.ldos)
        print('Integrals: written, read=', wf, wf2)
        equal(wf, wf2, 2.e-7)

##    print eigenvalue_string(calc)
    stm.write_3D(3.1, f3dname)
    wf2 = stm.gd.integrate(stm.ldos)
##    print "wf2=", wf2
    equal(wf2, 2, 0.12)

    return wf
Beispiel #7
0
def check(calc):
    wannier = Wannier(calc, nbands=6)
    wannier.localize()

    centers = wannier.get_centers()
    print centers
    expected = [[1.950, 2.376, 3.000],
                [1.950, 3.624, 3.000],
                [3.000, 3.000, 2.671],
                [3.000, 3.000, 3.329],
                [4.050, 2.376, 3.000],
                [4.050, 3.624, 3.000]]
    equal(13.7995, wannier.value, 0.016)
    for center in centers:
        i = 0
        while np.sum((expected[i] - center)**2) > 0.01:
            i += 1
            if i == len(expected):
                raise RuntimeError, 'Correct center not found'
    expected.pop(i)
Beispiel #8
0
def run(lastres=[]):
    results = []

    # Hirshfeld ----------------------------------------

    if 1:

        hd = HirshfeldDensity(calc)

        # check for the number of electrons
        expected = [[None, 10],
                    [[0, 1, 2], 10],
                    [[1, 2], 2],
                    [[0], 8],
                    ]
        #expected = [[[0, 2], 9], ]
        #expected = [[None, 10], ]
        for gridrefinement in [1, 2, 4]:
            #Test for all gridrefinements for get_all_electron_density
            parprint('grid refinement', gridrefinement)
            for result in expected:
                indicees, result = result
                full, gd = hd.get_density(indicees, gridrefinement)
                parprint('indicees', indicees, end=': ') 
                parprint('result, expected:', gd.integrate(full), result)
                if gridrefinement < 4:
                    #The highest level of gridrefinement gets wrong electron numbers
                    equal(gd.integrate(full), result, 1.e-8)
                else:
                    equal(gd.integrate(full), result, 1.e-5)

        hp = HirshfeldPartitioning(calc)
        vr = hp.get_effective_volume_ratios()
        parprint('Hirshfeld:', vr)
        if len(lastres):
            equal(vr, lastres.pop(0), 1.e-10)
        results.append(vr)

    # Wigner-Seitz ----------------------------------------

    if 1:
        ws = WignerSeitz(calc.density.finegd, mol, calc)

        vr = ws.get_effective_volume_ratios()
        parprint('Wigner-Seitz:', vr)
        if len(lastres):
            equal(vr, lastres.pop(0), 1.e-10)
        results.append(vr)

    return results
Beispiel #9
0
    # without spin
    lr = LrTDDFT(calc, xc=xc)
    lr.diagonalize()
    t1 = lr[0]
    lr_calc = lr
    ex = ExcitedState(lr, 0)
    den = ex.get_pseudo_density() * Bohr**3

    # course grids
    for finegrid in [1,0]:
        lr = LrTDDFT(calc, xc=xc, finegrid=finegrid)
        lr.diagonalize()
        t3 = lr[0]
        parprint('finegrid, t1, t3=', finegrid, t1 ,t3)
        equal(t1.get_energy(), t3.get_energy(), 5.e-4)

    # with spin
    
    lr_vspin = LrTDDFT(calc, xc=xc, nspins=2)
    singlet, triplet = lr_vspin.singlets_triplets()
    lr_vspin.diagonalize()
    # the triplet is lower, so that the second is the first singlet
    # excited state
    t2 = lr_vspin[1]
    ex_vspin = ExcitedState(lr_vspin, 1)
    den_vspin = ex_vspin.get_pseudo_density() * Bohr**3

    parprint('with virtual/wo spin t2, t1=', 
             t2.get_energy(), t1 .get_energy())
    equal(t1.get_energy(), t2.get_energy(), 5.e-7)
Beispiel #10
0
from ase import Atoms
from gpaw import GPAW
from gpaw.spinorbit import get_spinorbit_eigenvalues
from gpaw.test import equal

a = Atoms('Kr')
a.center(vacuum=3.0)

calc = GPAW(mode='pw', xc='LDA')

a.calc = calc
a.get_potential_energy()

e_n = calc.get_eigenvalues()
e_m = get_spinorbit_eigenvalues(calc)

equal(e_n[0] - e_m[0], 0.0, 1.0e-3)
equal(e_n[1] - e_m[2], 0.452, 1.0e-3)
equal(e_n[2] - e_m[4], -0.226, 1.0e-3)
Beispiel #11
0
l = 2  # d-orbitals
U_ev = 6  # U in eV
U_au = U_ev / Hartree  # U in atomic units
scale = 1  # Do not scale (does not seem to matter much)
store = 0  # Do not store (not in use yet)
for a in np.arange(2):  # Loops though all Ni atoms
    calc.hamiltonian.setups[a].set_hubbard_u(U_au, l, scale, store)  # Apply U

##############################################################################
## Make ready for scf with the DFT+U functional and converge this new system
## and get new band bag.....which should be much larger:
calc.scf.reset()
e2 = calc.get_potential_energy()
niter2 = calc.get_number_of_iterations()
Eg_Hub = band_gab(calc)

##############################################################################
## Now we expect that one effect of the Hubbard U is the opening of the band
## gab, so the band gab shall we test parameter:
## Let's compare the new and old band gab and require that is has opened by
## at least 0.2 eV
assert (Eg_Hub - Eg_non_Hub > 1.9)

energy_tolerance = 0.0004
niter_tolerance = 0
equal(e1, -28.43826, energy_tolerance)  # svnversion 5252
equal(niter1, 13, niter_tolerance)  # svnversion 5252
equal(e2, -27.70915, energy_tolerance)  # svnversion 5252
equal(niter2, 9, niter_tolerance)  # svnversion 7411
Beispiel #12
0
h =.3
box = 4.
energy_tolerance = 0.0004

l=2                         # d-orbitals
U_ev=3                      # U in eV
U_au=U_ev / Hartree   # U in atomic units
scale=1                     # Do not scale (does not seem to matter much)
store=0                     # Do not store (not in use yet)

s = Cluster([Atom('Zn')])
s.minimal_box(box, h=h)

E = {}
E_U = {}
for spin in [0, 1]:
    c = GPAW(h=h, spinpol=bool(spin), 
             charge=1, occupations=FermiDirac(width=0.1)
             )
    s.set_calculator(c)
    E[spin] = s.get_potential_energy()
    for setup in c.hamiltonian.setups:
        setup.set_hubbard_u(U_au, l, scale, store) # Apply U
    c.scf.reset()
    E_U[spin] = s.get_potential_energy()

print "E=", E
equal(E[0], E[1], energy_tolerance)
print "E_U=", E_U
equal(E_U[0], E_U[1], energy_tolerance)
bulk = Atoms("Li", pbc=True)
k = 4
g = 8
calc = GPAW(gpts=(g, g, g), kpts=(k, k, k), mode="lcao", basis="dzp")
bulk.set_calculator(calc)
e = []
niter = []
A = [2.6, 2.65, 2.7, 2.75, 2.8]
for a in A:
    bulk.set_cell((a, a, a))
    e.append(bulk.get_potential_energy())
    niter.append(calc.get_number_of_iterations())

a = np.roots(np.polyder(np.polyfit(A, e, 2), 1))[0]
print("a =", a)
equal(a, 2.63781, 0.0001)

e_ref = [-1.8677343236247692, -1.8690343169380492, -1.8654175796625045, -1.8566274574918875, -1.8432374955346396]
niter_ref = [6, 6, 6, 6, 6]

print(e)
energy_tolerance = 0.00003
niter_tolerance = 0

for i in range(len(A)):
    equal(e[i], e_ref[i], energy_tolerance)
    equal(niter[i], niter_ref[i], niter_tolerance)

wf1 = calc.get_pseudo_wave_function(kpt=3, band=0)
calc.write("Li", mode="all")
calc2 = GPAW("Li")
        poissonsolver=PoissonSolver(nn="M"),
        occupations=FermiDirac(width=0.01),
        kpts=(3, 3, 3),
        convergence={"eigenstates": 9.2e-11, "bands": 8},
        xc=xc,
        eigensolver="cg",
    )

    bulk.set_calculator(calc)
    e[xc] = {"direct": bulk.get_potential_energy()}
    niter[xc] = {"direct": calc.get_number_of_iterations()}
    print(calc.get_ibz_k_points())
    old_eigs = calc.get_eigenvalues(kpt=3)
    calc.write("Si_gs.gpw")
    del bulk
    del calc
    bulk, calc = restart("Si_gs.gpw", fixdensity=True, kpts=[[0, 0, 0], [1.0 / 3, 1.0 / 3, 1.0 / 3]])
    e[xc] = {"restart": bulk.get_potential_energy()}
    niter[xc] = {"restart": calc.get_number_of_iterations()}

    if world.rank == 0:
        os.remove("Si_gs.gpw")
    diff = calc.get_eigenvalues(kpt=1)[:6] - old_eigs[:6]
    if world.rank == 0:
        print("occ. eig. diff.", diff)
        error = max(abs(diff))
        assert error < 5e-6

    for mode in e[xc].keys():
        equal(e[xc][mode], e_ref[xc][mode], energy_tolerance)
Beispiel #15
0
#!/usr/bin/env python
from ase import Atom, Atoms
from gpaw import GPAW
from gpaw.test import equal

a = 6.
b = a / 2
mol = Atoms([Atom('O',(b, b, 0.1219 + b)),
             Atom('H',(b, 0.7633 + b, -0.4876 + b)),
             Atom('H',(b, -0.7633 + b, -0.4876 + b))],
            pbc=False, cell=[a, a, a])
calc = GPAW(gpts=(32, 32, 32), nbands=4, mode='lcao')
mol.set_calculator(calc)
e = mol.get_potential_energy()
niter = calc.get_number_of_iterations()

eref = -10.39054
err = abs(e - eref)

print 'Energy', e
print 'Ref', eref
print 'Err', err

assert err < 1e-4

equal(niter, 8, 0)
Beispiel #16
0
extra_parameters['usenewxc'] = True
from gpaw.utilities.kspot import AllElectronPotential
try:
    if 1:
        be = Atoms(symbols='Be', positions=[(0, 0, 0)])
        be.center(vacuum=5)
        calc = GPAW(gpts=(64, 64, 64), xc='LDA',
                    nbands=1)  #0.1 required for accuracy
        be.set_calculator(calc)
        e = be.get_potential_energy()
        niter = calc.get_number_of_iterations()
        #calc.write("be.gpw")

        energy_tolerance = 0.00001
        niter_tolerance = 0
        equal(e, 0.00246471, energy_tolerance)
        equal(niter, 16, niter_tolerance)

    #be, calc = restart("be.gpw")
    AllElectronPotential(calc).write_spherical_ks_potentials('bepot.txt')
    f = open('bepot.txt')
    lines = f.readlines()
    f.close()
    mmax = 0
    for l in lines:
        mmax = max(abs(eval(l.split(' ')[3])), mmax)

    print "Max error: ", mmax
    assert mmax < 0.009
except:
    extra_parameters['usenewxc'] = usenewxc
Beispiel #17
0
calc = prepare({0: 'paw', 1: 'ghost'})
system.set_calculator(calc)
e_bsse = system.get_potential_energy()
niter_bsse = calc.get_number_of_iterations()

c_nM = calc.wfs.kpt_u[0].C_nM
print('coefs')
print(c_nM)
print('energy', e_bsse)

# Reference system which is just a hydrogen
sys0 = system[0:1].copy()
calc = prepare('paw')
sys0.set_calculator(calc)
e0 = sys0.get_potential_energy()
niter0 = calc.get_number_of_iterations()
print('e0, e_bsse = ', e0, e_bsse)

# One coefficient should be very small (0.012), the other very large (0.99)
assert abs(1.0 - abs(c_nM[0, 0])) < 0.02
assert abs(c_nM[0, 1]) < 0.02
assert abs(e_bsse - e0) < 2e-3

energy_tolerance = 0.0002
niter_tolerance = 1
equal(e_bsse, 0.0287208853911, energy_tolerance)  # svnversion 5252
equal(niter_bsse, 7, niter_tolerance)  # svnversion 5252
equal(e0, 0.0299220702846, energy_tolerance)  # svnversion 5252
equal(niter0, 6, niter_tolerance)  # svnversion 5252
Beispiel #18
0
from gpaw.test import equal
from gpaw.grid_descriptor import GridDescriptor
from gpaw.spline import Spline
import gpaw.mpi as mpi
from gpaw.lfc import LocalizedFunctionsCollection as LFC

s = Spline(0, 1.0, [1.0, 0.5, 0.0])
n = 40
a = 8.0
gd = GridDescriptor((n, n, n), (a, a, a), comm=mpi.serial_comm)
c = LFC(gd, [[s], [s], [s]])
c.set_positions([(0.5, 0.5, 0.25 + 0.25 * i) for i in [0, 1, 2]])
b = gd.zeros()
c.add(b)
x = gd.integrate(b)

gd = GridDescriptor((n, n, n), (a, a, a), comm=mpi.serial_comm)
c = LFC(gd, [[s], [s], [s]])
c.set_positions([(0.5, 0.5, 0.25 + 0.25 * i) for i in [0, 1, 2]])
b = gd.zeros()
c.add(b)
y = gd.integrate(b)
equal(x, y, 1e-13)
## with fractional translations
calc = GPAW(mode=PW(),
            xc='LDA',
            kpts=(3, 3, 3),
            nbands=42,
            symmetry={'symmorphic': False},
            gpts=(20, 20, 24),
            eigensolver='rmm-diis')

atoms.set_calculator(calc)
energy_fractrans = atoms.get_potential_energy()

assert (len(calc.wfs.kd.ibzk_kc) == 7)
assert (len(calc.wfs.kd.symmetry.op_scc) == 6)

## without fractional translations
calc = GPAW(mode=PW(),
            xc='LDA',
            kpts=(3, 3, 3),
            nbands=42,
            gpts=(20, 20, 24),
            eigensolver='rmm-diis')

atoms.set_calculator(calc)
energy_no_fractrans = atoms.get_potential_energy()

assert (len(calc.wfs.kd.ibzk_kc) == 10)
assert (len(calc.wfs.kd.symmetry.op_scc) == 2)

equal(energy_fractrans, energy_no_fractrans, 1e-3)
Beispiel #20
0
rpa = RPACorrelation('N2.gpw', nfrequencies=8)
E_n2_rpa = rpa.calculate(ecut=[ecut])

N = molecule('N')
N.set_cell(N2.cell)

calc = GPAW(mode=PW(force_complex_dtype=True),
            xc='PBE',
            parallel={'domain': 1},
            eigensolver='rmm-diis')
N.set_calculator(calc)
E_n_pbe = N.get_potential_energy()

calc.diagonalize_full_hamiltonian(nbands=104, scalapack=True)
calc.write('N.gpw', mode='all')

exx = EXX('N.gpw')
exx.calculate()
E_n_hf = exx.get_total_energy()

rpa = RPACorrelation('N.gpw', nfrequencies=8)
E_n_rpa = rpa.calculate(ecut=[ecut])

print('Atomization energies:')
print('PBE: ', E_n2_pbe - 2 * E_n_pbe)
print('HF: ', E_n2_hf - 2 * E_n_hf)
print('HF+RPA: ', E_n2_hf - 2 * E_n_hf + E_n2_rpa[0] - 2 * E_n_rpa[0])

equal(E_n2_rpa - 2 * E_n_rpa, -1.68, 0.02)
Beispiel #21
0
for xcname in libxc_set:
    ra.seed(8)
    xc = XC(xcname)
    s = create_setup('N', xc)
    ni = s.ni
    nii = ni * (ni + 1) // 2
    D_p = 0.1 * ra.random(nii) + 0.4
    H_p = np.zeros(nii)

    E1 = s.xc_correction.calculate(xc, D_p.reshape(1, -1), H_p.reshape(1, -1))
    dD_p = x * ra.random(nii)
    D_p += dD_p
    dE = np.dot(H_p, dD_p) / x
    E2 = s.xc_correction.calculate(xc, D_p.reshape(1, -1))
    print xcname, dE, (E2 - E1) / x
    equal(dE, (E2 - E1) / x, 0.003)

    E2s = s.xc_correction.calculate(xc, np.array([0.5 * D_p, 0.5 * D_p]),
                                    np.array([H_p, H_p]))
    print E2, E2s
    equal(E2, E2s, 1.0e-12)

    if xcname in reference:  # compare with old gpaw
        print 'A:', E2, reference[xcname]
        equal(E2, reference[xcname], tolerance)

    if xc in reference_libxc:  # compare with reference libxc
        print 'B:', E2, reference_libxc[xcname]
        equal(E2, reference_libxc[xcname], tolerance)

    D_sp = 0.1 * ra.random((2, nii)) + 0.2
Beispiel #22
0
atoms[0].magmom = 1
calc.set(charge=-1,
         setups={'O': 'fch1s'},
         occupations=FermiDirac(0.0, fixmagmom=True))
e2 = atoms.get_potential_energy() + calc.get_reference_energy()
niter2 = calc.get_number_of_iterations()

atoms[0].magmom = 0
calc.set(charge=0,
         setups={'O': 'fch1s'},
         occupations=FermiDirac(0.0, fixmagmom=True),
         spinpol=True)
e3 = atoms.get_potential_energy() + calc.get_reference_energy()
niter3 = calc.get_number_of_iterations()

print 'Energy difference %.3f eV' % (e2 - e1)
print 'XPS %.3f eV' % (e3 - e1)

assert abs(e2 - e1 - 533.349) < 0.001
assert abs(e3 - e1 - 538.844) < 0.001

energy_tolerance = 0.00002
niter_tolerance = 0
equal(e1, -2080.0831386228238, energy_tolerance)
equal(niter1, 25, niter_tolerance)
equal(e2, -1546.7345330563153, energy_tolerance)
equal(niter2, 24, niter_tolerance)
equal(e3, -1541.2394024, energy_tolerance)
equal(niter3, 20, niter_tolerance)
Beispiel #23
0
from ase.calculators.test import numeric_force
from gpaw import GPAW, Mixer
from gpaw.test import equal

a = 4.0
n = 16
atoms = Atoms([Atom('H', [1.234, 2.345, 3.456])],
                    cell=(a, a, a), pbc=True)
calc = GPAW(nbands=1,
            gpts=(n, n, n),
            txt=None,
            mixer=Mixer(0.25, 3, 1),
            convergence={'energy': 1e-7})
atoms.set_calculator(calc)
e1 = atoms.get_potential_energy()
niter1 = calc.get_number_of_iterations()
f1 = atoms.get_forces()[0]
for i in range(3):
    f2i = numeric_force(atoms, 0, i)
    print f1[i]-f2i
    equal(f1[i], f2i, 0.00025)

energy_tolerance = 0.00006
force_tolerance = 0.0001
niter_tolerance = 0
equal(e1, -0.531042, energy_tolerance)
f1_ref = [-0.291893, -0.305174, -0.35329]
for i in range(3):
    equal(f1[i], f1_ref[i], force_tolerance)
assert 34 <= niter1 <= 35, niter1
Beispiel #24
0
                        txt=txt)
        else:
            name = 'zero_bc'
            calc = GPAW(h=0.25,
                        nbands=4,
                        mode=mode,
                        eigensolver=eigensolver,
                        txt=txt)
        Be.set_calculator(calc)
        Be.get_potential_energy()

        kss = KSSingles(calc, eps=0.9)
        # all s->p transitions at the same energy [Ha] and
        # oscillator_strength
        for ks in kss:
            equal(ks.get_energy(), kss[0].get_energy(), 5.e-3)
            equal(ks.get_oscillator_strength()[0],
                  kss[0].get_oscillator_strength()[0], 5.e-3)
            equal(ks.get_oscillator_strength()[0],
                  ks.get_oscillator_strength()[1:].sum() / 3, 1.e-15)
            for c in range(3):
                equal(ks.get_oscillator_strength()[1 + c],
                      ks.get_dipole_tensor()[c, c], 1.e-15)
        energy[name] = np.array([ks.get_energy() * Hartree
                                 for ks in kss]).mean()
        osz[name] = np.array([ks.get_oscillator_strength()[0]
                              for ks in kss]).sum()

        parprint(name + ':')
        parprint(kss)
calc = prepare({0 : 'paw', 1 : 'ghost'})
system.set_calculator(calc)
e_bsse = system.get_potential_energy()
niter_bsse = calc.get_number_of_iterations()

c_nM = calc.wfs.kpt_u[0].C_nM
print('coefs')
print(c_nM)
print('energy', e_bsse)

# Reference system which is just a hydrogen
sys0 = system[0:1].copy()
calc = prepare('paw')
sys0.set_calculator(calc)
e0 = sys0.get_potential_energy()
niter0 = calc.get_number_of_iterations()
print('e0, e_bsse = ', e0, e_bsse)

# One coefficient should be very small (0.012), the other very large (0.99)
assert abs(1.0 - abs(c_nM[0, 0])) < 0.02
assert abs(c_nM[0, 1]) < 0.02
assert abs(e_bsse - e0) < 2e-3

energy_tolerance = 0.0002
niter_tolerance = 1
equal(e_bsse, 0.0287208853911, energy_tolerance) # svnversion 5252
equal(niter_bsse, 7, niter_tolerance) # svnversion 5252
equal(e0, 0.0299220702846, energy_tolerance) # svnversion 5252
equal(niter0, 6, niter_tolerance) # svnversion 5252
Beispiel #26
0
# full information
c = GPAW(fwfname, txt=txt)
E_PBE = c.get_potential_energy()
try: # number of iterations needed in restart
    niter_PBE = c.get_number_of_iterations()
except: pass
dE = c.get_xc_difference('TPSS')
E_1 = E_PBE + dE
print "E PBE, TPSS=", E_PBE, E_1

# no wfs
c = GPAW(fname, txt=txt)
E_PBE_no_wfs = c.get_potential_energy()
try: # number of iterations needed in restart
    niter_PBE_no_wfs = c.get_number_of_iterations()
except: pass
dE = c.get_xc_difference('TPSS')
E_2 = E_PBE_no_wfs + dE
print "E PBE, TPSS=", E_PBE_no_wfs, E_2

print "diff=", E_1 - E_2
assert abs(E_1 - E_2) < 0.005

energy_tolerance = 0.00004
niter_tolerance = 0
equal(E_PBE, -5.33901, energy_tolerance)
equal(E_PBE_no_wfs, -5.33901, energy_tolerance)
equal(E_1, -5.6435, energy_tolerance)
equal(E_2, -5.64352, energy_tolerance)
assert ferr < 0.015, 'forces do not match FD check'

# Sanity check.  In HGH, the atomic Hamiltonian is constant.
# Also the projectors should be normalized
for a, dH_sp in dH_asp.items():
    dH_p = dH_sp[0]
    K_p = wfs.setups[a].K_p
    #B_ii = wfs.setups[a].B_ii
    #assert np.abs(B_ii.diagonal() - 1).max() < 1e-3
    #print 'B_ii'
    #print wfs.setups[a].B_ii
    # Actually, H2O might not be such a good test, since there'll only
    # be one element in the atomic Hamiltonian for O and zero for H.
    #print 'dH_p', dH_p
    #print 'K_p', K_p

    assert np.abs(dH_p - K_p).max() < 1e-10, 'atomic Hamiltonian changed'

    #h_ii = setup.data.h_ii
    #print 'h_ii', h_ii
    #print 'dH_ii', dH_ii

# Sanity check: HGH is normconserving
for psit_G in psit_nG:
    norm = gd.integrate(psit_G**2) # Around 1e-15 !  Surprisingly good.
    assert abs(1 - norm) < 1e-10, 'Not normconserving'

energy_tolerance = 0.00002
niter_tolerance = 0
equal(e, eref, energy_tolerance) # svnversion 5252
Beispiel #28
0
from ase.build import bulk

from gpaw import GPAW, FermiDirac
from gpaw.test import equal

a = 5.475
calc = GPAW(h=0.24,
            kpts=(4, 4, 4),
            poissonsolver={'name': 'fft'},
            occupations=FermiDirac(width=0.0),
            nbands=5)
atoms = bulk('Si', 'diamond', a=a)
atoms.set_calculator(calc)
E = atoms.get_potential_energy()
equal(E, -11.8699605591, 0.0002)
niter = calc.get_number_of_iterations()

equal(atoms.calc.get_fermi_level(), 5.17751284, 0.005)
h**o, lumo = calc.get_homo_lumo()
equal(lumo - h**o, 1.11445025, 0.002)

calc.write('si_primitive.gpw', 'all')
calc = GPAW('si_primitive.gpw',
            parallel={'domain': 1, 'band': 1},
            idiotproof=False,
            txt=None)
Beispiel #29
0
from ase import Atoms
from gpaw import GPAW
from gpaw.test import equal

h = 0.2
n = 24
a = n * h
b = a / 2
H = Atoms('H', [(b - 0.1, b, b)], pbc=True, cell=(a, a, a))
calc = GPAW(nbands=1, gpts=(n, n, n), txt='ltt.txt')
H.set_calculator(calc)
e0 = H.get_potential_energy()
for i in range(50):
    e = H.get_potential_energy()
    H.positions += (0.09123456789, 0.0423456789, 0.03456789)
equal(e, e0, 0.0006)
print e, e0, e-e0
Beispiel #30
0
    E = xc.calculate(gd, n, v)

    here = (gd.beg_c[0] <= 1 < gd.end_c[0] and
            gd.beg_c[1] <= 2 < gd.end_c[1] and
            gd.beg_c[2] <= 3 < gd.end_c[2])
    if here:
        x = v[-1, 1, 2, 3] * gd.dv
        n[-1, 1, 2, 3] += 0.000001
    Ep = xc.calculate(gd, n, v)
    if here:
        n[-1, 1, 2, 3] -= 0.000002
    Em = xc.calculate(gd, n, v)
    x2 = (Ep - Em) / 0.000002
    if here:
        print(xc.name, E, x, x2, x - x2)
        equal(x, x2, 1e-11)
        n[-1, 1, 2, 3] += 0.000001

    if 0:#xc.type == 'LDA':
        xc = XC(NonCollinearLDAKernel())
    else:
        xc = NonCollinearFunctional(xc)

    n2 = gd.zeros(4)
    n2[0] = n.sum(0)
    n2[3] = n[0] - n[1]
    E2 = xc.calculate(gd, n2)
    print(E, E2-E)
    assert abs(E2 - E) < 1e-11
    n2[1] = 0.1 * n2[3]
    n2[2] = 0.2 * n2[3]
from gpaw import GPAW
from gpaw.eigensolvers.rmm_diis_old import RMM_DIIS
from ase import Atoms
from gpaw.test import equal

atoms = Atoms("H")
atoms.center(3.0)

convergence = {"eigenstates": 1e-2, "density": 1e-2}
# Keep htpsit
calc = GPAW(nbands=2, eigensolver=RMM_DIIS(keep_htpsit=True), convergence=convergence, maxiter=20)
atoms.set_calculator(calc)
e0 = atoms.get_potential_energy()

# Do not keep htpsit
calc = GPAW(nbands=2, eigensolver=RMM_DIIS(keep_htpsit=False), convergence=convergence, maxiter=20)
atoms.set_calculator(calc)
e1 = atoms.get_potential_energy()

equal(e0, e1, 1e-12)
Beispiel #32
0
print F_ac
print
print 'Reference result'
print F_ac_ref
print
print 'Error'
print err_ac
print
print 'Max error'
print err

# ASE uses dx = [+|-] 0.001 by default,
# error should be around 2e-3.  In fact 4e-3 would probably be acceptable


equal(err, 0, 1e-3)

# Set boolean to run new FD check
fd = False

if fd:
    from ase.calculators.test import numeric_forces
    calc.set(usesymm=False)
    F_ac_fd = numeric_forces(system)
    print 'Self-consistent forces'
    print F_ac
    print 'FD'
    print F_ac_fd
    print repr(F_ac_fd)
    print F_ac - F_ac_fd, np.abs(F_ac - F_ac_fd).max()
from __future__ import print_function
from ase import Atoms
from gpaw import GPAW, restart
from gpaw.test import equal

from gpaw.utilities.kspot import AllElectronPotential
if 1:
    be = Atoms(symbols='Be',positions=[(0,0,0)])
    be.center(vacuum=5)
    calc = GPAW(gpts=(64,64,64), xc='LDA', nbands=1) #0.1 required for accuracy
    be.set_calculator(calc)
    e = be.get_potential_energy()
    niter = calc.get_number_of_iterations()
    #calc.write("be.gpw")

    energy_tolerance = 0.00001
    niter_tolerance = 0
    equal(e, 0.00246471, energy_tolerance)

#be, calc = restart("be.gpw")
AllElectronPotential(calc).write_spherical_ks_potentials('bepot.txt')
f = open('bepot.txt')
lines = f.readlines()
f.close()
mmax = 0
for l in lines:
    mmax = max(abs(eval(l.split(' ')[3])), mmax)

print("Max error: ", mmax)
assert mmax<0.009
Beispiel #34
0
    H2.get_potential_energy()

    xc='LDA'

    # without spin
    lr = LrTDDFT(calc, xc=xc)
    lr.diagonalize()
    t1 = lr[0]

    # course grids
    for finegrid in [1,0]:
        lr = LrTDDFT(calc, xc=xc, finegrid=finegrid)
        lr.diagonalize()
        t3 = lr[0]
        print 'finegrid, t1, t3=', finegrid, t1 ,t3
        equal(t1.get_energy(), t3.get_energy(), 5.e-4)

    # with spin
    
    lr_vspin = LrTDDFT(calc, xc=xc, nspins=2)
    singlet, triplet = lr_vspin.singlets_triplets()
    lr_vspin.diagonalize()
    # the triplet is lower, so that the second is the first singlet
    # excited state
    t2 = lr_vspin[1]

    print 'with virtual/wo spin t2, t1=', t2.get_energy(), t1 .get_energy()
    equal(t1.get_energy(), t2.get_energy(), 5.e-7)

    if not load:
        c_spin = GPAW(xc='PBE', nbands=2, 
Beispiel #35
0
from math import exp, pi, sqrt
import numpy as np

from gpaw.gauss import Gauss
from gpaw.test import equal
from gpaw.utilities.folder import Folder, Lorentz, Voigt  # noqa

# Gauss and Lorentz functions

width = 0.5
x = 1.5

equal(Gauss(width).get(x),
      exp(- x**2 / 2 / width**2) / sqrt(2 * pi) / width,
      1.e-15)
equal(Gauss(width).fwhm, width * np.sqrt(8 * np.log(2)), 1.e-15) 
equal(Lorentz(width).get(x),
      width / (x**2 + width**2) / pi,
      1.e-15)
equal(Lorentz(width).fwhm, width * 2, 1.e-15) 

# folder function

for func in [Gauss, Lorentz, Voigt]:
    folder = Folder(width, func(width).__class__.__name__)

    x = [0, 2]
    y = [[2, 0, 1], [1, 1, 1]]

    xl, yl = folder.fold(x, y, dx=.7)
Beispiel #36
0
                'energy': 1e-5,
                'density': 1e-5
            })

# Calculate potential energy per atom for orthogonal unitcell
atoms = hcp0001('C', a=a / sqrt(3), vacuum=d, size=(3, 2, 1), orthogonal=True)
del atoms[[1, -1]]
atoms.center(axis=0)
atoms.set_calculator(calc)

kpts_c = np.ceil(50 / np.sum(atoms.get_cell()**2, axis=1)**0.5).astype(int)
kpts_c[~atoms.get_pbc()] = 1
calc.set(kpts=kpts_c)
eppa1 = atoms.get_potential_energy() / len(atoms)
F1_av = atoms.get_forces()
equal(np.abs(F1_av).max(), 0, 5e-3)

# Redo calculation with non-orthogonal unitcell
atoms = Atoms(symbols='C2',
              pbc=(True, True, False),
              positions=[(a / 2, -sqrt(3) / 6 * a, d),
                         (a / 2, sqrt(3) / 6 * a, d)],
              cell=[(a / 2, -sqrt(3) / 2 * a, 0), (a / 2, sqrt(3) / 2 * a, 0),
                    (0, 0, 2 * d)])
atoms.set_calculator(calc)

kpts_c = np.ceil(50 / np.sum(atoms.get_cell()**2, axis=1)**0.5).astype(int)
kpts_c[~atoms.get_pbc()] = 1
calc.set(kpts=kpts_c)
eppa2 = atoms.get_potential_energy() / len(atoms)
F2_av = atoms.get_forces()
Beispiel #37
0
EHOMO = {'Be': -0.309 + 0.008, 'Ne': -0.851 + 0.098, 'Mg': -0.253 + 0.006}
eignum = {'Be': 0, 'Ne': 3, 'Mg': 0}

for xcname in ['GLLB', 'GLLBSC']:
    atoms = ['Be', 'Ne', 'Mg']
    for atom in atoms:
        # Test AllElectron GLLB
        GLLB = AllElectron(atom, xcname=xcname, scalarrel=False, gpernode=600)
        GLLB.run()

        out("Total energy", xcname + "1D", atom, ETotal[atom], GLLB.ETotal,
            "Ha")
        out("Exchange energy", xcname + "1D", atom, EX[atom], GLLB.Exc, "Ha")
        out("H**O Eigenvalue", xcname + "1D", atom, EHOMO[atom], GLLB.e_j[-1],
            "Ha")
        if xcname == 'GLLB':
            equal(GLLB.ETotal, ETotal[atom], tolerance=1e-2)
            equal(GLLB.Exc, EX[atom], tolerance=1e-2)
            equal(GLLB.e_j[-1], EHOMO[atom], tolerance=1e-2)

    print(
        "             Quanity        Method    Symbol     Ref[1]         GPAW      Unit  "
    )
    for a, b, c, d, e, f in data:
        print("%20s %10s %10s   %10.3f   %10.3f   %5s" % (a, b, c, d, e, f))

print("""References:
[1] Self-consistent approximation to the Kohn-Sham exchange potential
Gritsenko, Oleg; Leeuwen, Robert van; Lenthe, Erik van; Baerends, Evert Jan
Phys. Rev. A Vol. 51 p. 1944""")
Beispiel #38
0
             nbands=nbands,
             occupations=ZeroKelvin(True),
             convergence=convergence,
             txt=txt)
    H2.set_calculator(c)
    E_zk = H2.get_potential_energy()

    c = GPAW(h=h,
             nbands=nbands,
             occupations=FixedOccupations([[2, 0]]),
             convergence=convergence,
             txt=txt)
    H2.set_calculator(c)
    E_fo = H2.get_potential_energy()
    parprint(E_zk, E_fo)
    equal(E_zk, E_fo, 1.e-10)

if 1:
    # test spin-paired vs spin-polarized
    c = GPAW(h=h,
             nbands=nbands,
             occupations=FixedOccupations([[1, 1]]),
             convergence=convergence,
             txt=txt)
    H2.set_calculator(c)
    E_ns = H2.get_potential_energy()
if 1:
    c = GPAW(h=h,
             nbands=nbands,
             spinpol=True,
             occupations=FixedOccupations([[0.5, 0.5]] * 2),
                               frequencies=np.linspace(0, 14, 141),
                               hilbert=not True,
                               eta=0.1,
                               ecut=10,
                               truncation='wigner-seitz')
    
    a0_ws, a_ws = df_ws.get_polarizability(filename=None,
                                           direction='z')

    w0_ = 5.60491055
    I0_ = 244.693028
    w_ = 5.696528390
    I_ = 207.8
    
    w, I = findpeak(np.linspace(0, 14., 141), b0.imag)
    equal(w, w0_, 0.05)
    equal(6**3 * I / (4 * np.pi), I0_, 0.5)
    w, I = findpeak(np.linspace(0, 14., 141), a0.imag)
    equal(w, w0_, 0.05)
    equal(I, I0_, 0.5)
    w, I = findpeak(np.linspace(0, 14., 141), a0_ws.imag)
    equal(w, w0_, 0.05)
    equal(I, I0_, 0.5)
    w, I = findpeak(np.linspace(0, 14., 141), b.imag)
    equal(w, w_, 0.05)
    equal(6**3 * I / (4 * np.pi), I_, 0.5)
    w, I = findpeak(np.linspace(0, 14., 141), a.imag)
    equal(w, w_, 0.05)
    equal(I, I_, 0.5)
    # The Wigner-Seitz truncation does not give exactly the same for small cell
    w, I = findpeak(np.linspace(0, 14., 141), a_ws.imag)
Beispiel #40
0
                 [30.0, 25.0, 14.9]]))

# Wrap calculators
qsfdtd = QSFDTD(classical_material=classical_material,
                atoms=None,
                cells=(cell, 2.00),
                spacings=[1.60, 0.40],
                remove_moments=(1, 1))

# Run
energy = qsfdtd.ground_state('gs.gpw', eigensolver='cg', nbands=-1)
qsfdtd.time_propagation('gs.gpw',
                        kick_strength=[0.000, 0.000, 0.001],
                        time_step=10,
                        iterations=5,
                        dipole_moment_file='dmCl.dat')

# Restart and run
qsfdtd.write('td.gpw', mode='all')
qsfdtd.time_propagation('td.gpw',
                        kick_strength=None,
                        time_step=10,
                        iterations=5,
                        dipole_moment_file='dmCl.dat')

# Test
ref_cl_dipole_moment = [-1.01218549e-04, -3.03603883e-05, 1.86063875e-01]
tol = 1e-6
equal(qsfdtd.td_calc.hamiltonian.poisson.get_classical_dipole_moment(),
      ref_cl_dipole_moment, tol)
Beispiel #41
0
        m_xg[x] += eps
        d_xg[x] = 0.5 * f1(m_xg, xc)[0] / eps
        m_xg[x] -= 2 * eps
        d_xg[x] -= 0.5 * f1(m_xg, xc)[0] / eps
    ns_xg = np.empty((7, len(n_g)))
    ns_xg[:2] = n_xg[0] / 2
    ns_xg[2:5] = n_xg[1] / 4
    ns_xg[5:] = n_xg[2] / 2
    es_g, ds_xg = f2(ns_xg, xc)
    error = (abs(d0_xg-d_xg).max() +
            abs(es_g - e0_g).max() +
            abs(ds_xg[:2] - d0_xg[0]).max() +
            abs(ds_xg[2:5].sum(0) / 4 - d0_xg[1]).max() +
            abs(ds_xg[5:] - d0_xg[2]).max())
    #print xc.name, error
    equal(error, 0, 6e-9)
    del xc

# Numbers from old lxc_xc.py test:
na = 2.0
nb = 1.0
sigma0 = 2.0 # (0.0, 1.0, 1.0)
sigma1 = 2.0
sigma2 = 5.0 # (1.0, 2.0, 0.0)
taua=(3.*np.pi**2)**(2./3.)*na**(5./3.)/2.*sigma0
taub=(3.*np.pi**2)**(2./3.)*nb**(5./3.)/2.*sigma2

n_xg = np.array(
    [[na, nb, sigma0, sigma1, sigma2, taua, taub],
     [0.1, 0.1, 0.025, 0.025, 0.025, 0.25, 0.25],
     [0.1, 0.1, 0.125, 0.125, 0.125, 0.0025, 0.025],
Beispiel #42
0
            kpts={
                'size': (2, 2, 2),
                'gamma': True
            },
            xc='LDA',
            eigensolver='rmm-diis',
            occupations=FermiDirac(0.001))

atoms.set_calculator(calc)
e0 = atoms.get_potential_energy()

calc.diagonalize_full_hamiltonian(scalapack=True)
calc.write('BN_bulk_k2_ecut400_allbands.gpw', mode='all')

gw = G0W0('BN_bulk_k2_ecut400_allbands.gpw',
          bands=(3, 5),
          nbands=9,
          nblocks=1,
          method='GW0',
          maxiter=5,
          ecut=40)

result = gw.calculate()

gaps = [3.256, 4.746, 4.937, 4.952, 4.948, 4.946]

for i in range(result['iqp'].shape[0]):
    equal(
        np.min(result['iqp'][i, 0, :, 1]) - np.max(result['iqp'][i, 0, :, 0]),
        gaps[i], 0.03)
for mode in ['fd', 'pw']:
    print(mode)
    hydrogen = Atoms('H',
                     cell=(2.5, 3, 3.5),
                     pbc=1,
                     calculator=GPAW(txt=None, mode=mode))
    hydrogen.get_potential_energy()
    dens = hydrogen.calc.density
    ham = hydrogen.calc.hamiltonian
    ham.poisson.eps = 1e-20
    dens.interpolate_pseudo_density()
    dens.calculate_pseudo_charge()
    ham.update(dens)
    ham.get_energy(hydrogen.calc.occupations)
    y = (ham.vt_sG[0, 0, 0, 0] - ham.vt_sG[0, 0, 0, 1]) * ham.gd.dv
    x = 0.0001
    dens.nt_sG[0, 0, 0, 0] += x
    dens.nt_sG[0, 0, 0, 1] -= x
    dens.interpolate_pseudo_density()
    dens.calculate_pseudo_charge()
    ham.update(dens)
    e1 = ham.get_energy(hydrogen.calc.occupations) - ham.Ekin
    dens.nt_sG[0, 0, 0, 0] -= 2 * x
    dens.nt_sG[0, 0, 0, 1] += 2 * x
    dens.interpolate_pseudo_density()
    dens.calculate_pseudo_charge()
    ham.update(dens)
    e2 = ham.get_energy(hydrogen.calc.occupations) - ham.Ekin
    equal(y, (e1 - e2) / (2 * x), 2e-8)
Beispiel #44
0
# Sanity check.  In HGH, the atomic Hamiltonian is constant.
# Also the projectors should be normalized
for a, dH_sp in dH_asp.items():
    dH_p = dH_sp[0]
    K_p = wfs.setups[a].K_p
    #B_ii = wfs.setups[a].B_ii
    #assert np.abs(B_ii.diagonal() - 1).max() < 1e-3
    #print 'B_ii'
    #print wfs.setups[a].B_ii
    # Actually, H2O might not be such a good test, since there'll only
    # be one element in the atomic Hamiltonian for O and zero for H.
    #print 'dH_p', dH_p
    #print 'K_p', K_p

    assert np.abs(dH_p - K_p).max() < 1e-10, 'atomic Hamiltonian changed'

    #h_ii = setup.data.h_ii
    #print 'h_ii', h_ii
    #print 'dH_ii', dH_ii

# Sanity check: HGH is normconserving
for psit_G in psit_nG:
    norm = gd.integrate(psit_G**2)  # Around 1e-15 !  Surprisingly good.
    assert abs(1 - norm) < 1e-10, 'Not normconserving'

energy_tolerance = 0.000001
niter_tolerance = 0
equal(e, eref, energy_tolerance)  # svnversion 5252
equal(niter, 31, niter_tolerance)  # svnversion 5252
Beispiel #45
0
    xc = XC(name)
    for nspins in [1, 2]:
        n = rgd.zeros(nspins)
        v = rgd.zeros(nspins)
        n[:] = np.exp(-rgd.r_g**2)
        n[-1] *= 2
        E = xc.calculate_spherical(rgd, n, v)
        i = 23
        x = v[-1, i] * rgd.dv_g[i]
        n[-1, i] += 0.000001
        Ep = xc.calculate_spherical(rgd, n, v)
        n[-1, i] -= 0.000002
        Em = xc.calculate_spherical(rgd, n, v)
        x2 = (Ep - Em) / 0.000002
        print(name, nspins, E, x, x2, x - x2)
        equal(x, x2, 1e-9)
        n[-1, i] += 0.000001
        if nspins == 1:
            ns = rgd.empty(2)
            ns[:] = n / 2
            Es = xc.calculate_spherical(rgd, ns, 0 * ns)
            equal(E, Es, 1e-13)
        

N = 20
a = 1.0
gd = GridDescriptor((N, N, N), (a, a, a))

for name in ['LDA', 'PBE']:
    xc = XC(name)
    for nspins in [1, 2]:
Beispiel #46
0
        calc.write(fname)

# Check that a / h = 10 is rounded up to 12 as always:
assert (calc.wfs.gd.N_c == (12, 12, 16)).all()

############ AngularIntegral

gd = calc.density.gd
ai = AngularIntegral(H2.positions.mean(0), calc.wfs.gd, Rmax=1.5)
unity_g = gd.zeros() + 1.
average_R = ai.average(unity_g)
integral_R = ai.integrate(unity_g)
for V, average, integral, R, Rm in zip(ai.V_R, average_R, integral_R,
                                       ai.radii(), ai.radii('mean')):
    if V > 0:
        equal(average, 1, 1.e-9)
        equal(integral / (4 * pi * Rm**2), 1, 0.61)
        equal(Rm / R, 1, 0.61)

############ ExpandYl

yl = ExpandYl(H2.positions.mean(0), calc.wfs.gd, Rmax=1.5)


def max_index(l):
    mi = 0
    limax = l[0]
    for i, li in enumerate(l):
        if limax < li:
            limax = li
            mi = i
Beispiel #47
0
h=.4
q=3
spin=True

s = Atoms([Atom('Fe')])
s.center(vacuum=2.5)
convergence={'eigenstates':0.01, 'density':0.1, 'energy':0.1}

# use Hunds rules

c = GPAW(charge=q, h=h, nbands=5,
         hund=True,
         eigensolver='rmm-diis',
         occupations=FermiDirac(width=0.1),
         convergence=convergence
         )
c.calculate(s)
equal(c.get_magnetic_moment(0), 5, 0.1)

# set magnetic moment

mm = [5]
s.set_initial_magnetic_moments(mm)
c = GPAW(charge=q, h=h, nbands=5,
         occupations=FermiDirac(width=0.1, fixmagmom=True),
         convergence=convergence
         )
c.calculate(s)
equal(c.get_magnetic_moment(0), 5, 0.1)
Beispiel #48
0
    Atom('H', (x, -x, -x)),
    Atom('H', (-x, x, -x))
],
              cell=(a, a, a),
              pbc=False)

atoms.positions[:] += a / 2
calc = GPAW(h=0.25, nbands=4, convergence={'eigenstates': 7.8e-10})
atoms.calc = calc
energy = atoms.get_potential_energy()
niter = calc.get_number_of_iterations()

# The three eigenvalues e[1], e[2], and e[3] must be degenerate:
e = calc.get_eigenvalues()
print(e[1] - e[3])
equal(e[1], e[3], 9.3e-8)

energy_tolerance = 0.0003
niter_tolerance = 0
equal(energy, -23.6277, energy_tolerance)

# Calculate non-selfconsistent PBE eigenvalues:
from gpaw.xc.tools import vxc

epbe0 = e - vxc(calc)[0, 0] + vxc(calc, 'PBE')[0, 0]

# Calculate selfconsistent PBE eigenvalues:
calc.set(xc='PBE')
energy = atoms.get_potential_energy()
epbe = calc.get_eigenvalues()
b[:] = np.zeros(b.shape)

op = Laplace(gd, 1.0, 3)

if offload_enabled:
    offl_a = device.bind(a)
    offl_b = device.bind(b)

print "--------------------------------------------------------------"
print "Starting relaxation step"
relax_start = time.time()
if offload_enabled:
    op.relax(2, offl_b.array, offl_a.array, 4, 2.0 / 3.0)
else:
    op.relax(2, b, a, 4, 2.0 / 3.0)
relax_end = time.time()
print "--------------------------------------------------------------"

print "time needed: " + str(relax_end-relax_start)

s = np.sum(b)
# print "Checksum: {0}".format(s)
if gpts == 64:
    equal(s, -10.4429888082, 1e-5)
if gpts == 128:
    equal(s, -20.9047491129, 1e-5)
    
#if __name__ == '__main__':
#    print timeit.repeat('op.relax(2, b, a, 4, 2.0 / 3.0)', setup='from  __main__ import op, a, b', number=100, repeat=5)

Beispiel #50
0
LiH.set_calculator(calc)
e_LiH = LiH.get_potential_energy()
niter_LiH = calc.get_number_of_iterations()
energies, Li_orbitalweight = raw_orbital_LDOS(calc, a=0, spin=0, angular=None)
energies, H_orbitalweight = raw_orbital_LDOS(calc, a=1, spin=0, angular=None)
energies, Li_wzweight = raw_wignerseitz_LDOS(calc, a=0, spin=0)
energies, H_wzweight = raw_wignerseitz_LDOS(calc, a=1, spin=0)
n_a = calc.get_wigner_seitz_densities(spin=0)

print sweight, pdfweight
print sweight_spin
print Li_wzweight
print H_wzweight
print n_a

equal(sweight[0], 1., .06)
equal(pdfweight[0], 0., .0001)
equal(sweight_spin[0], 1.14, .06)
assert ((Li_wzweight - [.13, .93]).round(2) == 0).all()
assert ((H_wzweight - [.87, .07]).round(2) == 0).all()
assert ((Li_wzweight + H_wzweight).round(5) == 1).all()
equal(n_a.sum(), 0., 1e-5)
equal(n_a[1], .737, .001)

print Li_orbitalweight
print H_orbitalweight
#               H**O    s   py  pz  px  *s
Li_orbitalweight[0] -= [.5, .0, .6, .0, .0]
H_orbitalweight[0] -= [.7, .0, .0, .0, .0]

#              LUMO       s  py   pz  px  *s
Beispiel #51
0
from __future__ import print_function
from ase import Atom, Atoms
from gpaw import GPAW
from gpaw.test import equal

a = 4.05
d = a / 2 ** 0.5
bulk = Atoms([Atom("Al", (0, 0, 0)), Atom("Al", (0, 0, d))], cell=(4 * d, 4 * d, 2 * d), pbc=1)
n = 16
calc = GPAW(gpts=(2 * n, 2 * n, 1 * n), nbands=1 * 8, kpts=(1, 1, 4), convergence={"eigenstates": 2.3e-9}, xc="LDA")
bulk.set_calculator(calc)
e2 = bulk.get_potential_energy()
niter2 = calc.get_number_of_iterations()

bulk = bulk.repeat((1, 1, 2))
bulk.set_calculator(calc)
calc.set(nbands=16, kpts=(1, 1, 2), gpts=(2 * n, 2 * n, 2 * n))
e4 = bulk.get_potential_energy()
niter4 = calc.get_number_of_iterations()

# checks
energy_tolerance = 0.00007
niter_tolerance = 0

print(e2, e4)
equal(e4 / 2, e2, 48e-6)
equal(e2, -3.41595, energy_tolerance)
equal(e4, -6.83191, energy_tolerance)
Beispiel #52
0
calc.write('N2.gpw', mode='all')

ralda = FXCCorrelation('N2.gpw', xc='rALDA')
Ec_N2 = ralda.calculate(ecut=[50])

# N
N = Atoms('N', [(0, 0, 0)])
N.set_cell((2.5, 2.5, 3.5))
N.center()
calc = GPAW(mode=PW(force_complex_dtype=True),
            eigensolver='rmm-diis',
            xc='LDA',
            basis='dzp',
            nbands=8,
            hund=True,
            convergence={'density': 1.e-6})
N.set_calculator(calc)
N.get_potential_energy()
calc.diagonalize_full_hamiltonian(nbands=80, scalapack=scalapack2)
calc.write('N.gpw', mode='all')

ralda = FXCCorrelation('N.gpw', xc='rALDA')
Ec_N = ralda.calculate(ecut=[50])

equal(
    Ec_N2,
    -6.1651,
    0.001,
)
equal(Ec_N, -1.1085, 0.001)
Beispiel #53
0
from gpaw.xc.fxc_correlation_energy import FXCCorrelation
import numpy as np

a0  = 5.43
Ni = bulk('Ni', 'fcc')
Ni.set_initial_magnetic_moments([0.7])

kpts = monkhorst_pack((3,3,3))

calc = GPAW(mode='pw',
            kpts=kpts,
            occupations=FermiDirac(0.001),
            setups={'Ni': '10'}, 
            communicator=serial_comm)
Ni.set_calculator(calc)
E = Ni.get_potential_energy()
calc.diagonalize_full_hamiltonian(nbands=50)

rpa = RPACorrelation(calc)
E_rpa = rpa.get_rpa_correlation_energy(ecut=50,
                                       skip_gamma=True,
                                       gauss_legendre=8)

fxc = FXCCorrelation(calc, xc='RPA')
E_fxc = fxc.get_fxc_correlation_energy(ecut=50,
                                       skip_gamma=True,
                                       gauss_legendre=8)

equal(E_rpa, -7.826, 0.01)
equal(E_fxc, -7.827, 0.01)
Beispiel #54
0
bulk.set_cell((d, d, a), scale_atoms=True)
h = 0.25
calc = GPAW(h=h,
            nbands=2 * 8,
            kpts=(2, 2, 2),
            convergence={
                'eigenstates': 7.2e-9,
                'energy': 1e-5
            })
bulk.set_calculator(calc)
e0 = bulk.get_potential_energy()
niter0 = calc.get_number_of_iterations()
calc = GPAW(h=h,
            nbands=2 * 8,
            kpts=(2, 2, 2),
            convergence={
                'eigenstates': 7.2e-9,
                'energy': 1e-5,
                'bands': 5
            },
            eigensolver='dav')
bulk.set_calculator(calc)
e1 = bulk.get_potential_energy()
niter1 = calc.get_number_of_iterations()
equal(e0, e1, 5.0e-5)

energy_tolerance = 0.00004
niter_tolerance = 0
equal(e0, -6.97626, energy_tolerance)
equal(e1, -6.976265, energy_tolerance)
Beispiel #55
0
#!/usr/bin/env python
from ase import Atoms
from gpaw import GPAW, restart
from gpaw.test import equal

from gpaw.utilities.kspot import CoreEigenvalues
a = 7.0
calc = GPAW(h=0.1)
system = Atoms('Ne', calculator=calc)
system.center(vacuum=a / 2)
e0 = system.get_potential_energy()
niter0 = calc.get_number_of_iterations()
calc.write('Ne.gpw')

del calc, system

atoms, calc = restart('Ne.gpw')
calc.restore_state()
e_j = CoreEigenvalues(calc).get_core_eigenvalues(0)
assert abs(e_j[0] - (-30.344066)) * 27.21 < 0.1 # Error smaller than 0.1 eV

energy_tolerance = 0.0004
equal(e0, -0.0107707223, energy_tolerance)
Beispiel #56
0
    E = lr[n].get_energy() * Hartree
    osz = lr[n].get_oscillator_strength()
    print('Original object        :', E, osz[0])

    # Test the output of analyse
    origstdout = sys.stdout
    sys.stdout = sio = StringIO()
    lr.analyse(n)
    s = sio.getvalue()
    sys.stdout = origstdout
    match = re.findall(r'%i: E=([0-9]*\.[0-9]*) eV, f=([0-9]*\.[0-9]*)*' % n,
                       s)
    Eanalyse = float(match[0][0])
    oszanalyse = float(match[0][1])
    print('From analyse           :', Eanalyse, oszanalyse)
    equal(E, Eanalyse, 1e-3)  # Written precision in analyse
    equal(osz[0], oszanalyse, 1e-3)

    E2 = lr2[n].get_energy() * Hartree
    osz2 = lr2[n].get_oscillator_strength()
    print('Written and read object:', E2, osz2[0])

    # Compare values of original and written/read objects
    equal(E, E2, 1e-4)
    for i in range(len(osz)):
        equal(osz[i], osz2[i], 1.7e-4)

    width = 0.05
    photoabsorption_spectrum(lr,
                             spectrum_file='lrtddft3-spectrum.dat',
                             width=width)
Beispiel #57
0
    E = lr[n].get_energy() * Hartree
    osz = lr[n].get_oscillator_strength()
    print 'Original object        :', E, osz[0]

    # Test the output of analyse
    origstdout = sys.stdout
    sys.stdout = sio = StringIO()
    lr.analyse(n)
    s = sio.getvalue() 
    sys.stdout = origstdout
    match = re.findall(r'%i: E=([0-9]*\.[0-9]*) eV, f=([0-9]*\.[0-9]*)*' % n, s)
    Eanalyse = float(match[0][0])
    oszanalyse = float(match[0][1])
    print 'From analyse           :', Eanalyse, oszanalyse
    equal(E, Eanalyse, 1e-3)            # Written precision in analyse
    equal(osz[0], oszanalyse, 1e-3)

    E2 = lr2[n].get_energy() * Hartree
    osz2 = lr2[n].get_oscillator_strength()
    print 'Written and read object:', E2, osz2[0]
    
    # Compare values of original and written/read objects   
    equal(E, E2, 1e-4)
    for i in range(len(osz)):
        equal(osz[i], osz2[i], 1.7e-4)

    width = 0.05
    photoabsorption_spectrum(lr, 
                             spectrum_file = 'lrtddft3-spectrum.dat', 
                             width = width)
Beispiel #58
0
    h2 = Atoms('H2', [[0, 0, 0], [0, 0, d]])
    h2.center(vacuum=2)
    h2.calc = GPAW(txt='H2-' + xc + '.txt', convergence=c)
    h2.get_potential_energy()
    h2.calc.set(xc=xc)
    h2.get_potential_energy()
    h2.get_forces()
    ens = BEEFEnsemble(h2.calc)
    e_h2 = ens.get_ensemble_energies()

    # H atom:
    h = Atoms('H', cell=h2.cell, magmoms=[1])
    h.center()
    h.calc = GPAW(txt='H-' + xc + '.txt', convergence=c)
    h.get_potential_energy()
    h.calc.set(xc=xc)
    h.get_potential_energy()
    ens = BEEFEnsemble(h.calc)
    e_h = ens.get_ensemble_energies()

    # binding energy
    ae = 2 * e_h - e_h2
    print(ae.mean(), ae.std())
    equal(ae.mean(), E0, 0.015)
    equal(ae.std(), dE0, 0.015)

ens.write('H')
world.barrier()
energies = readbee('H')
equal(abs(energies - e_h).max(), 0, 1e-12)
## with fractional translations
calc = GPAW(mode=PW(),
            xc='LDA',
            kpts=(3, 3, 3),
            nbands=42,
            symmetry={'symmorphic': False},
            gpts=(20, 20, 24),
            eigensolver='rmm-diis')

atoms.set_calculator(calc)
energy_fractrans = atoms.get_potential_energy()

assert(len(calc.wfs.kd.ibzk_kc) == 7)
assert(len(calc.wfs.kd.symmetry.op_scc) == 6)

## without fractional translations
calc = GPAW(mode=PW(),
            xc='LDA',
            kpts=(3, 3, 3),
            nbands=42,
            gpts=(20, 20, 24),
            eigensolver='rmm-diis')

atoms.set_calculator(calc)
energy_no_fractrans = atoms.get_potential_energy()

assert(len(calc.wfs.kd.ibzk_kc) == 10)
assert(len(calc.wfs.kd.symmetry.op_scc) == 2)

equal(energy_fractrans, energy_no_fractrans, 1e-3)
# 1 potential
if True:
    if txt:
        print('################## 1 potential')
    cp1 = ConstantPotential(-1.0 / Hartree)
    c1 = GPAW(h=0.3, nbands=-2, external=cp1, convergence=convergence, txt=txt)
    c1.calculate(H2)

for i in range(c00.get_number_of_bands()):
    f00 = c00.get_occupation_numbers()[i]
    if f00 > 0.01:
        e00 = c00.get_eigenvalues()[i]
        e1 = c1.get_eigenvalues()[i]
        print('Eigenvalues no pot, expected, error=', e00, e1 + 1,
              e00 - e1 - 1)
        equal(e00, e1 + 1., 0.007)

E_c00 = c00.get_potential_energy()
niter_c00 = c00.get_number_of_iterations()

E_c1 = c1.get_potential_energy()
niter_c1 = c1.get_number_of_iterations()

DeltaE = E_c00 - E_c1
print('Energy diff, expected, error=', DeltaE, nelectrons, DeltaE - nelectrons)
equal(DeltaE, nelectrons, 0.002)

energy_tolerance = 0.00001
niter_tolerance = 0
#equal(E_c00, 10.4409370467, energy_tolerance) # svnversion 5252
#equal(niter_c00, 14, niter_tolerance) # svnversion 5252