def test():
    atoms, calc = restart(
        '/home/hexu/projects/jiahui/STO_bulk_LCAO/STO3_gs.gpw',
        fixdensity=True)
    kpoints = calc.get_ibz_kpoints()
    H, S = get_lcao_hamiltonian()
    desc = calc.setups[0].basis.get_description()
Beispiel #2
0
def gpawRestart(calc):
    from gpaw import restart, PW, Davidson, Mixer, MixerSum, FermiDirac
    return restart(
        'preCalc_inp.gpw',
        mode=PW(calc.pw),
        xc=calc.xc,
        kpts={
            'density': calc.kpt,
            'gamma': True
        } if isinstance(calc.kpt, int) else calc.kpt,
        spinpol=calc.magmom > 0,
        convergence={'energy': calc.eConv}  #eV/electron
        ,
        mixer=((MixerSum(beta=calc.mixing, nmaxold=calc.nmix, weight=100))
               if calc.magmom > 0 else
               (Mixer(beta=calc.mixing, nmaxold=calc.nmix, weight=100))),
        maxiter=calc.maxsteps,
        nbands=-1 * calc.nbands,
        occupations=FermiDirac(calc.sigma),
        setups='sg15'  #(pspDict[calc.psp]).pthFunc[cluster]
        ,
        eigensolver=Davidson(5),
        poissonsolver=
        None  # {'dipolelayer': 'xy'} if isinstance(self,SurfaceJob) else None
        ,
        txt=str(calc) + '.txt',
        symmetry={'do_not_symmetrize_the_density':
                  True}  #ERROR IN LI bcc 111 surface
    )
Beispiel #3
0
    def read(self, filename):

        self.lrtddft = LrTDDFT(filename + '/' + filename + '.lr.dat.gz')
        self.atoms, self.calculator = restart(
            filename + '/' + filename, communicator=self.world)
        E0 = self.calculator.get_potential_energy()

        f = open(filename + '/' + filename + '.exst', 'r')
        f.readline()
        self.d = f.readline().replace('\n', '').split()[1]
        indextype = f.readline().replace('\n', '').split()[1]
        if indextype == 'UnconstraintIndex':
            iex = int(f.readline().replace('\n', '').split()[1])
            self.index = UnconstraintIndex(iex)
        else:
            direction = f.readline().replace('\n', '').split()[1]
            if direction in [str(0), str(1), str(2)]:
                direction = int(direction)
            else:
                direction = None

            val = f.readline().replace('\n', '').split()
            if indextype == 'MinimalOSIndex':

                self.index = MinimalOSIndex(float(val[1]), direction)
            else:
                emin = float(val[2])
                emax = float(val[3].replace(']', ''))
                self.index = MaximalOSIndex([emin, emax], direction)

        index = self.index.apply(self.lrtddft)
        self.results['energy'] = E0 + self.lrtddft[index].energy * Hartree
        self.lrtddft.set_calculator(self.calculator)
def createCubeFiles():
    atoms, calc = gp.restart( "CO.gpw" )
    nbands = calc.get_number_of_bands()
    for band in range(nbands):
        wf = calc.get_pseudo_wave_function(band=band)
        fname = "wavefuncttionCO_%d.cube"%(band)
        ase.io.write( fname, atoms, data=wf )
Beispiel #5
0
    def gpawRestart(self):
        from gpaw import restart, PW, Davidson, Mixer, MixerSum, FermiDirac

        spinpol = any([x > 0 for x in self.magmomsinit()])

        return restart(
            'preCalc_inp.gpw',
            mode=PW(self.pw),
            xc=self.xc,
            kpts=self.kpt(),
            spinpol=spinpol,
            convergence={'energy': self.econv()}  #eV/electron
            ,
            mixer=(
                (MixerSum(beta=self.mixing(), nmaxold=self.nmix(), weight=100))
                if spinpol else
                (Mixer(beta=self.mixing(), nmaxold=self.nmix(), weight=100))),
            maxiter=self.maxstep(),
            nbands=self.nbands(),
            occupations=FermiDirac(self.sigma()),
            setups=self.psp  #(pspDict[calc.psp]).pthFunc[cluster]
            ,
            eigensolver=Davidson(5),
            poissonsolver=
            None  # {'dipolelayer': 'xy'} if isinstance(self,SurfaceJob) else None
            ,
            txt='%d_%s.txt' % (self.pw, self.xc),
            symmetry={'do_not_symmetrize_the_density':
                      True})  #ERROR IN LI bcc 111 surface
Beispiel #6
0
def file_ok(gpw_file):
    try:
        atoms, calc = restart(gpw_file)
        atoms.get_potential_energy()
    except KeyError as exc:
        print(str(exc))
        return False
    return True
Beispiel #7
0
def add_efield(fname, efield=0):
    printit('Starting Efield calculation for efiled = {}'.format(efield))
    atom, calc = restart('gs_' + fname + '.gpw')
    calc.set(txt='gs_efield_{}.txt'.format(efield))
    calc.set(external=ConstantElectricField(efield, [0, 0, 1]))
    calc.get_potential_energy()
    calc.write('gs_' + fname + '_{}.gpw'.format(efield), mode='all')
    printit('Efield GS calculation done')
    gap, p1, p2 = get_gap(calc)
    printit("{} {} {} {}".format(efield, gap, p1, p2), fname="gaps.dat")
    printit("efield={} gap={}".format(efield, gap))
Beispiel #8
0
def main():
    molecule, calc = gp.restart("H2.gpw", txt="H2-relaxed.txt")
    print("Getting potential energy")
    e2 = molecule.get_potential_energy()
    d0 = molecule.get_distance(0, 1)

    # Find the minimum energy by Quasi-Newton
    relax = QuasiNewton(molecule, logfile="qn.log")
    relax.run(fmax=0.05)
    d1 = molecule.get_distance(0, 1)

    print("Original bondlength: %.2f" % (d0))
    print("Optimized bondlength: %.2f" % (d1))
Beispiel #9
0
def read(fn, gridref=4, spin_flag=False):
    """Read in from a GPAW restart file, this function requires gpaw.
    args:
        fn: filename
        gridref: the gridrefinemnet flag for get_all_electron_density method
        spin_flag: whether to read the spin density also
    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    Future: remove gpaw dependancy?
    """
    from gpaw import restart

    prefix, filename = os.path.split(fn)
    prefix = os.path.join(prefix, '')
    _, calc = restart(fn)
    return read_calc(calc, gridref, spin_flag, fn, prefix)
Beispiel #10
0
def getXCcontribs(jobID):
    jobObject = db2BulkJob(jobID)
    if jobObject.dftCode == 'gpaw':
        from gpaw import restart
        from gpaw.xc.bee import BEEFEnsemble
        atoms, calc = restart('inp.gpw',
                              setups='sg15',
                              xc='mBEEF',
                              convergence={'energy': 5e-4},
                              txt='mbeef.txt')
        atoms.get_potential_energy()
        beef = BEEFEnsemble(calc)
        return beef.mbeef_exchange_energy_contribs()
    else:
        return np.zeros((8, 8))
	def run_task(self,fw_spec): 

		jobID = fw_spec['jobID']
		job   = db2object(jobID)
	
		if job.dftcode == 'gpaw':
			from gpaw        import restart
			from gpaw.xc.bee import BEEFEnsemble
			atoms,calc = restart('inp.gpw', setups='sg15', xc='mBEEF', convergence={'energy': 5e-4}, txt='mbeef.txt')
			atoms.get_potential_energy()
			beef = BEEFEnsemble(calc)
			xcContribs = beef.mbeef_exchange_energy_contribs()
		else: 
			xcContribs = np.zeros((8,8))

		return FWAction( stored_data={'xcContribs': xcContribs}
						,mod_spec=[{'_push': {'xcContribs': xcContribs}}])
	def run_task(self,fw_spec): 
		from gpaw        import restart
		from gpaw.xc.bee import BEEFEnsemble
		job,params,atoms = initialize(fw_spec)
		atoms.set_calculator(job.PBEcalc())
		atoms.get_potential_energy()
		atoms.calc.write('inp.gpw', mode='all') 

		atoms,calc = restart('inp.gpw', setups='sg15', xc='mBEEF', convergence={'energy': 5e-4}, txt='mbeef.txt')
		atoms.get_potential_energy()
		beef 		= BEEFEnsemble(calc)
		xcContribs 	= beef.mbeef_exchange_energy_contribs()
		ase.io.write('final.traj',atoms)
		resultDict 	= misc.mergeDicts([params,trajDetails(ase.io.read('final.traj'))
									,{'xcContribs': pickle.dumps(xcContribs)}])

		with open('result.json', 'w') as outfile:   json.dumps(resultDict, outfile)
		return fireworks.core.firework.FWAction( stored_data=resultDict)
