def eggbox(self): atom = Atoms(self.symbol, pbc=True, cell=(self.a, self.a, self.a)) negg = 25 self.Eegg = np.zeros((self.ng, negg)) self.Fegg = np.zeros((self.ng, negg)) eigensolver = 'rmm-diis' if self.symbol in ['Na', 'Mg']: eigensolver = 'cg' if self.symbol in ['Sc', 'Ti', 'V', 'Mn', 'Ni', 'Zn']: eigensolver = 'cg' if self.symbol in ['Zr', 'Nb', 'Mo', 'Ru', 'Rh', 'Pd', 'Ag']: eigensolver = 'cg' if self.symbol in ['Sn', 'Sb', 'Te', 'Ba']: eigensolver = 'cg' if self.symbol in ['Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Hg', 'Pb', 'Bi']: eigensolver = 'cg' for i in range(self.ng): h = self.gridspacings[i] calc = GPAW(h=h, txt='%s-eggbox-%.3f.txt' % (self.symbol, h), mixer=Mixer(beta=0.1, nmaxold=5, weight=50), eigensolver=eigensolver, maxiter=300, nbands=-10, **self.parameters) atom.set_calculator(calc) for j in range(negg): x = h * j / (2 * negg - 2) atom[0].x = x try: e = calc.get_potential_energy(atom, force_consistent=True) self.Eegg[i, j] = e except ConvergenceError: raise self.Fegg[i, j] = atom.get_forces()[0, 0]
def dimer(self): dimer = Atoms([self.symbol, self.symbol], pbc=True, cell=(self.a, self.a, self.a)) self.Edimer = np.zeros((self.ng, 7)) self.Fdimer = np.zeros((self.ng, 7, 2)) q0 = self.d0 / np.sqrt(3) eigensolver = 'rmm-diis' if self.symbol in ['Ti', 'Sn', 'Te', 'Ba']: eigensolver = 'cg' for i in range(self.ng): h = self.gridspacings[i] calc = GPAW(h=h, txt='%s-dimer-%.3f.txt' % (self.symbol, h), mixer=Mixer(beta=0.1, nmaxold=5, weight=50), #mixer=Mixer(beta=0.05, nmaxold=7, weight=100), eigensolver=eigensolver, maxiter=300, nbands=-10, **self.parameters) dimer.set_calculator(calc) y = [] for j in range(-3, 4): q = q0 * (1 + j * 0.02) dimer.positions[1] = (q, q, q) try: e = calc.get_potential_energy(dimer, force_consistent=True) self.Edimer[i, j + 3] = e except ConvergenceError: raise self.Fdimer[i, j + 3] = dimer.get_forces()[:, 0]
def setup_calculator(self, system, formula): hund = (len(system) == 1) cell = system.get_cell() h = self.h system.set_cell((cell / (4 * h)).round() * 4 * h) system.center() calc = GPAW(xc=self.xc, h=h, hund=hund, fixmom=True, setups=self.setups, txt=self.get_filename(formula, extension='txt'), mode=self.mode, basis=self.basis ) # Special cases if formula == 'BeH': calc.set(idiotproof=False) #calc.initialize(system) #calc.nuclei[0].f_si = [(1, 0, 0.5, 0, 0), # (0.5, 0, 0, 0, 0)] if formula in self.bad_formulas: system.positions[:, 1] += h * 1.5 return calc
def get_forces(self, atoms): """ Altered version of the original get_forces function in the GPAW-class. The function obtains the DFT forces by using the original call for the GPAW package and adds the DFT-D contribution to the calculated forces. """ # # Conversion factors a.u. -> eV and a.u. -> eV/Angst Eh__2__eV = 27.211396132 Eh_rb__2__eV_Angst = 51.422086162 # # Calling original VASP-calculator for forces self.dft_forces = GPAW.get_forces(self, atoms) # # Get functional name as string self.functional = xc_name(str.lower(GPAW.get_xc_functional(self))) # # Call DFT-D module: Energy and gradients self.dispersion_correction, self.dft_d_gradient_contribution = d2_pbc(atoms,self.functional) # # Convert to proper units self.dispersion_correction = self.dispersion_correction * Eh__2__eV self.dft_d_gradient_contribution = self.dft_d_gradient_contribution * Eh_rb__2__eV_Angst # # Adding correction contributions to forces # Note the (-) sign: DFT-D module delivers gradients, not forces return self.dft_forces - self.dft_d_gradient_contribution
def fulldiag(filename, bands=None, scalapack=1, dry_run=False): """Set up full H and S matrices and find all or some eigenvectors/values. calc: str Filename of gpw-file. bands: int Number of bands to calculate. Defaults to all. scalapack: int Number of cores to use for ScaLapack. Default is one. dry_run: bool Don't do actual calculation. """ name, ext = filename.rsplit('.', 1) assert ext == 'gpw' calc = GPAW(filename, parallel={'band': scalapack}, txt=name + '-all.txt') if not dry_run: calc.diagonalize_full_hamiltonian(bands) calc.write(name + '-all.gpw', 'all') ng = calc.wfs.pd.ngmax mem = ng**2 * 16 / 1024**2 print('Maximum matrix size: {0}x{0} = {1:.3f} MB'.format(ng, mem))
def GLLBSC_fail(): calc = GPAW(xc='GLLBSC', eigensolver='cg', kpts=(1,2,1), convergence={'density':1e-8}) atoms.set_calculator(calc) atoms.get_potential_energy() calc.set(kpts=(4,1,1)) return atoms.get_potential_energy()
def get_potential_energy(self, atoms, force_consistent=False): """ Altered version of the original get_potential_energy function in the class GPAW. The function obtains the DFT energy by using the original call for the GPAW package and adds the DFT-D3 contribution to the converged SCF-energy. """ # # Conversion factors a.u. -> eV Eh__2__eV = 27.211396132 # # Calling original GPAW-calculator for energy self.ks_scf_energy = GPAW.get_potential_energy(self, atoms, force_consistent) # # Get functional name as string self.functional = xc_name(str.lower(GPAW.get_xc_functional(self))) # # Call DFT-D module: Energy and gradients self.dispersion_correction, self.dft_d_gradient_contribution = d3_pbc(atoms, self.functional) # # Convert to proper units self.dispersion_correction = self.dispersion_correction * Eh__2__eV # # # Print out components (Useful?) # print # print 'DFT total energy : ', self.ks_scf_energy # print 'DFT-D3 correction : ', self.dispersion_correction # print # print 'DFT-D3 final corrected energy: ', self.ks_scf_energy + self.dispersion_correction # print # # Adding correction contribution to energy return self.ks_scf_energy + self.dispersion_correction
def test(): vdw = VDWFunctional('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() 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() 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)
def dos(filename, plot=False, output='dos.csv', width=0.1): """Calculate density of states. filename: str Name of restart-file. plot: bool Show a plot. output: str Name of CSV output file. width: float Width of Gaussians. """ from gpaw import GPAW from ase.dft.dos import DOS calc = GPAW(filename, txt=None) dos = DOS(calc, width) D = [dos.get_dos(spin) for spin in range(calc.get_number_of_spins())] if output: fd = sys.stdout if output == '-' else open(output, 'w') for x in zip(dos.energies, *D): print(*x, sep=', ', file=fd) if output != '-': fd.close() if plot: import matplotlib.pyplot as plt for y in D: plt.plot(dos.energies, y) plt.show()
def get_exact_exchange(self, ecut=None, communicator=world, file='EXX.pckl'): try: self.ini except: self.initialize() self.printtxt('------------------------------------------------') self.printtxt("calculating Exact exchange and E_XC") calc = GPAW(self.file, communicator=communicator, parallel={'domain':1, 'band':1}, txt=None) v_xc = vxc(calc) if ecut == None: ecut = self.ecut.max() else: ecut /= Hartree if self.pwmode: # planewave mode from gpaw.xc.hybridg import HybridXC self.printtxt('Use planewave ecut from groundstate calculator: %4.1f eV' % (calc.wfs.pd.ecut*Hartree) ) exx = HybridXC('EXX', alpha=5.0, bandstructure=True, bands=self.bands) else: # grid mode from gpaw.xc.hybridk import HybridXC self.printtxt('Planewave ecut (eV): %4.1f' % (ecut*Hartree) ) exx = HybridXC('EXX', alpha=5.0, ecut=ecut, bands=self.bands) calc.get_xc_difference(exx) e_skn = np.zeros((self.nspins, self.gwnkpt, self.gwnband), dtype=float) f_skn = np.zeros((self.nspins, self.gwnkpt, self.gwnband), dtype=float) vxc_skn = np.zeros((self.nspins, self.gwnkpt, self.gwnband), dtype=float) exx_skn = np.zeros((self.nspins, self.gwnkpt, self.gwnband), dtype=float) for s in range(self.nspins): for i, k in enumerate(self.gwkpt_k): ik = self.kd.bz2ibz_k[k] for j, n in enumerate(self.gwbands_n): e_skn[s][i][j] = self.e_skn[s][ik][n] f_skn[s][i][j] = self.f_skn[s][ik][n] vxc_skn[s][i][j] = v_xc[s][ik][n] / Hartree exx_skn[s][i][j] = exx.exx_skn[s][ik][n] if self.eshift is not None: if e_skn[s][i][j] > self.eFermi: vxc_skn[s][i][j] += self.eshift / Hartree data = { 'e_skn': e_skn, # in Hartree 'vxc_skn': vxc_skn, # in Hartree 'exx_skn': exx_skn, # in Hartree 'f_skn': f_skn, 'gwkpt_k': self.gwkpt_k, 'gwbands_n': self.gwbands_n } if rank == 0: pickle.dump(data, open(file, 'w'), -1) self.printtxt("------------------------------------------------") self.printtxt("non-selfconsistent HF eigenvalues are (eV):") self.printtxt((e_skn - vxc_skn + exx_skn)*Hartree)
class UTGroundStateSetup(TestCase): """ Setup a simple calculation starting from ground state.""" # Number of bands nbands = 1 # Spin-paired, single kpoint nspins = 1 nibzkpts = 1 # Mean spacing and number of grid points per axis (G x G x G) h = 0.25 / Bohr def setUp(self): for virtvar in []: assert getattr(self,virtvar) is not None, 'Virtual "%s"!' % virtvar parsize_domain, parsize_bands = create_parsize_maxbands(self.nbands, world.size) self.parallel = {'domain': parsize_domain, 'band': parsize_bands} self.atoms = molecule('Na2') self.atoms.center(vacuum=4.0) self.atoms.set_pbc(False) cell_c = np.sum(self.atoms.get_cell()**2, axis=1)**0.5 / Bohr ngpts = 16 * np.round(cell_c / (self.h * 16)) self.gsname = 'ut_tddft_gs' self.gscalc = GPAW(gpts=ngpts, nbands=self.nbands, basis='dzp', setups={'Na': '1'}, spinpol=(self.nspins==2), parallel=self.parallel, txt=self.gsname + '.txt') def tearDown(self): del self.atoms, self.gscalc # ================================= def verify_comm_sizes(self): if world.size == 1: return rem = world.size // (self.parallel['band'] * self.parallel['domain']) comm_sizes = (world.size, self.parallel['band'], self.parallel['domain'], rem) self._parinfo = '%d world, %d band, %d domain, %d kpt' % comm_sizes self.assertEqual(self.nbands % self.parallel['band'], 0) self.assertEqual((self.nspins * self.nibzkpts) % rem, 0) def verify_ground_state(self): #XXX DEBUG START if debug and os.path.isfile(self.gsname + '.gpw'): return #XXX DEBUG END self.atoms.set_calculator(self.gscalc) self.assertAlmostEqual(self.atoms.get_potential_energy(), -1.0621, 4) self.gscalc.write(self.gsname + '.gpw', mode='all') self.assertTrue(os.path.isfile(self.gsname + '.gpw'))
def energy(N, k, a=4.05): fcc = fcc100('Al', (1, 1, N), a=a, vacuum=7.5) fcc.center(axis=2) calc = GPAW(nbands=N * 5, kpts=(k, k, 1), h=0.25, txt='slab-%d.txt' % N) fcc.set_calculator(calc) e = fcc.get_potential_energy() calc.write('slab-%d.gpw' % N) return e
def f(kpts, n, magmom, pbc, dd): global de1 H = Atoms([Atom('H',(a/2, a/2, a/2), magmom=magmom)], pbc=pbc, cell=(a, a, a)) H.set_calculator(GPAW(nbands=1, gpts=(n, n, n), kpts=kpts, txt=None, tolerance=0.0001, parsize=dd)) e = H.get_potential_energy() H.get_calculator().write('H-par.gpw') c = GPAW('H-par.gpw', txt=None) H = c.get_atoms() de = abs(H.get_potential_energy() - e) if de > de1: de1 = de assert de < 1e-15 return e
def ground_state(self, filename, **kwargs): # GPAW calculator for the ground state self.gs_calc = GPAW(gpts = self.gpts, poissonsolver = self.poissonsolver, **kwargs ) self.atoms.set_calculator(self.gs_calc) self.energy = self.atoms.get_potential_energy() self.write(filename, mode='all')
def f(kpts, n, magmom, periodic, dd): global de1 H = Atoms('H', positions=[(a/2, a/2, a/2)], magmoms=[magmom], pbc=periodic, cell=(a, a, a)) H.set_calculator(GPAW(nbands=1, gpts=(n, n, n), kpts=kpts, txt=None, convergence={'eigenstates': 0.0001}, parsize=dd)) e = H.get_potential_energy() H.get_calculator().write('/tmp/H-par.gpw') c = GPAW('/tmp/H-par.gpw', txt=None) H = c.get_atoms() de = abs(H.get_potential_energy() - e) if de > de1: de1 = de assert de < 1e-15 return e
def do_calculations(self, formulas): """Perform calculation on molecules, write results to .gpw files.""" atoms = {} for formula in formulas: for symbol in string2symbols(formula.split('_')[0]): atoms[symbol] = None formulas = formulas + atoms.keys() for formula in formulas: if path.isfile(formula + '.gpw'): continue barrier() open(formula + '.gpw', 'w') s = molecule(formula) s.center(vacuum=self.vacuum) cell = s.get_cell() h = self.h s.set_cell((cell / (4 * h)).round() * 4 * h) s.center() calc = GPAW(h=h, xc=self.xc, eigensolver=self.eigensolver, setups=self.setups, basis=self.basis, fixmom=True, txt=formula + '.txt') if len(s) == 1: calc.set(hund=True) s.set_calculator(calc) if formula == 'BeH': calc.initialize(s) calc.nuclei[0].f_si = [(1, 0, 0.5, 0, 0), (0.5, 0, 0, 0, 0)] if formula in ['NO', 'ClO', 'CH']: s.positions[:, 1] += h * 1.5 try: energy = s.get_potential_energy() except (RuntimeError, ConvergenceError): if rank == 0: print >> sys.stderr, 'Error in', formula traceback.print_exc(file=sys.stderr) else: print >> self.txt, formula, repr(energy) self.txt.flush() calc.write(formula) if formula in diatomic and self.calculate_dimer_bond_lengths: traj = PickleTrajectory(formula + '.traj', 'w') d = diatomic[formula][1] for x in range(-2, 3): s.set_distance(0, 1, d * (1.0 + x * 0.02)) traj.write(s)
def aual100(site, height, calc=None): slab = fcc100('Al', size=(2, 2, 1)) add_adsorbate(slab, 'Au', height, site) slab.center(axis=2, vacuum=3.0) mask = [atom.symbol == 'Al' for atom in slab] fixlayer = FixAtoms(mask=mask) slab.set_constraint(fixlayer) if calc is None: calc = GPAW(h=0.25, kpts=(2, 2, 1), xc='PBE', txt=site + '.txt') slab.set_calculator(calc) qn = QuasiNewton(slab, trajectory=site + '.traj') qn.run(fmax=0.05) if isinstance(calc, GPAW): calc.write(site + '.gpw') return slab.get_potential_energy()
def create_calc(name, spinpol, pbc): # Bond lengths between H-C and C-C for ethyne (acetylene) cf. # CRC Handbook of Chemistry and Physics, 87th ed., p. 9-28 dhc = 1.060 dcc = 1.203 atoms = Atoms([Atom('H', (0, 0, 0)), Atom('C', (dhc, 0, 0)), Atom('C', (dhc+dcc, 0, 0)), Atom('H', (2*dhc+dcc, 0, 0))], pbc=pbc) atoms.center(vacuum=2.0) # Number of occupied and unoccupied bands to converge nbands = int(10/2.0) nextra = 3 #TODO use pbc and cell to calculate nkpts kwargs = {} if spinpol: kwargs['mixer'] = MixerSum(nmaxold=5, beta=0.1, weight=100) else: kwargs['mixer'] = Mixer(nmaxold=5, beta=0.1, weight=100) calc = GPAW(h=0.3, nbands=nbands+nextra, xc='PBE', spinpol=spinpol, eigensolver='cg', convergence={'energy':1e-4/len(atoms), 'density':1e-5, \ 'eigenstates': 1e-9, 'bands':-1}, txt=name+'.txt', **kwargs) atoms.set_calculator(calc) atoms.get_potential_energy() calc.write(name+'.gpw', mode='all')
def xc(filename, xc, ecut=None): """Calculate non self-consitent energy. filename: str Name of restart-file. xc: str Functional ecut: float Plane-wave cutoff for exact exchange. """ name, ext = filename.rsplit(".", 1) assert ext == "gpw" if xc in ["EXX", "PBE0", "B3LYP"]: from gpaw.xc.exx import EXX exx = EXX(filename, xc, ecut=ecut, txt=name + "-exx.txt") exx.calculate() e = exx.get_total_energy() else: from gpaw import GPAW calc = GPAW(filename, txt=None) e = calc.get_potential_energy() + calc.get_xc_difference(xc) print(e, "eV")
def setUp(self): for virtvar in []: assert getattr(self,virtvar) is not None, 'Virtual "%s"!' % virtvar parsize_domain, parsize_bands = create_parsize_maxbands(self.nbands, world.size) self.parallel = {'domain': parsize_domain, 'band': parsize_bands} self.atoms = molecule('Na2') self.atoms.center(vacuum=4.0) self.atoms.set_pbc(False) cell_c = np.sum(self.atoms.get_cell()**2, axis=1)**0.5 / Bohr ngpts = 16 * np.round(cell_c / (self.h * 16)) self.gsname = 'ut_tddft_gs' self.gscalc = GPAW(gpts=ngpts, nbands=self.nbands, basis='dzp', setups={'Na': '1'}, spinpol=(self.nspins==2), parallel=self.parallel, txt=self.gsname + '.txt')
def get_dispersion_correction(self, atoms): """ Returns the DFT-D dispersion correction for the current geometry """ # # Conversion factors a.u. -> eV Eh__2__eV = 27.211396132 # # Get functional name as string self.functional = xc_name(str.lower(GPAW.get_xc_functional(self))) # # Call DFT-D module: Energy and gradients self.dispersion_correction, self.dft_d_gradient_contribution = d2_pbc(atoms, self.functional) # # Convert to proper units self.dispersion_correction = self.dispersion_correction * Eh__2__eV # # # Return dispersion correction return self.dispersion_correction
def check_degenerate_bands(filename, etol): from gpaw import GPAW calc = GPAW(filename,txt=None) print('Number of Electrons :', calc.get_number_of_electrons()) nibzkpt = calc.get_ibz_k_points().shape[0] nbands = calc.get_number_of_bands() print('Number of Bands :', nbands) print('Number of ibz-kpoints :', nibzkpt) e_kn = np.array([calc.get_eigenvalues(k) for k in range(nibzkpt)]) f_kn = np.array([calc.get_occupation_numbers(k) for k in range(nibzkpt)]) for k in range(nibzkpt): for n in range(1,nbands): if (f_kn[k,n-1] - f_kn[k,n] > 1e-5) and (np.abs(e_kn[k,n] - e_kn[k,n-1]) < etol): print(k, n, e_kn[k,n], e_kn[k, n-1]) return
def setUp(self): for virtvar in []: assert getattr(self, virtvar) is not None, 'Virtual "%s"!' % virtvar parsize_domain, parsize_bands = create_parsize_maxbands(self.nbands, world.size) self.parallel = {"domain": parsize_domain, "band": parsize_bands} self.atoms = molecule("Na2") self.atoms.center(vacuum=4.0) self.atoms.set_pbc(False) cell_c = np.sum(self.atoms.get_cell() ** 2, axis=1) ** 0.5 / Bohr ngpts = 16 * np.round(cell_c / (self.h * 16)) self.gsname = "ut_tddft_gs" self.gscalc = GPAW( gpts=ngpts, nbands=self.nbands, basis="dzp", setups={"Na": "1"}, spinpol=(self.nspins == 2), parallel=self.parallel, txt=self.gsname + ".txt", )
def test(): h=4.02 vdw = FFTVDWFunctional(verbose=1) L=20 a=3.52 atoms = Atoms(pbc=(True, True, True), cell=(a/sqrt(2), sqrt(6)*a/2.0, L)) atoms.append(Atom('C',[1.5*a/sqrt(2)*1.0/3,a/sqrt(2)*sqrt(3)/2*1.0/3, L/2+h])) atoms.append(Atom('C',[1.5*a/sqrt(2)*2.0/3,a/sqrt(2)*sqrt(3)/2*2.0/3, L/2+h])) atoms.append(Atom('C',[a/sqrt(2)/2.0+1.5*a/sqrt(2)*1.0/3,sqrt(6)*a/4.0+a/sqrt(2)*sqrt(3)/2*1.0/3, L/2+h])) atoms.append(Atom('C',[a/sqrt(2)/2.0+1.5*a/sqrt(2)*2.0/3-a/sqrt(2),sqrt(6)*a/4.0+a/sqrt(2)*sqrt(3)/2*2.0/3, L/2+h])) atoms.append(Atom('C',[1.5*a/sqrt(2)*1.0/3,a/sqrt(2)*sqrt(3)/2*1.0/3+2.874/2, L/2])) atoms.append(Atom('C',[1.5*a/sqrt(2)*2.0/3,a/sqrt(2)*sqrt(3)/2*2.0/3+2.874/2, L/2])) atoms.append(Atom('C',[a/sqrt(2)/2.0+1.5*a/sqrt(2)*1.0/3,sqrt(6)*a/4.0+a/sqrt(2)*sqrt(3)/2*1.0/3+2.874/2, L/2])) atoms.append(Atom('C',[a/sqrt(2)/2.0+1.5*a/sqrt(2)*2.0/3-a/sqrt(2),sqrt(6)*a/4.0+a/sqrt(2)*sqrt(3)/2*2.0/3+2.874/2, L/2])) calc = GPAW(h=0.18, xc='revPBE',kpts=(8,8,1),txt=str(h)+'.txt') atoms.set_calculator(calc) e2 = atoms.get_potential_energy() calc.write('gr_dilayer.gpw') e2vdw = calc.get_xc_difference(vdw) del atoms[4:] e = atoms.get_potential_energy() calc.write('gr_dilayer.gpw') evdw = calc.get_xc_difference(vdw) E = 2 * e - e2 Evdw = E + 2 * evdw - e2vdw print E, Evdw assert abs(E +0.032131069056 ) < 1e-4 assert abs(Evdw- 0.144516773316) < 1e-4
from ase import Atoms from gpaw import GPAW, PW from ase.optimize import BFGS from ase.build import fcc111, add_adsorbate, bulk from gpaw import GPAW, PW from ase.io import read, write from ase.constraints import FixAtoms adsorbate = Atoms('CO') adsorbate[1].z = 1.43 #panjang ikatan CO adsorbate.center(vacuum=5) c = FixAtoms(indices=[0]) adsorbate.set_constraint(c) calc = GPAW(mode=PW(750), xc='PBE', parallel={'band': 1}, txt='relax-co.txt') adsorbate.calc = calc adsorbate.get_potential_energy() relax = BFGS(adsorbate, logfile='bfgs.log', trajectory='co.traj') relax.run(fmax=0.05)
filename = 'atoms_'+name+'.dat' f = paropen(filename,'w') elements = ['N'] for symbol in elements: mixer = Mixer() eigensolver = CG(tw_coeff=lambda_coeff) poissonsolver=PoissonSolver() molecule = Atoms(symbol, positions=[(c,c,c)] , cell=(a,a,a)) calc = GPAW(h=h, xc=xcname, maxiter=240, eigensolver=eigensolver, mixer=mixer, setups=name, poissonsolver=poissonsolver) molecule.set_calculator(calc) E = molecule.get_total_energy() f.write('{0}\t{1}\n'.format(symbol,E))
#!/usr/bin/env python import numpy as np from ase import Atom, Atoms from ase.parallel import rank from gpaw import GPAW from gpaw.test import equal try: calc = GPAW('NaCl.gpw') NaCl = calc.get_atoms() e = NaCl.get_potential_energy() niter = None except IOError: h = 0.21 # gridspacing a = [6.5, 6.5, 7.7] # unit cell d = 2.3608 # experimental bond length NaCl = Atoms( [Atom('Na', [0, 0, 0]), Atom('Cl', [0, 0, d])], pbc=False, cell=a) NaCl.center() calc = GPAW(h=h, xc='LDA', nbands=5, lmax=0, convergence={'eigenstates': 1e-6}, spinpol=1) NaCl.set_calculator(calc) e = NaCl.get_potential_energy()
from ase import Atoms from ase.parallel import paropen from gpaw import GPAW from gpaw.wavefunctions.pw import PW resultfile = paropen('H.ralda.DFT_corr_energies.txt', 'w') resultfile.write('DFT Correlation energies for H atom\n') H = Atoms('H', [(0, 0, 0)]) H.set_pbc(True) H.center(vacuum=2.0) calc = GPAW(mode=PW(300, force_complex_dtype=True), parallel={'domain': 1}, hund=True, txt='H.ralda_01_lda.output.txt', xc='LDA') H.set_calculator(calc) E_lda = H.get_potential_energy() E_c_lda = -calc.get_xc_difference('LDA_X') resultfile.write('LDA correlation: %s eV' % E_c_lda) resultfile.write('\n') calc.diagonalize_full_hamiltonian() calc.write('H.ralda.lda_wfcs.gpw', mode='all')
from ase import Atoms from ase.build import fcc111, add_adsorbate, bulk from ase.io import read, write from gpaw import GPAW, PW a = 3.597 #lattice Cu slab = fcc111('Cu', (1, 1, 3), a=a, vacuum=10.0) for k in range(2, 11, 1): calc = GPAW(mode=PW(850), xc='PBE', kpts=(k, k, 1), parallel={'band': 1}, txt='scf-k_%d.txt' % k) slab.calc = calc slab.get_potential_energy()
from ase.build import bulk from gpaw import GPAW, PW, FermiDirac from ase.units import Bohr, Hartree import numpy as np atoms = bulk("Si", "diamond", a=10.2631 * Bohr) ecutwfc = 15.0 * Hartree for kden in np.linspace(1.0, 5.0, 9): calc = GPAW(mode=PW(ecutwfc), occupations=FermiDirac(0.0), kpts={"density": kden}, txt="LOG_kden_v2_" + str(kden)) atoms.set_calculator(calc) etot = atoms.get_potential_energy() print("%6.3f %18.10f %18.10f" % (kden, etot, etot / Hartree))
# Set calculator # loop a number of times to capture if minimization stops with high force # due to the VariansBreak calls niter = 0 # If the structure is already fully relaxed just return it traj = Trajectory(label + '_lcao.traj', 'w', structure) while (structure.get_forces()** 2).sum(axis=1).max()**0.5 > forcemax and niter < niter_max: dyn = BFGS(structure, logfile=label + '.log') vb = VariansBreak(structure, dyn, min_stdev=0.01, N=15) dyn.attach(traj) dyn.attach(vb) dyn.run(fmax=forcemax, steps=steps) niter += 1 #print('relaxgpaw over',flush=True) return structure calc = GPAW(mode=PW(500), xc='PBE', basis='dzp', kpts=(3, 3, 1)) traj = Trajectory('V2O5_2H2OTiO2_101_DFTrelaxed.traj', 'w') name = 'V2O5_2H2OTiO2_101surface_gm' data = read('V2O5_2H2O_TiO2_I3s.traj@:') for i in range(0, len(data)): name = 'V2O5_2H2OTiO2_101surface_isomer_{}'.format(i) a = data[i] a.set_calculator(calc) a_relaxed = relaxGPAW(a, name, forcemax=0.01, niter_max=2, steps=100) traj.write(a_relaxed)
from ase.constraints import ExpCellFilter from ase.io import write from ase.optimize import BFGS from ase.spacegroup import crystal from gpaw import GPAW, PW a = 4.6 c = 2.95 # Rutile TiO2: atoms = crystal(['Ti', 'O'], basis=[(0, 0, 0), (0.3, 0.3, 0.0)], spacegroup=136, cellpar=[a, a, c, 90, 90, 90]) write('rutile.traj', atoms) calc = GPAW(mode=PW(800), kpts=[2, 2, 3], txt='gpaw.rutile.txt') atoms.calc = calc opt = BFGS(ExpCellFilter(atoms), trajectory='opt.rutile.traj') opt.run(fmax=0.05) calc.write('groundstate.rutile.gpw') print('Final lattice:') print(atoms.cell.get_bravais_lattice())
from gpaw.lrtddft import LrTDDFT, photoabsorption_spectrum from gpaw.lrtddft.kssingle import KSSingles from cStringIO import StringIO L = 10.0 txt=None txt='-' N2 = molecule('N2') N2.set_cell([L, L, L]) #N2.set_pbc(True) N2.center() try: calc = GPAW('N2_wfs.gpw', txt=txt, parallel={'domain': world.size}) calc.converge_wave_functions() except: calc = GPAW(h=0.25, nbands=-5, spinpol=True, xc='PBE', txt=txt, eigensolver='cg', parallel={'domain': world.size}) N2.set_calculator(calc) E0 = N2.get_potential_energy() calc.write('N2_wfs.gpw', 'all') # selections
#!/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)
import numpy as np from ase.lattice import bulk from gpaw import GPAW from gpaw.response.df import DielectricFunction # Part 1: Ground state calculation atoms = bulk('Si', 'diamond', a=5.431) # Generate diamond crystal structure for silicon calc = GPAW(mode='pw', kpts=(4,4,4)) # GPAW calculator initialization atoms.set_calculator(calc) atoms.get_potential_energy() # Ground state calculation is performed calc.write('si.gpw', 'all') # Use 'all' option to write wavefunction # Part 2 : Spectrum calculation # DF: dielectric function object df = DielectricFunction(calc='si.gpw', # Ground state gpw file (with wavefunction) as input domega0=0.05) # Using nonlinear frequency grid df.get_dielectric_function() # By default, a file called 'df.csv' is generated
atoms = sys.argv[5] atoms = int(atoms) bulk_mat = bulk('Cu','fcc',a)*(atoms,atoms,atoms) is_varying = str(sys.argv[6]) if (str(sys.argv[8]) == 'True'): del bulk_mat[[atom.index for atom in bulk_mat if atom.index == 0]] #view(bulk_mat) #time.sleep(3600) calc = GPAW(mode=PW(e_cut), nbands = nbands, xc='PBE', kpts=(k_pts,k_pts,k_pts), occupations=FermiDirac(smear), txt='Cu.out') bulk_mat.set_calculator(calc) traj = Trajectory('some_test.traj', 'w', bulk_mat) relaxer = PreconLBFGS(bulk_mat, variable_cell = True, logfile = 'my_log.txt') relaxer.attach(traj) relaxer.run(fmax = 0.025, smax = 0.003) bulk_mat.get_potential_energy() calc.write('Cu.gpw') save_atoms(bulk_mat, e_cut, nbands, k_pts, smear, a, is_varying, str(sys.argv[7]))
## try: ## import Scientific.IO.NetCDF ## endings.append('nc') ## except ImportError: ## pass for ending in endings: restart_wf = 'gpaw-restart-wf.' + ending # H2 H = Atoms([Atom('H', (0, 0, 0)), Atom('H', (0, 0, 1))]) H.center(vacuum=2.0) if 1: calc = GPAW(nbands=2, convergence={ 'eigenstates': 0.001, 'energy': 0.1, 'density': 0.1 }) H.set_calculator(calc) H.get_potential_energy() calc.write(restart_wf, 'all') # refine the result directly calc.set(convergence={'energy': 0.00001}) Edirect = H.get_potential_energy() # refine the result after reading from a file H = GPAW(restart_wf, convergence={'energy': 0.00001}).get_atoms() Erestart = H.get_potential_energy() print Edirect, Erestart
'Test ase.dft.wannier module with k-points.' from __future__ import print_function from ase.build import bulk from ase.dft.wannier import Wannier from gpaw import GPAW from gpaw.mpi import world, serial_comm si = bulk('Si', 'diamond', a=5.43) k = 2 if 1: si.calc = GPAW(kpts=(k, k, k), mode='lcao', txt='Si-ibz.txt') #si.calc = GPAW(kpts=(k, k, k), mode='lcao') e1 = si.get_potential_energy() si.calc.write('Si-ibz', mode='all') #si.calc.set(symmetry='off', txt='Si-bz.txt') #si.calc.set(symmetry='off') #e2 = si.get_potential_energy() #si.calc.write('Si-bz', mode='all') #print e1, e2 def wan(calc): centers = [([0.125, 0.125, 0.125], 0, 1.5), ([0.125, 0.625, 0.125], 0, 1.5), ([0.125, 0.125, 0.625], 0, 1.5), ([0.625, 0.125, 0.125], 0, 1.5)] w = Wannier(4, calc, nbands=4, verbose=False, initialwannier=centers) w.localize()
# plot orthogonal to bond axis through H2 ax[1][1].set_title( r'Plane of $ -\frac{1}{2} \nabla^2 \rho^{1/2} $ orthogonal to bond axis at H2' ) ax[1][1].set_xlabel(r'cell axis x') ax[1][1].set_ylabel(r'cell axis y') ax[1][1].set_xlim(x1z, x2z) ax[1][1].set_ylim(y1z, y2z) ax[1][1].contour(func_obj.coordinates[0], func_obj.coordinates[1], z_plane_kin_o_bond_h2) ax[1][1].scatter(pos_z[1], pos_z[0], c='red') # load results from GPAW calculation calc2 = GPAW('/home/misa/APDFT/prototyping/gpaw/OFDFT/result_64_gpts.gpw') # cell width in Bohr cell_vectors = calc2.atoms.cell a_x = cell_vectors[0][0] a_y = cell_vectors[1][1] a_z = cell_vectors[2][2] ############################################################################### # create func object for sqrt of coarse pseudo density and apply own kinetic energy operator to sqrt(density) sqrt_pseudo_dens = np.sqrt( calc2.density.nt_sG[0]) # sqrt of pseudo density on coarse grid kwargs_pseuod_dens = { 'func_value': sqrt_pseudo_dens, 'length_cell': [a_x, a_y, a_z]
from ase.build import molecule from ase import io from gpaw import GPAW txt = 'out.txt' if 1: calculator = GPAW(h=0.3, txt=txt) atoms = molecule('H2', calculator=calculator) atoms.center(vacuum=3) atoms.get_potential_energy() atoms.set_initial_magnetic_moments([0.5, 0.5]) calculator.set(charge=1) atoms.get_potential_energy() # read again t = io.read(txt, index=':') assert isinstance(t, list) M = t[1].get_magnetic_moments() assert abs(M - 0.2).max() < 0.1
atoms = Atoms(symbols=myGpaw.symstr, pbc=[ True, True, True], cell=myGpaw.gcell, positions=myGpaw.pos ) # view(atoms) kpts={'size': (4, 4, 4), 'gamma': True} calc = GPAW(#h=0.16, mode=PW(900), kpts=kpts, xc='PBE', txt=myGpaw.symstr+'_900.out', occupations=FermiDirac(width=0.05), # nbands=-2, convergence={'energy': 0.0005, # eV / electron 'density': 1.0e-4, 'eigenstates': 4.0e-8, # eV^2 / electron 'bands': 'CBM+2.0', 'forces': float('inf')} # eV / Ang Max ) atoms.calc = calc e2 = atoms.get_potential_energy() d0 = atoms.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)
struct = elem_list[1] print("struct = ", struct) nbnd = int(elem_list[2]) print("nbands = ", nbnd) spath = elem_list[3] print("path = ", spath) nkpts = elem_list[4] print("kpts = ", nkpts) kpts = ast.literal_eval(nkpts) # First perform a regular SCF run calc = GPAW( mode=PW(400), maxiter=200, spinpol=False, kpts=kpts, xc=xc, txt='-', occupations=FermiDirac(0.02), mixer=Mixer(0.05, 8, 100), ) atoms = bulk(element, struct) # sc,fcc,bcc,tetragonal,bct,hcp,rhmbohedral,orthorhombic # mlc, diamond,zincblende,rocksalt,cesiumchloride, fluorite, wurtzite atoms.set_calculator(calc) atoms.get_potential_energy() # Get the valence band maximum efermi = calc.get_fermi_level() Nk = len(calc.get_ibz_k_points()) Ns = calc.get_number_of_spins()
class GWBands: """This class defines the GW_bands properties""" def __init__(self, calc=None, comm=None, gw_file=None, kpoints=None, bandrange=None): self.calc = GPAW(calc, communicator=comm, txt=None) if gw_file is not None: self.gw_file = pickle.load(open(gw_file, 'rb'),encoding='bytes') self.kpoints = kpoints if bandrange is None: self.bandrange = np.arange(self.calc.get_number_of_bands()) else: self.bandrange = bandrange self.gd = self.calc.wfs.gd.new_descriptor() self.kd = self.calc.wfs.kd self.acell_cv = self.gd.cell_cv self.bcell_cv = 2 * np.pi * self.gd.icell_cv self.vol = self.gd.volume self.BZvol = (2 * np.pi)**3 / self.vol def find_k_along_path(self, plot_BZ=True): """Finds the k-points along the bandpath present in the original calculation""" kd = self.kd acell_cv = self.acell_cv bcell_cv = self.bcell_cv kpoints = self.kpoints if plot_BZ: """Plotting the points in the Brillouin Zone""" kp_1bz = to1bz(kd.bzk_kc, acell_cv) bzk_kcv = np.dot(kd.bzk_kc, bcell_cv) kp_1bz_v = np.dot(kp_1bz, bcell_cv) import matplotlib.pyplot as plt plt.plot(bzk_kcv[:, 0], bzk_kcv[:, 1], 'xg') plt.plot(kp_1bz_v[:, 0], kp_1bz_v[:, 1], 'ob') for ik in range(1, len(kpoints)): kpoint1_v = np.dot(kpoints[ik], bcell_cv) kpoint2_v = np.dot(kpoints[ik - 1], bcell_cv) plt.plot([kpoint1_v[0], kpoint2_v[0]], [kpoint1_v[1], kpoint2_v[1]], '--vr') """Finding the points along given directions""" print('Finding the kpoints along the path') N_c = kd.N_c wpts_xc = kpoints x_x = [] k_xc = [] k_x = [] x = 0. X = [] for nwpt in range(1, len(wpts_xc)): X.append(x) to_c = wpts_xc[nwpt] from_c = wpts_xc[nwpt - 1] vec_c = to_c - from_c print('From ', from_c, ' to ', to_c) Nv_c = (vec_c * N_c).round().astype(int) Nv = abs(gcd(gcd(Nv_c[0], Nv_c[1]), Nv_c[2])) print(Nv, ' points found') dv_c = vec_c / Nv dv_v = np.dot(dv_c, bcell_cv) dx = np.linalg.norm(dv_v) if nwpt == len(wpts_xc) - 1: # X.append(Nv * dx) Nv += 1 for n in range(Nv): k_c = from_c + n * dv_c bzk_c = to1bz(np.array([k_c]), acell_cv)[0] ikpt = kd.where_is_q(bzk_c, kd.bzk_kc) x_x.append(x) k_xc.append(k_c) k_x.append(ikpt) x += dx X.append(x_x[-1]) if plot_BZ is True: for ik in range(len(k_xc)): ktemp_xcv = np.dot(k_xc[ik], bcell_cv) plt.plot(ktemp_xcv[0], ktemp_xcv[1], 'xr', markersize=10) plt.show() return x_x, k_xc, k_x, X def get_dft_eigenvalues(self): Nk = len(self.calc.get_ibz_k_points()) bands = np.arange(self.bandrange[0], self.bandrange[-1]) e_kn = np.array([self.calc.get_eigenvalues(kpt=k)[bands] for k in range(Nk)]) return e_kn def get_vacuum_level(self, plot_pot=False): """Finds the vacuum level through Hartree potential""" vHt_g = self.calc.get_electrostatic_potential() vHt_z = np.mean(np.mean(vHt_g, axis=0), axis=0) if plot_pot: import matplotlib.pyplot as plt plt.plot(vHt_z) plt.show() return vHt_z[0] def get_spinorbit_corrections(self, return_spin=True, return_wfs=False, bands=None, gwqeh_file=None, dft=False, eig_file=None): """Gets the spinorbit corrections to the eigenvalues""" calc = self.calc bandrange = self.bandrange if not dft: try: e_kn = self.gw_file['qp'][0] except: e_kn = self.gw_file[b'qp'][0] else: if eig_file is not None: e_kn = pickle.load(open(eig_file))[0] else: e_kn = self.get_dft_eigenvalues()[:,bandrange[0]:bandrange[-1]] eSO_nk, s_nk, v_knm = get_spinorbit_eigenvalues( calc, return_spin=return_spin, return_wfs=return_wfs, bands=range(bandrange[0], bandrange[-1]+1), gw_kn=e_kn) e_kn = eSO_nk.T return e_kn, v_knm def get_gw_bands(self, nk_Int=50, interpolate=False, SO=False, gwqeh_file=None, dft=False, eig_file=None, vac=False): """Getting Eigenvalues along the path""" kd = self.kd if SO: e_kn, v_knm = self.get_spinorbit_corrections(return_wfs=True, dft=dft, eig_file=eig_file) if gwqeh_file is not None: gwqeh_file = pickle.load(open(gwqeh_file)) eqeh_noSO_kn = gwqeh_file['qp_sin'][0] * Ha eqeh_kn = np.zeros_like(e_kn) eqeh_kn[:, ::2] = eqeh_noSO_kn eqeh_kn[:, 1::2] = eqeh_noSO_kn e_kn += eqeh_kn elif gwqeh_file is not None: gwqeh_file = pickle.load(open(gwqeh_file)) e_kn = gwqeh_file['Qp_sin'][0] * Ha elif eig_file is not None: e_kn = pickle.load(open(eig_file))[0] else: if not dft: try: e_kn = self.gw_file['qp'][0] except: e_kn = self.gw_file[b'qp'][0] else: e_kn = self.get_dft_eigenvalues() e_kn = np.sort(e_kn, axis=1) bandrange = self.bandrange ef = self.calc.get_fermi_level() if vac: evac = self.get_vacuum_level() else: evac = 0.0 x_x, k_xc, k_x, X = self.find_k_along_path(plot_BZ=False) k_ibz_x = np.zeros_like(k_x) eGW_kn = np.zeros((len(k_x), e_kn.shape[1])) for n in range(e_kn.shape[1]): for ik in range(len(k_x)): ibzkpt = kd.bz2ibz_k[k_x[ik]] k_ibz_x[ik] = ibzkpt eGW_kn[ik, n] = e_kn[ibzkpt, n] N_occ = (eGW_kn[0] < ef).sum() print(N_occ, bandrange[0]) # N_occ = int(self.calc.get_number_of_electrons()/2) print(' ') if SO: print('The number of Occupied bands is:', N_occ + 2.*bandrange[0]) else: print('The number of Occupied bands is:', N_occ + bandrange[0]) gap = (eGW_kn[:, N_occ].min() - eGW_kn[:, N_occ - 1].max()) print('The bandgap is: %f' % gap) vbm = eGW_kn[:, N_occ - 1].max() - evac cbm = eGW_kn[:, N_occ].min() - evac if interpolate: xfit_k = np.linspace(x_x[0], x_x[-1], nk_Int) xfit_k = np.append(xfit_k, x_x) xfit_k = np.sort(xfit_k) nk_Int = len(xfit_k) efit_kn = np.zeros((nk_Int, eGW_kn.shape[1])) for n in range(eGW_kn.shape[1]): fit_e = InterpolatedUnivariateSpline(x_x, eGW_kn[:, n]) efit_kn[:, n] = fit_e(xfit_k) results = {'x_k': xfit_k, 'X': X, 'e_kn': efit_kn - evac, 'ef': ef - evac, 'gap': gap, 'vbm': vbm, 'cbm': cbm} return results else: results = {'x_k': x_x, 'X': X, 'k_ibz_x': k_ibz_x, 'e_kn': eGW_kn - evac, 'ef': ef - evac, 'gap': gap, 'vbm': vbm, 'cbm': cbm} return results
import numpy as np from ase import Atoms from ase.units import Bohr from gpaw.jellium import JelliumSlab from gpaw import GPAW, PW rs = 5.0 * Bohr # Wigner-Seitz radius h = 0.2 # grid-spacing a = 8 * h # lattice constant v = 3 * a # vacuum L = 10 * a # thickness k = 12 # number of k-points (k*k*1) ne = a**2 * L / (4 * np.pi / 3 * rs**3) jellium = JelliumSlab(ne, z1=v, z2=v + L) surf = Atoms(pbc=(True, True, False), cell=(a, a, v + L + v)) surf.calc = GPAW(mode=PW(400.0), background_charge=jellium, xc='LDA_X+LDA_C_WIGNER', eigensolver='dav', kpts=[k, k, 1], h=h, convergence={'density': 0.001}, nbands=int(ne / 2) + 15, txt='surface.txt') e = surf.get_potential_energy() surf.calc.write('surface.gpw')
atoms.center() atoms.set_pbc(1) r = [1, 1, 1] atoms = atoms.repeat(r) n = [240 * ri for ri in r] # nbands (>=1683) is the number of bands per cluster nbands = 3 * 6 * 6 * 16 # 1728 for ri in r: nbands = nbands * ri mixer = Mixer(beta=0.1, nmaxold=5, weight=100.0) # the next three lines decrease memory usage es = RMMDIIS(keep_htpsit=False) calc = GPAW( nbands=nbands, # uncomment next two lines to use lcao/sz # mode='lcao', # basis='sz', gpts=tuple(n), maxiter=5, width=0.1, xc='LDA', mixer=mixer, eigensolver=es, txt=prefix + '.txt') atoms.set_calculator(calc) try: pot = atoms.get_potential_energy() except ConvergenceError: pass
from gpaw.poisson import PoissonSolver from gpaw.lcaotddft.dipolemomentwriter import DipoleMomentWriter from gpaw.lcaotddft.wfwriter import WaveFunctionWriter from gpaw.tddft.spectrum import photoabsorption_spectrum from gpaw.mpi import world from gpaw.test import equal # Atoms atoms = molecule('Na2') atoms.center(vacuum=4.0) # Ground-state calculation calc = GPAW(nbands=2, h=0.4, setups=dict(Na='1'), basis='dzp', mode='lcao', poissonsolver=PoissonSolver(eps=1e-16), convergence={'density': 1e-8}, txt='gs.out') atoms.set_calculator(calc) energy = atoms.get_potential_energy() calc.write('gs.gpw', mode='all') # Time-propagation calculation td_calc = LCAOTDDFT('gs.gpw', txt='td.out') DipoleMomentWriter(td_calc, 'dm.dat') WaveFunctionWriter(td_calc, 'wf.ulm') WaveFunctionWriter(td_calc, 'wf_split.ulm', split=True) td_calc.absorption_kick(np.ones(3) * 1e-5) td_calc.propagate(20, 3) td_calc.write('td.gpw', mode='all') td_calc.propagate(7, 3)
a = 5.404 bulk = Atoms(symbols='Si8', scaled_positions=[(0, 0, 0), (0, 0.5, 0.5), (0.5, 0, 0.5), (0.5, 0.5, 0), (0.25, 0.25, 0.25), (0.25, 0.75, 0.75), (0.75, 0.25, 0.75), (0.75, 0.75, 0.25)], 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') bulk, calc = restart('temp.gpw', fixdensity=True) e2 = bulk.get_potential_energy() eigs2 = calc.get_eigenvalues(kpt=0) print('Orginal', eigs) print('Fixdensity', eigs2) print('Difference', eigs2 - eigs)
density_number = int(sys.argv[3]) #density_number = 5.4, 1.37 k_pts = {'density': density_number, 'even': True} smear = 0.1 system_id = int((sys.argv[1])) system_name = 'fesi_id' + str(system_id) final_db = str(sys.argv[2]) print(time.strftime("%d/%m/%Y")) print(time.strftime("%H:%M:%S")) print('The id for this script is: ' + str(system_id)) calc = GPAW(mode=PW(e_cut), nbands=nbands, xc='PBE', spinpol=True, kpts=k_pts, occupations=FermiDirac(smear), txt=system_name + '.out') if os.path.isfile('./' + system_name + '.gpw'): #Recover past done calculations if available #bulk_mat, calc = restart(system_name + '.gpw', txt = None) #bulk_mat.set_calculator(calc) traj = Trajectory(system_name + '.traj') bulk_mat = traj[-1] bulk_mat.set_calculator(calc) else: #Initialize new calculations db = connect(final_db)
d = 1.2 logo = Atoms() for i, line in enumerate(ase.split('\n')): for j, c in enumerate(line): if c == 'H': logo.append(Atom('H', [d * j, d * i, 0])) logo.set_cell((15, 15, 2)) logo.center() #logo.center(vacuum=2.0) #view(logo) if 1: from gpaw import GPAW calc = GPAW() logo.set_calculator(calc) e = logo.get_potential_energy() calc.write('logo2.gpw') if 0: from gpaw import GPAW calc = GPAW('logo2.gpw', idiotproof=0) if 1: print(calc.density.nt_sg.shape) n = calc.density.nt_sg[0, :, :, 10] #1c4e63 c0 = np.array([19, 63, 82.0]).reshape((3, 1, 1)) / 255 c1 = np.array([1.0, 1, 0]).reshape((3, 1, 1)) a = c0 + n / n.max() * (c1 - c0)
from gpaw import GPAW, restart from gpaw.test import gen from gpaw import setup_paths from gpaw.mpi import world xc = 'GLLBSC' gen('C', xcname=xc) setup_paths.insert(0, '.') # Calculate ground state atoms = bulk('C', 'diamond', a=3.567) # We want sufficiently many grid points that the calculator # can use wfs.world for the finegd, to test that part of the code. calc = GPAW(h=0.2, kpts=(4, 4, 4), xc=xc, nbands=8, parallel=dict(domain=min(world.size, 2), band=1), eigensolver=Davidson(niter=4)) atoms.set_calculator(calc) atoms.get_potential_energy() calc.write('Cgs.gpw') # Calculate accurate KS-band gap from band structure calc = GPAW('Cgs.gpw', kpts={ 'path': 'GX', 'npoints': 12 }, fixdensity=True, symmetry='off', nbands=8,
from gpaw import GPAW, Mixer, FermiDirac tag = 'Ru001' adsorbate_heights = {'H': 1.0, 'N': 1.108, 'O': 1.257} slab = hcp0001('Ru', size=(2, 2, 4), a=2.72, c=1.58*2.72, vacuum=7.0, orthogonal=True) slab.center(axis=2) if len(argv) > 1: adsorbate = argv[1] tag = adsorbate + tag add_adsorbate(slab, adsorbate, adsorbate_heights[adsorbate], 'hcp') slab.set_constraint(FixAtoms(mask=slab.get_tags() >= 3)) calc = GPAW(xc='PBE', h=0.2, mixer=Mixer(0.1, 5, weight=100.0), stencils=(3, 3), occupations=FermiDirac(width=0.1), kpts=[4, 4, 1], eigensolver='cg', txt=tag + '.txt') slab.set_calculator(calc) opt = LBFGS(slab, logfile=tag + '.log', trajectory=tag + '.traj') opt.run(fmax=0.05) calc.write(tag)
from __future__ import print_function from ase import Atoms from gpaw import GPAW from gpaw.test import equal s = Atoms('Cl') s.center(vacuum=3) c = GPAW(xc={'name': 'PBE', 'stencil': 1}, nbands=-4, charge=-1, h=0.3) s.set_calculator(c) e = s.get_potential_energy() niter = c.get_number_of_iterations() print(e, niter) energy_tolerance = 0.0003 niter_tolerance = 0 equal(e, -2.89336, energy_tolerance)
from ase.build import molecule #s = UPFSetupData('/home/askhl/parse-upf/h_lda_v1.uspp.F.UPF') upfsetups = { 'H': UPFSetupData('H.pz-hgh.UPF'), 'O': UPFSetupData('O.pz-hgh.UPF') } system = molecule('H2O') system.center(vacuum=3.5) calc = GPAW( txt='-', nbands=6, setups=upfsetups, #setups='paw', #hund=True, #mixer=MixerSum(0.1, 5, 20.0), #eigensolver='cg', #occupations=FermiDirac(0.1), #charge=1-1e-12, #eigensolver='rmm-diis', gpts=h2gpts(0.12, system.get_cell(), idiv=8), poissonsolver=PoissonSolver(relax='GS', eps=1e-7), xc='oldLDA', #nbands=4 ) system.set_calculator(calc) system.get_potential_energy()
from gpaw import GPAW calc = GPAW('groundstate.rutile.gpw') atoms = calc.get_atoms() path = atoms.cell.bandpath(density=7) path.write('path.rutile.json') calc.set(kpts=path, fixdensity=True, symmetry='off') atoms.get_potential_energy() bs = calc.band_structure() bs.write('bs.rutile.json')
# Initial state: # 2x2-Al(001) surface with 1 layer and an # Au atom adsorbed in a hollow site: slab = fcc100('Al', size=(2, 2, 2)) slab.center(axis=2, vacuum=3.0) add_adsorbate(slab, 'Au', 1.6, 'hollow') # Make sure the structure is correct: view(slab) # Fix the Al atoms: mask = [atom.symbol == 'Al' for atom in slab] print(mask) fixlayer = FixAtoms(mask=mask) slab.set_constraint(fixlayer) # Use GPAW: calc = GPAW(mode=PW(200), kpts=(2, 2, 1), xc='PBE', txt='hollow.txt') slab.set_calculator(calc) qn = QuasiNewton(slab, trajectory='hollow.traj') # Find optimal height. The stopping criterion is: the force on the # Au atom should be less than 0.05 eV/Ang qn.run(fmax=0.05) calc.write('hollow.gpw') # Write gpw output after the minimization print('energy:', slab.get_potential_energy()) print('height:', slab.positions[-1, 2] - slab.positions[0, 2])
from ase.build import molecule from gpaw import GPAW, PW from gpaw.mpi import world a = molecule('H', pbc=1) a.center(vacuum=2) comm = world.new_communicator([world.rank]) e0 = 0.0 a.calc = GPAW(mode=PW(250), communicator=comm, txt=None) e0 = a.get_potential_energy() e0 = world.sum(e0) / world.size a.calc = GPAW(mode=PW(250), eigensolver='rmm-diis', basis='szp(dzp)', txt='%d.txt' % world.size) e = a.get_potential_energy() f = a.get_forces() assert abs(e - e0) < 7e-5, abs(e - e0) assert abs(f).max() < 1e-10, abs(f).max()
from __future__ import print_function import numpy as np from ase import Atoms from gpaw import GPAW from gpaw.test import equal 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)):
from __future__ import print_function import numpy as np import ase.units as units from gpaw import restart, GPAW from gpaw.poisson import PoissonSolver from gpaw.dipole_correction import DipoleCorrection energies = [] for name in ['zero', 'periodic', 'corrected']: if name == 'corrected': calc = GPAW(name, txt=None, poissonsolver=DipoleCorrection(PoissonSolver(), 2)) else: calc = GPAW(name, txt=None) energies.append(calc.get_potential_energy()) print(energies) assert abs(energies[1] - energies[0]) < 0.003 assert abs(energies[2] - energies[0] - 0.0409) < 0.003 efermi = calc.get_fermi_level() calc.restore_state() v = (calc.hamiltonian.vHt_g * units.Hartree).mean(0).mean(0) w1 = v[0] - efermi w2 = v[-1] - efermi print(w1, w2) assert abs(w1 - 4.359) < 0.01 assert abs(w2 - 2.556) < 0.01
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
from gpaw import GPAW, restart, FD from ase.build import molecule from gpaw.test import equal Eini0 = -17.8037610364 energy_eps = 0.0005 esolvers = ['cg', 'rmm-diis', 'dav'] calc = GPAW(xc='LDA', h=0.21, eigensolver='cg', convergence={'eigenstates': 3.5e-5, 'energy': energy_eps}, mode=FD(force_complex_dtype=True)) mol = molecule('N2') 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, energy_eps * calc.get_number_of_electrons()) calc.write('N2_complex.gpw', mode='all') for esolver in esolvers: mol, calc = restart('N2_complex.gpw') assert calc.wfs.dtype == complex assert calc.wfs.kpt_u[0].psit_nG.dtype == complex calc.set(convergence={'eigenstates': 3.5e-9, 'energy': energy_eps})