Beispiel #13
0
def read_and_check_results():
    """Read energies from .gpw files."""
    fd = sys.stdout
    E = {}
    fd.write('E = {')
    for formula in systems:
        try:
            atoms, calc = restart(formula, txt=None)
        except (KeyError, IOError):
            #print formula
            continue
    
        nspins = calc.get_number_of_spins()
        fa = calc.get_occupation_numbers(spin=0)
        assert ((fa.round() - fa)**2).sum() < 1e-14
        if nspins == 2:
            fb = calc.get_occupation_numbers(spin=1)
            assert ((fb.round() - fb)**2).sum() < 1e-9
            if len(atoms) == 1:
                M = data[formula]['magmom']
            else:
                M = sum(data[formula]['magmoms'])
            assert abs((fa-fb).sum() - M) < 1e-9
        e = calc.get_potential_energy()
        fd.write("'%s': %.3f, " % (formula, e))
        fd.flush()
        E[formula] = e

    dE = [] # or maybe {} ?
    fd.write('}\ndE = [')
    
    for formula in dimers:
        try:
            trajectory = PickleTrajectory(formula + '.traj', 'r')
        except IOError:
            continue
        energies = [a.get_potential_energy() for a in trajectory]
        dE.append((formula, (energies)))
        fd.write("('%s', (" % formula)
        fd.write(', '.join(['%.4f' % (energy - E[formula])
                            for energy in energies]))
        fd.write(')),\n      ')
    fd.write(']\n')
    return E, dE
Beispiel #14
0
def read_and_check_results():
    """Read energies from .gpw files."""
    fd = sys.stdout
    E = {}
    fd.write('E = {')
    for formula in systems:
        try:
            atoms, calc = restart(formula, txt=None)
        except (KeyError, IOError):
            #print formula
            continue
    
        nspins = calc.get_number_of_spins()
        fa = calc.get_occupation_numbers(spin=0)
        assert ((fa.round() - fa)**2).sum() < 1e-14
        if nspins == 2:
            fb = calc.get_occupation_numbers(spin=1)
            assert ((fb.round() - fb)**2).sum() < 1e-9
            if len(atoms) == 1:
                M = data[formula]['magmom']
            else:
                M = sum(data[formula]['magmoms'])
            assert abs((fa-fb).sum() - M) < 1e-9
        e = calc.get_potential_energy()
        fd.write("'%s': %.3f, " % (formula, e))
        fd.flush()
        E[formula] = e

    dE = [] # or maybe {} ?
    fd.write('}\ndE = [')
    
    for formula in dimers:
        try:
            trajectory = PickleTrajectory(formula + '.traj', 'r')
        except IOError:
            continue
        energies = [a.get_potential_energy() for a in trajectory]
        dE.append((formula, (energies)))
        fd.write("('%s', (" % formula)
        fd.write(', '.join(['%.4f' % (energy - E[formula])
                            for energy in energies]))
        fd.write(')),\n      ')
    fd.write(']\n')
    return E, dE
Beispiel #15
0
 def __init__(self, atoms=None, calc=None, gpw_fname=None):
     if not _has_gpaw:
         raise ImportError("GPAW was not imported. Please install gpaw.")
     if atoms is None or calc is None:
         atoms, calc=restart(gpw_fname, fixdensity=False,  txt='nscf.txt')
     self.atoms=atoms
     self.calc=calc
     #self.wfs=self.calc.wfs
     #self.h=self.calc.hamiltonian
     #self.kpt_u = self.wfs.kpt_u
     self.cell = self.atoms.get_cell()
     #self.wann_centers=get_bf_centers(self.atoms)
     self.positions=self.cell.scaled_positions(get_bf_centers(self.atoms))
     #if calc.get_spin_polarized():
     #    self.positions=np.vstack([self.positions, self.positions])
     self.efermi=self.calc.get_fermi_level()
     self.R2kfactor= -2.0j* np.pi
     #self.nbasis=len(self.positions)
     self.norb=len(self.positions)
     self.nbasis=self.norb*2
Beispiel #16
0
def band_calc(fname):
    printit('Starting Band structure calculation')
    atom, calc = restart(fname)
    path = atom.cell.bandpath([[0, 0, 0], [0, 0.5, 0], [0, 1, 0]], npoints=100)
    calc.set(fixdensity=True)
    calc.set(symmetry='off')
    calc.set(kpts=path.kpts)
    calc.get_potential_energy()
    printit('Band structure calculation Done')
    gap, p1, p2 = gap(calc)
    printit("{} {}".format(fname, gap), fname="gaps.dat")
    e_kn = np.array([calc.get_eigenvalues(k) for k in range(len(kpts))])
    efermi = calc.get_fermi_level()
    plt.figure(figsize=(5, 6))
    x = path.get_linear_kpoint_axis()[0]
    for i in range(nbands):
        plt.plot(x, e_kn[:, i])
    for j in path.get_linear_kpoint_axis()[1]:
        plt.plot([0, X[-1]], [0, 0], 'k-')
    plt.axis(xmin=0, xmax=X[-1], ymin=emin, ymax=emax)
    plt.tight_layout()
    plt.savefig(fname + '.png', dpi=300)
Beispiel #17
0
def test(atoms):
    e0 = atoms.get_potential_energy()
    f0 = atoms.get_forces()
    m0 = atoms.get_magnetic_moments()
    eig00 = atoms.calc.get_eigenvalues(spin=0)
    eig01 = atoms.calc.get_eigenvalues(spin=1)
    wf0 = atoms.calc.get_pseudo_wave_function(band=1)
    # Write the restart file(s):
    atoms.calc.write('tmp1.gpw')
    atoms.calc.write('tmp2.gpw', 'all')

    # Try restarting:
    atoms, calc = restart('tmp2.gpw', txt=None)
    wf1 = calc.get_pseudo_wave_function(band=1)
    e1 = atoms.get_potential_energy()
    f1 = atoms.get_forces()
    m1 = atoms.get_magnetic_moments()
    eig10 = calc.get_eigenvalues(spin=0)
    eig11 = calc.get_eigenvalues(spin=1)
    print(e0, e1)
    equal(e0, e1, 1e-10)
    print(f0, f1)
    for ff0, ff1 in zip(f0, f1):
        err = np.linalg.norm(ff0 - ff1)
        assert err <= 1e-10
    print(m0, m1)
    for mm0, mm1 in zip(m0, m1):
        equal(mm0, mm1, 1e-10)
    print('A', eig00, eig10)
    for eig0, eig1 in zip(eig00, eig10):
        equal(eig0, eig1, 1e-10)
    print('B', eig01, eig11)
    for eig0, eig1 in zip(eig01, eig11):
        equal(eig0, eig1, 1e-10)
    equal(abs(wf1 - wf0).max(), 0, 1e-14)

    # Check that after restart everything is writable
    calc.write('tmp3.gpw')
    calc.write('tmp4.gpw', 'all')
def XCcontribsScript():
    import cPickle, json, ase
    from gpaw import restart
    from gpaw.xc.bee import BEEFEnsemble
    params, optAtoms = initialize(
    )  # Remove old .out/.err files, load from fw_spec, and write 'init.traj'
    pbeParams = copy.deepcopy(params)
    pbeParams['xc'] = 'PBE'

    atoms.set_calculator(makeCalc(pbeParams))
    atoms.get_potential_energy()
    atoms.calc.write('inp.gpw', mode='all')

    atoms, calc = restart('inp.gpw',
                          setups='sg15',
                          xc='mBEEF',
                          convergence={'energy': 5e-4},
                          txt='mbeef.txt')
    atoms.get_potential_energy()
    beef = BEEFEnsemble(calc)
    xcContribs = beef.mbeef_exchange_energy_contribs()
    ################################
    print "Storing Results..."
    #-------------------------------
    ase.io.write('final.traj', atoms)
    resultDict = mergeDicts([
        params,
        trajDetails(ase.io.read('final.traj')), {
            'xcContribs': cPickle.dumps(xcContribs)
        }
    ])
    with open('result.json', 'w') as outfile:
        outfile.write(json.dumps(resultDict))
    if rank() == 0:
        with open('result.json', 'r') as outfile:
            json.loads(outfile.read())  #test that dictionary isn't 'corrupted'
        log(params, atoms)
    return 0
Beispiel #19
0
 def load_gpaw_restart(
     self,
     infile,
     **kwargs,
 ):
     from gpaw import restart
     atoms, calc = restart(infile)
     try:  # check if the wavefunction exists
         wfs = calc.wfs
     except:
         print('ERROR: No wavefunctions found in the GPAW restart file {}'.
               format(filename))
         print("Make sure to write the GPAW file with mode='all'!")
         raise NoWavefunctionFound
     #end try
     if self.density:
         # run SCF to re-populate density
         print('Running SCF to re-populate density')
         calc.scf.converged = False
         calc.results.pop('energy')
         E = calc.get_potential_energy()
     #end def
     self.load_gpaw_calc(calc, atoms)
# Find optimal k parameter
k, calc = convergeK(atoms, tol=1e-4, kstart=4)
print(f'Optimal k-parameter: k={k}')

# Perform a ground state energy calculation to get the ground state density
atoms.get_potential_energy()

# Save the calculator
calc.write('Al_calc.gpw')
# if world.rank == 0:
print('Calculator saved')

#### Electronic band structure
# if world.rank == 0:
print('Electronic structure calculation started')
atoms, calc = restart('Al_calc.gpw')
# kpts = {'size': (60,60,60), 'path': 'GXWKGLUWLK,UX'}
kpts = {'path': 'GXWKGLUWLK,UX', 'npoints': 60}
calc.set(kpts = kpts, fixdensity=True, symmetry='off')

# calc = GPAW(
#     'Al_calc.gpw',
#     nbands=16,                              # Include more bands than convergence since metallic
#     fixdensity=True,                        # Fixate the density
#     symmetry='off',                         # Check all points along the path
#     kpts={'path': 'GXWKL', 'npoints': 60},
#     convergence={'bands': 8},
#     txt='Al_calc.txt'
# )
# calc.get_potential_energy()  # Converge the system
# # if world.rank == 0:
    calc.write(formula)
    # add total energy to users tags
    cmr_params['U_potential_energy'] = e
    # write the information 'as in' corresponding trajectory file
    # plus cmr_params into cmr file
    write(cmrfile, system, cmr_params=cmr_params)

    del calc

if recalculate:

    # now calculate PBE energies on LDA orbitals

    # molecule
    formula = symbol + '2'
    system, calc = restart(formula, txt=None)

    ediff = calc.get_xc_difference('PBE')

    cmrfile = formula + '.cmr'

    # add new results to the cmrfile
    data = cmr.read(cmrfile)
    data.set_user_variable('U_potential_energy_PBE', data['U_potential_energy'] + ediff)
    data.write(cmrfile)

    del calc

    # atom
    formula = symbol
    system, calc = restart(formula, txt=None)
             is_initial = Is_initial)

if __name__ == "__main__":


    #Main arguments:
    e_cut = 500
    nbands = -25
    xc = 'PBE'
    k_pts = 10
    smear = 0.1
    system_name = str(sys.argv[7])

    if os.path.isfile('./' + system_name + '_relaxed.gpw'):
        #Recover past done calculations if available
        bulk_mat, calc = restart(system_name + '_relaxed.gpw', txt = None)
        bulk_mat.set_calculator(calc)

    else:
        #Initialize new calculations
        db = connect(sys.argv[8])
        bulk_mat = db.get_atoms(id = sys.argv[9])

        calc = GPAW(mode=PW(e_cut), nbands = nbands,
                    xc='PBE', spinpol=True, kpts=(k_pts,k_pts,k_pts),
                    occupations=FermiDirac(smear), txt=system_name + '.out')

        bulk_mat.set_calculator(calc)

        save_atoms(bulk_mat, e_cut, nbands, k_pts, smear, a, initial_magmom, 1, str(sys.argv[6]))
Beispiel #23
0
from gpaw import restart
from gpaw.lrtddft import LrTDDFT, photoabsorption_spectrum

atoms, calc = restart('na2_gs_unocc.gpw')

# Calculate the omega matrix
lr = LrTDDFT(calc, xc='LDA', jend=5)
# Use only 5 unoccupied states

# Save the omega matrix
lr.write('Omega_Na2.gz')

# Diagonalize the matrix
lr.diagonalize()

# Analyse 5 lowest excitations
lr.analyse(range(5))
photoabsorption_spectrum(lr, 'Na2_spectrum.dat', e_min=0.0, e_max=10)
Beispiel #24
0
from __future__ import print_function
from ase.io import write
from gpaw import restart

basename = 'CO'

# load binary file and get calculator
atoms, calc = restart(basename + '.gpw')

# loop over all wfs and write their cube files
nbands = calc.get_number_of_bands()
for band in range(nbands):
    wf = calc.get_pseudo_wave_function(band=band)
    fname = '{0}_{1}.cube'.format(basename, band)
    print('writing wf', band, 'to file', fname)
    write(fname, atoms, data=wf)
Beispiel #25
0
from ase.io import write
from gpaw import restart

basename = 'CO'

# load nc binary file and get calculator
atoms, calc = restart(basename + '.gpw')

# loop over all wfs and write their cube files
nbands = calc.get_number_of_bands()

for band in range(nbands):

    wf = calc.get_pseudo_wave_function(band=band)
    fname=basename + '_' + '%d' % (band) + '.cube'
    print 'writing wf', band, 'to file', fname
    write(fname, atoms, data=wf)
Beispiel #26
0
from gpaw import restart
from ase.optimize import QuasiNewton

molecule, calc = restart("H2.gpw", txt="H2-relaxed.txt")

e2 = molecule.get_potential_energy()
d0 = molecule.get_distance(0, 1)

print "experimental bond length:"
print "hydrogen molecule energy: %5.2f eV" % e2
print "bondlength              : %5.2f Ang" % d0

# Find the theoretical bond length:
relax = QuasiNewton(molecule, logfile="qn.log")
relax.run(fmax=0.05)

e2 = molecule.get_potential_energy()
d0 = molecule.get_distance(0, 1)

print
print "PBE energy minimum:"
print "hydrogen molecule energy: %5.2f eV" % e2
print "bondlength              : %5.2f Ang" % d0
Beispiel #27
0
from gpaw import restart

# J.Phys.: Condens. Matter 18 (2006) 41-54
pw91vasp = {'NO':     -0.95,
            'N2':      0.00,
            'O2':      0.00,
            'NRu001': -0.94,
            'ORu001': -2.67,
            'Ru001':   0.00}

pbe = {}
pw91 = {}
for name in ['NO', 'O2', 'N2', 'Ru001', 'NRu001', 'ORu001']:
    a, calc = restart(name, txt=None)
    pbe[name] = a.get_potential_energy()
    pw91[name] = pbe[name] + calc.get_xc_difference('PW91')

for data, text in [(pbe, 'PBE'),
                   (pw91, 'PW91 (non-selfconsitent)'),
                   (pw91vasp, 'PW91 (VASP)')]:
    print ('%22s %.3f %.3f %.3f' %
           (text,
            data['NRu001'] - data['Ru001'] - data['N2'] / 2,
            data['ORu001'] - data['Ru001'] - data['O2'] / 2,
            data['NO'] - data['N2'] / 2 - data['O2'] / 2))

Beispiel #28
0
Eini = mol.get_potential_energy()
Iini = calc.get_number_of_iterations()
print ('%10s: %12.6f eV in %3d iterations' %
       ('init(cg)', Eini, Iini))
equal(Eini, Eini0, 1E-8)
equal(Iini, Iini0, 12)

calc.write('N2.gpw', mode='all')
del calc, mol

E = {}
I = {}
for esolver in esolvers:

    mol, calc = restart('N2.gpw', txt=None)

    if (calc.wfs.dtype!=complex or
        calc.wfs.kpt_u[0].psit_nG.dtype!=complex):
        raise AssertionError('ERROR: restart failed to read complex WFS')
    
    calc.scf.reset()
    calc.set(convergence={'eigenstates': 1E-10})
    calc.set(eigensolver=esolver)

    E[esolver]=mol.get_potential_energy()
    I[esolver]=calc.get_number_of_iterations()
    
    print ('%10s: %12.6f eV in %3d iterations' %
           (esolver, E[esolver], I[esolver]))
Beispiel #29
0
    def get_M(self, modes, log=None, q=0):
        """Calculate el-ph coupling matrix for given modes(s).

        XXX:
        kwarg "q=0" is an ugly hack for k-points.
        There shuold be loops over q!

        Note that modes must be given as a dictionary with mode
        frequencies in eV and corresponding mode vectors in units
        of 1/sqrt(amu), where amu = 1.6605402e-27 Kg is an atomic mass unit.
        In short frequencies and mode vectors must be given in ase units.

        ::
        
                  d                   d  ~
            < w | -- v | w' > = < w | -- v | w'>
                  dP                  dP

                               _
                              \        ~a     d   .       ~a
                            +  ) < w | p  >   -- /_\H   < p | w' >
                              /_        i     dP     ij    j
                              a,ij

                               _
                              \        d  ~a     .        ~a
                            +  ) < w | -- p  >  /_\H    < p | w' >
                              /_       dP  i        ij     j
                              a,ij

                               _
                              \        ~a     .        d  ~a
                            +  ) < w | p  >  /_\H    < -- p  | w' >
                              /_        i        ij    dP  j
                              a,ij

        """
        if log is None:
            timer = nulltimer
        elif log == '-':
            timer = StepTimer(name='EPCM')
        else:
            timer = StepTimer(name='EPCM', out=open(log, 'w'))

        modes1 = modes.copy()
        #convert to atomic units
        amu = 1.6605402e-27 # atomic unit mass [Kg]
        me = 9.1093897e-31  # electron mass    [Kg]
        modes = {}
        for k in modes1.keys():        
            modes[k / Hartree] = modes1[k] / np.sqrt(amu / me)

        dvt_Gx, ddH_aspx = self.get_gradient()

        from gpaw import restart
        atoms, calc = restart('eq.gpw', txt=None)
        spos_ac = atoms.get_scaled_positions()
        if calc.wfs.S_qMM is None:
            calc.initialize(atoms)
            calc.initialize_positions(atoms)

        wfs = calc.wfs
        nao = wfs.setups.nao
        bfs = wfs.basis_functions
        dtype = wfs.dtype
        spin = 0 # XXX

        M_lii = {}
        timer.write_now('Starting gradient of pseudo part')
        for f, mode in modes.items():
            mo = []    
            M_ii = np.zeros((nao, nao), dtype)
            for a in self.indices:
                mo.append(mode[a])
            mode = np.asarray(mo).flatten()
            dvtdP_G = np.dot(dvt_Gx, mode)   
            bfs.calculate_potential_matrix(dvtdP_G, M_ii, q=q)
            tri2full(M_ii, 'L')
            M_lii[f] = M_ii               
        timer.write_now('Finished gradient of pseudo part')

        P_aqMi = calc.wfs.P_aqMi
        # Add the term
        #  _
        # \        ~a     d   .       ~a
        #  ) < w | p  >   -- /_\H   < p | w' >
        # /_        i     dP     ij    j
        # a,ij

        Ma_lii = {}
        for f, mode in modes.items():
            Ma_lii[f] = np.zeros_like(M_lii.values()[0])
        
        timer.write_now('Starting gradient of dH^a part')
        for f, mode in modes.items():
            mo = []
            for a in self.indices:
                mo.append(mode[a])
            mode = np.asarray(mo).flatten()
            
            for a, ddH_spx in ddH_aspx.items():
                ddHdP_sp = np.dot(ddH_spx, mode)
                ddHdP_ii = unpack2(ddHdP_sp[spin])
                Ma_lii[f] += dots(P_aqMi[a][q], ddHdP_ii, P_aqMi[a][q].T)
        timer.write_now('Finished gradient of dH^a part')

        timer.write_now('Starting gradient of projectors part')
        spos_ac = self.atoms.get_scaled_positions() % 1.0
        dP_aMix = self.get_dP_aMix(spos_ac, wfs, q, timer)
        timer.write_now('Finished gradient of projectors part')

        dH_asp = pickle.load(open('v.eq.pckl'))[1]
        
        Mb_lii = {}
        for f, mode in modes.items():
            Mb_lii[f] = np.zeros_like(M_lii.values()[0])

        for f, mode in modes.items():
            for a, dP_Mix in dP_aMix.items():
                dPdP_Mi = np.dot(dP_Mix, mode[a])
                dH_ii = unpack2(dH_asp[a][spin])    
                dPdP_MM = dots(dPdP_Mi, dH_ii, P_aqMi[a][q].T)
                Mb_lii[f] -= dPdP_MM + dPdP_MM.T 
                # XXX The minus sign here is quite subtle.
                # It is related to how the derivative of projector
                # functions in GPAW is calculated.
                # More thorough explanations, anyone...?
                
        # Units of M_lii are Hartree/(Bohr * sqrt(m_e))
        for mode in M_lii.keys():
            M_lii[mode] += Ma_lii[mode] + Mb_lii[mode]

        # conversion to eV. The prefactor 1 / sqrt(hb^2 / 2 * hb * f)
        # has units Bohr * sqrt(me)
        M_lii_1 = M_lii.copy()
        M_lii = {}

        for f in M_lii_1.keys():
            M_lii[f * Hartree] =  M_lii_1[f] * Hartree / np.sqrt(2 * f)

        return M_lii
Beispiel #30
0
from ase.io import write
from gpaw import restart

slab, calc = restart('ontop.gpw', txt=None)
AuAl = slab.copy()
AuAl_density = calc.get_pseudo_density()

# Remove gold atom and do a clean slab calculation:
del slab[4]
slab.get_potential_energy()
Al_density = calc.get_pseudo_density()

# Remove Al atoms and do a calculation for Au only:
slab, calc = restart('ontop.gpw', txt=None)
del slab[:4]
calc.set(kpts=None)
slab.get_potential_energy()
Au_density = calc.get_pseudo_density()

diff = AuAl_density - Au_density - Al_density
write('diff.cube', AuAl, data=diff)
write('diff.plt', AuAl, data=diff)
import numpy as np
from gpaw import restart

slab, calc = restart("ontop.gpw", txt=None)
AuAl_density = calc.get_pseudo_density()

# Remove gold atom and do a clean slab calculation:
del slab[-1]
slab.get_potential_energy()
Al_density = calc.get_pseudo_density()

# Remove Al atoms and do a calculation for Au only:
slab, calc = restart("ontop.gpw", txt=None)
del slab[:-1]
calc.set(kpts=None)
slab.get_potential_energy()
Au_density = calc.get_pseudo_density()

diff = AuAl_density - Au_density - Al_density
np.save("densitydiff.npy", diff)
Beispiel #32
0
        eps = g.e_j[-1]
    world.barrier()

    a = 10
    Ne = Atoms([Atom(atom, (0, 0, 0))], cell=(a, a, a), pbc=False)
    Ne.center()
    calc = GPAW(nbands=10, h=0.2, xc=xcname)
    Ne.set_calculator(calc)
    e = Ne.get_potential_energy()
    response = calc.hamiltonian.xc.xcs["RESPONSE"]
    response.calculate_delta_xc()
    KS, dxc = response.calculate_delta_xc_perturbation()
    if xcname == "GLLB":
        equal(KS + dxc, 24.71, 1e-1)
    else:
        equal(KS + dxc, 27.70, 1e-2)
    eps3d = calc.wfs.kpt_u[0].eps_n[3]
    calc.write("Ne_temp.gpw")

    atoms, calc = restart("Ne_temp.gpw")
    KS2, dxc2 = response.calculate_delta_xc_perturbation()
    equal(KS, KS2, 1e-5)
    equal(dxc2, dxc, 1e-5)

    # Hardness of Ne 24.71eV by GLLB+Dxc, experimental I-A = I = 21.56eV

    if world.rank == 0:
        equal(eps, eps3d, 1e-3)
    if xcname == "GLLB":
        equal(24.71, KS2 + dxc2, 1e-1)
Beispiel #33
0
        kpts=(3, 1, 1),
        # basis='dzp',
        txt="Na4_fd.txt",
    )
    atoms.set_calculator(calc)
    etot_fd = atoms.get_potential_energy()
    niter_fd = calc.get_number_of_iterations()
    print "Etot:", etot_fd, "eV in fd-mode"
    calc.write("Na4_fd.gpw")
    del atoms, calc

    equal(etot_fd, -1.99055, energy_tolerance)
    equal(niter_fd, 17, niter_tolerance)

if os.path.isfile("Na4_fd.gpw"):
    # LCAO calculation based on grid kpts calculation
    atoms, calc = restart(
        "Na4_fd.gpw",
        # basis='dzp',
        mode="lcao",
        txt="Na4_lcao.txt",
    )
    etot_lcao = atoms.get_potential_energy()
    niter_lcao = calc.get_number_of_iterations()
    print "Etot:", etot_lcao, "eV in lcao-mode"
    calc.write("Na4_lcao.gpw")
    del atoms, calc

    equal(etot_lcao, -1.9616, energy_tolerance)
    equal(niter_lcao, 6, niter_tolerance)
Beispiel #34
0
from ase import Atoms
from gpaw import GPAW, restart
from gpaw.xc.sic import SIC
from gpaw.test import equal
a = 6.0
atom = Atoms('H', magmoms=[1.0], cell=(a, a, a))
molecule = Atoms('H2', positions=[(0, 0, 0), (0, 0, 0.737)], cell=(a, a, a))
atom.center()
molecule.center()

calc = GPAW(xc='LDA-PZ-SIC',
            eigensolver='rmm-diis',
            txt='h2.sic.txt',
            setups='hgh')

atom.set_calculator(calc)
e1 = atom.get_potential_energy()

molecule.set_calculator(calc)
e2 = molecule.get_potential_energy()
F_ac = molecule.get_forces()
de = 2 * e1 - e2
#equal(de, 4.5, 0.1)

# Test forces ...

calc.write('H2.gpw', mode='all')
atoms, calc = restart('H2.gpw')
e2b = atoms.get_potential_energy()
equal(e2, e2b, 0.0001)
Beispiel #35
0
if world.rank == 0:
    basis = BasisMaker('Li', 'szp').generate(1, 1)
    basis.write_xml()
world.barrier()
if setup_paths[0] != '.':
    setup_paths.insert(0, '.')

if 1:
    a = 2.7
    bulk = Atoms('Li', pbc=True, cell=[a, a, a])
    calc = GPAW(gpts=(8, 8, 8), kpts=(4, 4, 4), mode='lcao', basis='szp')
    bulk.set_calculator(calc)
    e = bulk.get_potential_energy()
    niter = calc.get_number_of_iterations()
    calc.write('temp.gpw')

atoms, calc = restart('temp.gpw')
H_skMM, S_kMM = get_lcao_hamiltonian(calc)
eigs = calc.get_eigenvalues(kpt=2)

if world.rank == 0:
    eigs2 = np.linalg.eigvals(np.linalg.solve(S_kMM[2], H_skMM[0, 2])).real
    eigs2.sort()
    assert abs(sum(eigs - eigs2)) < 1e-8

    energy_tolerance = 0.00003
    niter_tolerance = 0
    equal(e, -1.82847, energy_tolerance)
    equal(niter, 5, niter_tolerance)
Beispiel #36
0
from ase import Atoms
from ase.io import write
from ase.visualize import view
from gpaw import restart
from gpaw.wannier import Wannier

atoms, calc = restart('benzene.gpw')

h**o = calc.get_pseudo_wave_function(band=14)
write('h**o.cube', atoms, data=h**o)
write('h**o.plt', atoms, data=h**o)

# Initialize the Wannier class
w = Wannier(calc)
w.localize()
centers = w.get_centers()
view(atoms + Atoms(symbols='X15', positions=centers))

# Find the index of the center with the lowest y-coordinate:
nsigma = centers[:, 1].argmin()
sigma = w.get_function(calc, nsigma)

write('benzene.xyz', atoms)
write('sigma.cube', atoms, data=sigma)
write('sigma.plt', atoms, data=sigma)
Beispiel #37
0
            xc='PBE',
            nbands=-2,
            kpts=(8, 8, 8),
            occupations=FermiDirac(0.1),
            txt='cubulk_dos.txt')

copper.set_calculator(calc)
copper.get_potential_energy()
calc.write('cu.gpw', mode='all')

from ase import *
from ase.dft.dos import DOS
from gpaw import GPAW, restart
import pylab as p

slab, calc = restart('cu.gpw')
e, dos = calc.get_dos(spin=0, npts=2001, width=0.1)
e_f = calc.get_fermi_level()

#db = connect('cu_dos.db')
#db.write(slab, number_of_atoms = 1)
#
#for obj in db.select(number_of_atoms = 1):
#    print(obj)

bs = calc.band_structure()
bs.plot(filename='bandstructure.png', show=True, emax=10.0)

plt.figure(0)
plt.plot(dos, e)
plt.plot([0, 5], e_f * np.ones(2))
# Normal ground state calculation
atoms = bulk('Si')
calc = GPAW(h=0.24, kpts=(4,4,4), 
            convergence={'eigenstates' : 1e-4, 'density' : 1e-3},
    )
atoms.set_calculator(calc)
atoms.get_potential_energy()

# "Bandstructure" calculation (only Gamma point here)
kpts = np.array(((0, 0, 0),))
calc.set(fixdensity=True, kpts=kpts)
atoms.get_potential_energy()
calc.write('Si_gamma.gpw', mode='all')

# Analyse symmetries of wave functions
atoms, calc = restart('Si_gamma.gpw', txt=None)

# Find symmetries (in Gamma-point calculations calculator does not
# use symmetry)
sym = Symmetry(calc.wfs.setups.id_a, atoms.cell, atoms.pbc)
sym.analyze(atoms.get_scaled_positions())

def find_classes(op_all_scc):
    # Find classes of group represented by matrices op_all_scc
    # and return representative operations
    op_scc = [op_all_scc[0]]
    for op1 in op_all_scc[1:]:
        new_class = True
        for op2 in op_all_scc:
            op_tmp = (np.dot(np.dot(op2, op1), np.linalg.inv(op2).astype(int)))
            # Check whether operation op1 belongs to existing class 
Beispiel #39
0
    def get_M(self, modes, log=None, q=0):
        """Calculate el-ph coupling matrix for given modes(s).

        XXX:
        kwarg "q=0" is an ugly hack for k-points.
        There shuold be loops over q!

        Note that modes must be given as a dictionary with mode
        frequencies in eV and corresponding mode vectors in units
        of 1/sqrt(amu), where amu = 1.6605402e-27 Kg is an atomic mass unit.
        In short frequencies and mode vectors must be given in ase units.

        ::

                  d                   d  ~
            < w | -- v | w' > = < w | -- v | w'>
                  dP                  dP

                               _
                              \        ~a     d   .       ~a
                            +  ) < w | p  >   -- /_\H   < p | w' >
                              /_        i     dP     ij    j
                              a,ij

                               _
                              \        d  ~a     .        ~a
                            +  ) < w | -- p  >  /_\H    < p | w' >
                              /_       dP  i        ij     j
                              a,ij

                               _
                              \        ~a     .        d  ~a
                            +  ) < w | p  >  /_\H    < -- p  | w' >
                              /_        i        ij    dP  j
                              a,ij

        """
        if log is None:
            timer = nulltimer
        elif log == '-':
            timer = StepTimer(name='EPCM')
        else:
            timer = StepTimer(name='EPCM', out=open(log, 'w'))

        modes1 = modes.copy()
        #convert to atomic units
        amu = 1.6605402e-27  # atomic unit mass [Kg]
        me = 9.1093897e-31  # electron mass    [Kg]
        modes = {}
        for k in modes1.keys():
            modes[k / Hartree] = modes1[k] / np.sqrt(amu / me)

        dvt_Gx, ddH_aspx = self.get_gradient()

        from gpaw import restart
        atoms, calc = restart('eq.gpw', txt=None)
        if calc.wfs.S_qMM is None:
            calc.initialize(atoms)
            calc.initialize_positions(atoms)

        wfs = calc.wfs
        nao = wfs.setups.nao
        bfs = wfs.basis_functions
        dtype = wfs.dtype
        spin = 0  # XXX

        M_lii = {}
        timer.write_now('Starting gradient of pseudo part')
        for f, mode in modes.items():
            mo = []
            M_ii = np.zeros((nao, nao), dtype)
            for a in self.indices:
                mo.append(mode[a])
            mode = np.asarray(mo).flatten()
            dvtdP_G = np.dot(dvt_Gx, mode)
            bfs.calculate_potential_matrix(dvtdP_G, M_ii, q=q)
            tri2full(M_ii, 'L')
            M_lii[f] = M_ii
        timer.write_now('Finished gradient of pseudo part')

        P_aqMi = calc.wfs.P_aqMi
        # Add the term
        #  _
        # \        ~a     d   .       ~a
        #  ) < w | p  >   -- /_\H   < p | w' >
        # /_        i     dP     ij    j
        # a,ij

        Ma_lii = {}
        for f, mode in modes.items():
            Ma_lii[f] = np.zeros_like(M_lii.values()[0])

        timer.write_now('Starting gradient of dH^a part')
        for f, mode in modes.items():
            mo = []
            for a in self.indices:
                mo.append(mode[a])
            mode = np.asarray(mo).flatten()

            for a, ddH_spx in ddH_aspx.items():
                ddHdP_sp = np.dot(ddH_spx, mode)
                ddHdP_ii = unpack2(ddHdP_sp[spin])
                Ma_lii[f] += dots(P_aqMi[a][q], ddHdP_ii, P_aqMi[a][q].T)
        timer.write_now('Finished gradient of dH^a part')

        timer.write_now('Starting gradient of projectors part')
        dP_aMix = self.get_dP_aMix(calc.spos_ac, wfs, q, timer)
        timer.write_now('Finished gradient of projectors part')

        dH_asp = pickle.load(open('v.eq.pckl', 'rb'))[1]

        Mb_lii = {}
        for f, mode in modes.items():
            Mb_lii[f] = np.zeros_like(M_lii.values()[0])

        for f, mode in modes.items():
            for a, dP_Mix in dP_aMix.items():
                dPdP_Mi = np.dot(dP_Mix, mode[a])
                dH_ii = unpack2(dH_asp[a][spin])
                dPdP_MM = dots(dPdP_Mi, dH_ii, P_aqMi[a][q].T)
                Mb_lii[f] -= dPdP_MM + dPdP_MM.T
                # XXX The minus sign here is quite subtle.
                # It is related to how the derivative of projector
                # functions in GPAW is calculated.
                # More thorough explanations, anyone...?

        # Units of M_lii are Hartree/(Bohr * sqrt(m_e))
        for mode in M_lii.keys():
            M_lii[mode] += Ma_lii[mode] + Mb_lii[mode]

        # conversion to eV. The prefactor 1 / sqrt(hb^2 / 2 * hb * f)
        # has units Bohr * sqrt(me)
        M_lii_1 = M_lii.copy()
        M_lii = {}

        for f in M_lii_1.keys():
            M_lii[f * Hartree] = M_lii_1[f] * Hartree / np.sqrt(2 * f)

        return M_lii
Beispiel #40
0
from ase import Atoms, Atom
from gpaw import GPAW, restart

atoms, calc = restart('H2_gs.gpw')
atoms.center(vacuum=6.0)
calc.set(nbands=20)
calc.set(txt='H2.out')
atoms.set_calculator(calc)
e2 = atoms.get_potential_energy()
calc.write('H2.gpw')

lr = LrTDDFT(calc, xc="LDA")
lr.write("Omega_H2.gz")
photoabsorption_spectrum(lr, 'H2_spectrum.dat', e_min=0.0, e_max=10)

Beispiel #41
0
mol.center(vacuum=3.0)
mol.set_calculator(calc)

Eini = mol.get_potential_energy()
Iini = calc.get_number_of_iterations()
print ("%10s: %12.6f eV in %3d iterations" % ("init(cg)", Eini, Iini))
equal(Eini, Eini0, 1e-8)

calc.write("N2.gpw", mode="all")
del calc, mol

E = {}
I = {}
for esolver in esolvers:

    mol, calc = restart("N2.gpw", txt=None)

    if calc.wfs.dtype != complex or calc.wfs.kpt_u[0].psit_nG.dtype != complex:
        raise AssertionError("ERROR: restart failed to read complex WFS")

    calc.scf.reset()
    calc.set(convergence={"eigenstates": 3.5e-9})
    calc.set(eigensolver=esolver)

    E[esolver] = mol.get_potential_energy()
    I[esolver] = calc.get_number_of_iterations()

    print ("%10s: %12.6f eV in %3d iterations" % (esolver, E[esolver], I[esolver]))

for esolver in esolvers:
    print esolver
Beispiel #42
0
from __future__ import print_function
from sys import argv
import matplotlib.pyplot as plt

from ase.dft import STM
from gpaw import restart

filename = argv[1]
z0 = 8
bias = 1.0

atoms, calc = restart(filename, txt=None)

stm = STM(atoms, symmetries=[0, 1, 2])
c = stm.get_averaged_current(bias, z0)

print('Average current at z=%f: %f' % (z0, c))

# Get 2d array of constant current heights:
x, y, h = stm.scan(bias, c)

print('Min: %.2f Ang, Max: %.2f Ang' % (h.min(), h.max()))

plt.contourf(x, y, h, 40)
plt.hot()
plt.colorbar()
plt.show()
Beispiel #43
0
from ase.structure import molecule
from ase.io import write
from ase.parallel import parprint
from gpaw import GPAW, restart
from gpaw.elf import ELF
from gpaw.test import equal
from gpaw.mpi import rank, world

atoms = molecule('CO')
atoms.center(2.0)

txt=sys.stdout
txt=None

try:
    atoms, calc = restart('CO.gpw', txt=txt)
    energy = atoms.get_potential_energy()
except:
    calc = GPAW(h=0.24, txt=txt)
    atoms.set_calculator(calc)
    energy = atoms.get_potential_energy()
    calc.write('CO.gpw', 'all')

elf = ELF(calc)
elf.update()
elf_G = elf.get_electronic_localization_function(gridrefinement=1)
elf_g = elf.get_electronic_localization_function(gridrefinement=2)

nt_G = calc.density.nt_sG[0]
taut_G = elf.taut_sG[0]
nt_grad2_G = elf.nt_grad2_sG[0]
        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 #45
0
from __future__ import print_function

from gpaw import restart
from ase.parallel import paropen as open
from ase.optimize import QuasiNewton

molecule, calc = restart('H2.gpw', txt='H2-relaxed.txt')

e2 = molecule.get_potential_energy()
d0 = molecule.get_distance(0, 1)

fd = open('optimization.txt', 'w')
print('experimental bond length:', file=fd)
print('hydrogen molecule energy: %5.2f eV' % e2, file=fd)
print('bondlength              : %5.2f Ang' % d0, file=fd)

# Find the theoretical bond length:
relax = QuasiNewton(molecule, logfile='qn.log')
relax.run(fmax=0.05)

e2 = molecule.get_potential_energy()
d0 = molecule.get_distance(0, 1)

print(file=fd)
print('PBE energy minimum:', file=fd)
print('hydrogen molecule energy: %5.2f eV' % e2, file=fd)
print('bondlength              : %5.2f Ang' % d0, file=fd)
fd.close()
from ase import *
from ase.dft import Wannier
from gpaw import restart

atoms, calc = restart('poly.gpw', txt=None)

# Make wannier functions using (one) extra degree of freedom
wan = Wannier(nwannier=6, calc=calc, fixedenergy=1.5)
wan.localize()
wan.save('poly.pickle')
wan.translate_all_to_cell((2, 0, 0))
for i in range(wan.nwannier):
    wan.write_cube(i, 'polyacetylene_%i.cube' % i)

# Print Kohn-Sham bandstructure
ef = calc.get_fermi_level()
f = open('KSbands.txt', 'w')
for k, kpt_c in enumerate(calc.get_ibz_k_points()):
    for eps in calc.get_eigenvalues(kpt=k):
        print >> f, kpt_c[0], eps - ef

# Print Wannier bandstructure
f = open('WANbands.txt', 'w')
for k in np.linspace(-.5, .5, 100):
    for eps in np.linalg.eigvalsh(wan.get_hamiltonian_kpoint([k, 0, 0])).real:
        print >> f, k, eps - ef
Beispiel #47
0
                xc=xc,
                nbands=8,
                eigensolver=eigensolver,
                parallel={'band': band})
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    # And calculate the discontinuity potential with accurate band gap
    response = calc.hamiltonian.xc.xcs['RESPONSE']
    response.calculate_delta_xc(homolumo=homolumo / Ha)
    calc.write('CGLLBSC.gpw')

    # Redo the band structure calculation
    atoms, calc = restart('CGLLBSC.gpw',
                          kpts={
                              'path': 'GX',
                              'npoints': 12
                          },
                          fixdensity=True,
                          symmetry='off',
                          convergence=dict(bands=8))
    atoms.get_potential_energy()
    response = calc.hamiltonian.xc.xcs['RESPONSE']
    KS, dxc = response.calculate_delta_xc_perturbation()
    KSb.append(KS)
    dxcb.append(dxc)
    assert abs(KS + dxc - 5.41) < 0.10
    # M. Kuisma et. al, Phys. Rev. B 82, 115106,
    # QP gap for C, 5.41eV, expt. 5.48eV

assert abs(KSb[0] - KSb[1]) < 1e-6
assert abs(KSb[0] - KSb[2]) < 1e-6
assert abs(dxcb[0] - dxcb[1]) < 1e-6
Beispiel #48
0
    convergence={
        'eigenstates': 1e-4,
        'density': 1e-3
    },
)
atoms.set_calculator(calc)
atoms.get_potential_energy()

# "Bandstructure" calculation (only Gamma point here)
kpts = np.array(((0, 0, 0), ))
calc.set(fixdensity=True, kpts=kpts)
atoms.get_potential_energy()
calc.write('Si_gamma.gpw', mode='all')

# Analyse symmetries of wave functions
atoms, calc = restart('Si_gamma.gpw', txt=None)

# Find symmetries (in Gamma-point calculations calculator does not
# use symmetry)
sym = Symmetry(calc.wfs.setups.id_a, atoms.cell, atoms.pbc)
sym.analyze(atoms.get_scaled_positions())


def find_classes(op_all_scc):
    # Find classes of group represented by matrices op_all_scc
    # and return representative operations
    op_scc = [op_all_scc[0]]
    for op1 in op_all_scc[1:]:
        new_class = True
        for op2 in op_all_scc:
            op_tmp = (np.dot(np.dot(op2, op1), np.linalg.inv(op2).astype(int)))
Beispiel #49
0
                h=0.18,
                xc=xcname,
                basis='dzp',
                mixer=Mixer(0.6))
    Ne.set_calculator(calc)
    e = Ne.get_potential_energy()
    response = calc.hamiltonian.xc.xcs['RESPONSE']
    response.calculate_delta_xc()
    KS, dxc = response.calculate_delta_xc_perturbation()
    if xcname == 'GLLB':
        equal(KS + dxc, 24.89, 1.5e-1)
    else:
        equal(KS + dxc, 27.70, 6.0e-2)
    eps3d = calc.wfs.kpt_u[0].eps_n[3]
    calc.write('Ne_temp.gpw')

    atoms, calc = restart('Ne_temp.gpw')
    KS2, dxc2 = response.calculate_delta_xc_perturbation()
    equal(KS, KS2, 1e-5)
    equal(dxc2, dxc, 1e-5)

    # Hardness of Ne 24.71eV by GLLB+Dxc, experimental I-A = I = 21.56eV
    #
    # Not sure where 24.71 comes from, but with better grid and better
    # stencil, result becomes 24.89.  --askhl

    if world.rank == 0:
        equal(eps, eps3d, 1e-3)
    if xcname == 'GLLB':
        equal(24.89, KS2 + dxc2, 1.2e-1)
Beispiel #50
0
atoms = bulk('Fe', 'bcc', a=a)
atoms.set_initial_magnetic_moments([2.2,])
calc = GPAW(h=0.20,
            eigensolver=RMM_DIIS(),
            mixer=MixerSum(0.1,3),
            nbands=6,
            kpts=(4,4,4),
            parallel={'band' : 2, 'domain' : (2,1,1)},
            maxiter=4)
atoms.set_calculator(calc)
try:
    atoms.get_potential_energy()
except ConvergenceError:
    pass
for mode in modes:
    calc.write('tmp.%s' % mode, mode='all')

# Continue calculation for few iterations
for mode in modes:
    atoms, calc = restart('tmp.%s' % mode,
                          eigensolver=RMM_DIIS(),
                          mixer=MixerSum(0.1,3),
                          parallel={'band' : 2, 'domain' : (1,1,2)},
                          maxiter=4)
    try:
        atoms.get_potential_energy()
    except ConvergenceError:
        pass
    e = calc.hamiltonian.Etot
    equal(e, -0.372602008394, 0.000001)
Beispiel #51
0
calc = GPAW(h=0.30, nbands=3, setups={'Na': '1'}, convergence=conv)
atoms.set_calculator(calc)
e0 = atoms.get_potential_energy()
niter0 = calc.get_number_of_iterations()
f0 = atoms.get_forces()
m0 = atoms.get_magnetic_moments()
eig00 = calc.get_eigenvalues(spin=0)
eig01 = calc.get_eigenvalues(spin=1)
# Write the restart file(s)
for mode in modes:
    calc.write('tmp.%s' % mode)

del atoms, calc
# Try restarting from all the files
for mode in modes:
    atoms, calc = restart('tmp.%s' % mode)
    # Force new calculation
    calc.scf.converged = False
    e1 = atoms.get_potential_energy()
    f1 = atoms.get_forces()
    m1 = atoms.get_magnetic_moments()
    eig10 = calc.get_eigenvalues(spin=0)
    eig11 = calc.get_eigenvalues(spin=1)
    print(e0, e1)
    equal(e0, e1, 2e-3)
    print(f0, f1)
    for ff0, ff1 in zip(f0, f1):
        err = np.linalg.norm(ff0 - ff1)
        # for forces we use larger tolerance
        equal(err, 0.0, 4e-2)
    print(m0, m1)
Beispiel #52
0
from __future__ import print_function

from gpaw import restart
from ase.parallel import paropen as open
from ase.optimize import QuasiNewton


molecule, calc = restart('H2.gpw', txt='H2-relaxed.txt')

e2 = molecule.get_potential_energy()
d0 = molecule.get_distance(0, 1)

fd = open('optimization.txt', 'w')
print('experimental bond length:', file=fd)
print('hydrogen molecule energy: %5.2f eV' % e2, file=fd)
print('bondlength              : %5.2f Ang' % d0, file=fd)

# Find the theoretical bond length:
relax = QuasiNewton(molecule, logfile='qn.log')
relax.run(fmax=0.05)

e2 = molecule.get_potential_energy()
d0 = molecule.get_distance(0, 1)

print(file=fd)
print('PBE energy minimum:', file=fd)
print('hydrogen molecule energy: %5.2f eV' % e2, file=fd)
print('bondlength              : %5.2f Ang' % d0, file=fd)
fd.close()
from gpaw import restart
from ase.dft import Wannier

atoms, calc = restart('benzene.gpw', txt=None)

# Make wannier functions of occupied space only
wan = Wannier(nwannier=15, calc=calc)
wan.localize()
for i in range(wan.nwannier):
    wan.write_cube(i, 'benzene15_%i.cube' % i)

# Make wannier functions using (three) extra degrees of freedom.
wan = Wannier(nwannier=18, calc=calc, fixedstates=15)
wan.localize()
wan.save('wan18.pickle')
for i in range(wan.nwannier):
    wan.write_cube(i, 'benzene18_%i.cube' % i)
Beispiel #54
0
            convergence=conv)
atoms.set_calculator(calc)
e0 = atoms.get_potential_energy()
niter0 = calc.get_number_of_iterations()
f0 = atoms.get_forces()
m0 = atoms.get_magnetic_moments()
eig00 = calc.get_eigenvalues(spin=0)
eig01 = calc.get_eigenvalues(spin=1)
# Write the restart file(s)
for mode in modes:
    calc.write('tmp.%s' % mode)

del atoms, calc
# Try restarting from all the files
for mode in modes:
    atoms, calc = restart('tmp.%s' % mode)
    # Force new calculation
    calc.scf.converged = False
    e1 = atoms.get_potential_energy()
    f1 = atoms.get_forces()
    m1 = atoms.get_magnetic_moments()
    eig10 = calc.get_eigenvalues(spin=0)
    eig11 = calc.get_eigenvalues(spin=1)
    print e0, e1
    equal(e0, e1, 2e-3)
    print f0, f1
    for ff0, ff1 in zip(f0, f1):
        err = np.linalg.norm(ff0-ff1)
        # for forces we use larger tolerance
        equal(err, 0.0, 4e-2)
    print m0, m1
Beispiel #55
0
from ase.structure import molecule
from ase.io import write
from ase.parallel import parprint
from gpaw import GPAW, restart
from gpaw.elf import ELF
from gpaw.test import equal
from gpaw.mpi import rank, world

atoms = molecule("CO")
atoms.center(2.0)

txt = sys.stdout
txt = None

try:
    atoms, calc = restart("CO.gpw", txt=txt)
    energy = atoms.get_potential_energy()
except:
    calc = GPAW(h=0.24, txt=txt)
    atoms.set_calculator(calc)
    energy = atoms.get_potential_energy()
    calc.write("CO.gpw", "all")

elf = ELF(calc)
elf.update()
elf_G = elf.get_electronic_localization_function(gridrefinement=1)
elf_g = elf.get_electronic_localization_function(gridrefinement=2)

nt_G = calc.density.nt_sG[0]
taut_G = elf.taut_sG[0]
nt_grad2_G = elf.nt_grad2_sG[0]
    'mode': mode,
    'h': h,
    }
cmrfile = formula + '.cmr'

system1 = molecule(formula)
system1.center(vacuum=vacuum)

# first calculation: LDA lcao
calc = GPAW(mode=mode, xc=xc, h=h, txt=None)
system1.set_calculator(calc)
e = system1.get_potential_energy()
calc.write(formula)

# read gpw file
system2, calc2 = restart(formula, txt=None)
# write the information 'as in' gpw file into db file
# (called *db to avoid conflict with the *cmr file below)
if 1: # not used in this example
    calc2.write(formula + '.db', cmr_params=cmr_params)
# write the information 'as in' corresponding trajectory file into cmr file
write(cmrfile, system2, cmr_params=cmr_params)

# add the xc tag to the cmrfile
data = cmr.read(cmrfile)
data.set_user_variable('xc', xc)
data.write(cmrfile)

# perform PBE calculation on LDA density
ediff = calc2.get_xc_difference('PBE')
Beispiel #57
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 #58
0
Datei: si.py Projekt: qsnake/gpaw
             pbc=True, cell=(a, a, a))
n = 20
calc = GPAW(gpts=(n, n, n),
            nbands=8*3,
            occupations=FermiDirac(width=0.01),
            verbose=1,
            kpts=(1, 1, 1))
bulk.set_calculator(calc)
e1 = bulk.get_potential_energy()
niter1 = calc.get_number_of_iterations()
eigs = calc.get_eigenvalues(kpt=0)
calc.write('temp.gpw')
del bulk
del calc

bulk, calc = restart('temp.gpw', fixdensity=True)
#calc.scf.reset()
e2 = bulk.get_potential_energy()
try: # number of iterations needed in restart
    niter2 = calc.get_number_of_iterations()
except: pass
eigs2 = calc.get_eigenvalues(kpt=0)
print 'Orginal', eigs
print 'Fixdensity', eigs2
print 'Difference', eigs2-eigs

assert np.fabs(eigs2 - eigs)[:-1].max() < 3e-5

energy_tolerance = 0.0005
niter_tolerance = 0
equal(e1, -36.7664, energy_tolerance)