from ase import * from ase.dft.bee import BEEF_Ensemble from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.test import equal import numpy as np xc = 'mBEEF' conv = {'eigenstates':1.e-6, 'density':1.e-6, 'energy':1.e-6} h = 0.18 tol1 = 1.e-3 tol2 = 1.e-1 # N2 molecule n2 = Cluster(Atoms('N2',[[0.,0.,0.],[0.,0.,1.09]])) n2.minimal_box(3.0, h=h) cell = n2.get_cell() calc = GPAW(h=h, xc='PBE', convergence=conv) n2.set_calculator(calc) n2.get_potential_energy() n2.calc.set(xc=xc) e_n2 = n2.get_potential_energy() f = n2.get_forces() ens = BEEF_Ensemble(n2) de_n2 = ens.get_ensemble_energies() del n2, calc, ens # N atom n = Atoms('N') n.set_cell(cell) n.center()
def gen_test_data(datadir: str, params_fd: dict, supercell): from gpaw.elph.electronphonon import ElectronPhononCoupling params_gs = copy.deepcopy(params_fd) atoms = Cluster(ase.build.bulk('C')) calc_gs = GPAW(**params_gs) atoms.calc = calc_gs atoms.get_potential_energy() atoms.calc.write("gs.gpw", mode="all") # Make sure the real space grid matches the original. # (basically we multiply the number of grid points in each dimension by the supercell dimension) params_fd['gpts'] = calc_gs.wfs.gd.N_c * list(supercell) if 'h' in params_fd: del params_fd['h'] del calc_gs if world.rank == 0: os.makedirs(datadir, exist_ok=True) calc_fd = GPAW(**params_fd) elph = ElectronPhononCoupling(atoms, calc=calc_fd, supercell=supercell, calculate_forces=True, name=f'{datadir}/elph') elph.run() calc_fd.wfs.gd.comm.barrier() elph = ElectronPhononCoupling(atoms, calc=calc_fd, supercell=supercell) elph.set_lcao_calculator(calc_fd) elph.calculate_supercell_matrix(dump=1)
def read(self, filename='trajectory.vmol', position=0): """Read atom configurations of step position""" self.file = None f = open(filename) # find coordinates loa = Cluster([]) coords = False for l in f.readlines(): if coords: w = l.split() loa.append(Atom(w[3].replace ("\n", "" ), (float(w[0]), float(w[1]), float(w[2]))))
def read(self, filename='trajectory.vmol', position=0): """Read atom configurations of step position""" self.file = None f = open(filename) # find coordinates loa = Cluster([]) coords = False for l in f.readlines(): if coords: w = l.split() loa.append(Atom(w[3].replace("\n", ""), (float(w[0]), float(w[1]), float(w[2]))))
def read_viewmol(self, filename): f = open(filename) # read the definition first definition=False for line in f: w = line.split() if not definition: if w[0] == '$coord': definition=True self.scale = float(w[1]) loa = Cluster([]) else: if w[0] == '$grad': # definition ends here self.definition = loa break else: # we assume this is a coordinate entry coo = (float(w[0]), float(w[1]), float(w[2])) loa.append(Atom(w[3], coo)) # get the iterations cycle = False for line in f: w = line.split() if not cycle: # search for the cycle keyword if w[0] == 'cycle=': cycle=True n_coo=0 n_F=0 self.images.append(Cluster([])) else: if n_coo < len(self.definition): n_coo += 1 coo = (float(w[0]), float(w[1]), float(w[2])) self[-1].append(Atom(w[3], coo)) elif n_F < len(self.definition): F = (float(w[0]), float(w[1]), float(w[2])) self[-1][n_F].F = F n_F += 1 if n_F == len(self.definition): cycle=False
def read_viewmol(self, filename): f = open(filename) # read the definition first definition = False for line in f: w = line.split() if not definition: if w[0] == '$coord': definition = True self.scale = float(w[1]) loa = Cluster([]) else: if w[0] == '$grad': # definition ends here self.definition = loa break else: # we assume this is a coordinate entry coo = (float(w[0]), float(w[1]), float(w[2])) loa.append(Atom(w[3], coo)) # get the iterations cycle = False for line in f: w = line.split() if not cycle: # search for the cycle keyword if w[0] == 'cycle=': cycle = True n_coo = 0 n_F = 0 self.images.append(Cluster([])) else: if n_coo < len(self.definition): n_coo += 1 coo = (float(w[0]), float(w[1]), float(w[2])) self[-1].append(Atom(w[3], coo)) elif n_F < len(self.definition): F = (float(w[0]), float(w[1]), float(w[2])) self[-1][n_F].F = F n_F += 1 if n_F == len(self.definition): cycle = False
import os import sys from ase import Atoms, Atom, QuasiNewton, PickleTrajectory from gpaw import * from gpaw.cluster import Cluster from gpaw.utilities.viewmol import ViewmolTrajectory, write_viewmol s = Cluster([Atom('H'), Atom('H',(0,0,3))]) s.minimal_box(2) c = GPAW(h=0.3, nbands=2) s.set_calculator(c) vfname='traj.vmol' pfname='traj.pickle' vmt = ViewmolTrajectory(s, vfname) traj = PickleTrajectory(pfname, 'w', s) #c.attach(vmt.add, 100000) #sys.exit() # Find the theoretical bond length: dyn = QuasiNewton(s) dyn.attach(traj.write) dyn.attach(vmt.add) dyn.run(fmax=0.05) traj = PickleTrajectory(pfname, 'r') vfname2='pickle.vmol' write_viewmol(traj, vfname2)
# Wigner-Seitz ---------------------------------------- if 1: ws = WignerSeitz(calc.density.finegd, mol, calc) vr = ws.get_effective_volume_ratios() parprint('Wigner-Seitz:', vr) if len(lastres): equal(vr, lastres.pop(0), 1.e-10) results.append(vr) return results # calculate parprint('fresh:') mol = Cluster(molecule('H2O')) mol.minimal_box(3, h=h) calc = GPAW(nbands=6, h = h, txt=None) calc.calculate(mol) calc.write(gpwname) lastres = run() # load previous calculation parprint('reloaded:') calc = GPAW(gpwname, txt=None) mol = calc.get_atoms() run(lastres)
# Wigner-Seitz ---------------------------------------- if 1: ws = WignerSeitz(calc.density.finegd, mol, calc) vr = ws.get_effective_volume_ratios() parprint('Wigner-Seitz:', vr) if len(lastres): equal(vr, lastres.pop(0), 1.e-10) results.append(vr) return results mol = Cluster(molecule('H2O')) mol.minimal_box(2.5, h=h) # calculate if 1: parprint('### fresh:') calc = GPAW(nbands=6, h=h, txt=None) if 1: calc.calculate(mol) calc.write(gpwname) lastres = run() # load previous calculation if 1: parprint('### reloaded:') calc = GPAW(gpwname, txt=None)
CO.translate(-CO.get_center_of_mass()) p = CO.positions.copy() for i in range(2): equal(p[i, 1], 0, 1e-10) equal(p[i, 2], 0, 1e-10) # rotate the nuclear axis to the direction (1,1,1) CO.rotate(p[1] - p[0], (1, 1, 1)) q = CO.positions.copy() for c in range(3): equal(q[0, c], p[0, 0] / sqrt(3), 1e-10) equal(q[1, c], p[1, 0] / sqrt(3), 1e-10) # minimal box b = 4.0 CO = Cluster([Atom('C', (1, 0, 0)), Atom('O', (1, 0, R))]) CO.minimal_box(b) cc = CO.get_cell() for c in range(3): width = 2 * b if c == 2: width += R equal(cc[c, c], width, 1e-10) # minimal box, ensure multiple of 4 h = .13 b = [2, 3, 4] CO.minimal_box(b, h=h) cc = CO.get_cell() for c in range(3): # print "cc[c,c], cc[c,c] / h % 4 =", cc[c, c], cc[c, c] / h % 4
from __future__ import print_function from ase import Atom from ase.neb import SingleCalculatorNEB from ase.optimize import FIRE from gpaw import GPAW from gpaw.cluster import Cluster txt = None mol = Cluster( [Atom('H'), Atom('H', [1, 0, 0]), Atom('H', [.5, .5, .5])], cell=[2, 2, 2], pbc=True) def set_calculators(all=False): c = GPAW(h=.3, convergence={ 'eigenstates': 0.1, 'energy': 0.1, 'density': 0.01 }, txt=txt) # c = EMT() n = len(images) if not all: n -= 2 neb.set_calculators([c] * n)
from gpaw import GPAW, FermiDirac from gpaw.cluster import Cluster from gpaw.lrtddft import LrTDDFT from gpaw.lrtddft.excited_state import ExcitedState box = 5. # box dimension h = 0.25 # grid spacing width = 0.01 # Fermi width nbands = 6 # bands in GS calculation nconv = 4 # bands in GS calculation to converge R = 2.99 # starting distance iex = 1 # excited state index d = 0.01 # step for numerical force evaluation exc = 'LDA' # xc for the linear response TDDFT kernel s = Cluster([Atom('Na'), Atom('Na', [0, 0, R])]) s.minimal_box(box, h=h) c = GPAW(h=h, nbands=nbands, eigensolver='cg', occupations=FermiDirac(width=width), setups={'Na': '1'}, convergence={'bands':nconv}) c.calculate(s) lr = LrTDDFT(c, xc=exc, eps=0.1, jend=nconv-1) ex = ExcitedState(lr, iex, d=d) s.set_calculator(ex) ftraj='relax_ex' + str(iex) ftraj += '_box' + str(box) + '_h' + str(h) ftraj += '_d' + str(d) + '.traj'
from ase.build import molecule from ase import optimize from ase.vibrations.infrared import InfraRed from gpaw.cluster import Cluster from gpaw import GPAW, FermiDirac h = 0.22 atoms = Cluster(molecule('H2')) atoms.minimal_box(3.5, h=h) # relax the molecule calc = GPAW(h=h, occupations=FermiDirac(width=0.1)) atoms.calc = calc dyn = optimize.FIRE(atoms) dyn.run(fmax=0.05) atoms.write('relaxed.traj') # finite displacement for vibrations ir = InfraRed(atoms) ir.run()
def do_elph_symmetry( data_subdir: str, params_fd: dict, supercell, all_displacements: tp.Iterable[AseDisplacement], symmetry_type: tp.Optional[str], ): atoms = Cluster(ase.build.bulk('C')) # a supercell exactly like ElectronPhononCoupling makes supercell_atoms = atoms * supercell quotient_perms = list( interop.ase_repeat_translational_symmetry_perms(len(atoms), supercell)) # Make sure the grid matches our calculations (we repeated the grid of the groundstate) params_fd = copy.deepcopy(params_fd) params_fd['gpts'] = GPAW('gs.gpw').wfs.gd.N_c * list(supercell) if 'h' in params_fd: del params_fd['h'] wfs_with_sym = get_wfs_with_sym(params_fd=params_fd, supercell_atoms=supercell_atoms, symmetry_type=symmetry_type) calc_fd = GPAW(**params_fd) # GPAW displaces the center cell for some reason instead of the first cell elph = ElectronPhononCoupling(atoms, calc=calc_fd, supercell=supercell, calculate_forces=True) displaced_cell_index = elph.offset del elph # just showing that we don't use these anymore del calc_fd get_displaced_index = lambda prim_atom: displaced_cell_index * len( atoms) + prim_atom all_displacements = list(all_displacements) disp_atoms = [get_displaced_index(disp.atom) for disp in all_displacements] disp_carts = [ disp.cart_displacement(DISPLACEMENT_DIST) for disp in all_displacements ] disp_values = [ read_elph_input(data_subdir, disp) for disp in all_displacements ] full_Vt = np.empty((len(supercell_atoms), 3) + disp_values[0][0].shape) full_dH = np.empty((len(supercell_atoms), 3), dtype=object) full_forces = np.empty((len(supercell_atoms), 3) + disp_values[0][2].shape) lattice = supercell_atoms.get_cell()[...] oper_cart_rots = interop.gpaw_op_scc_to_cart_rots( wfs_with_sym.kd.symmetry.op_scc, lattice) if world.rank == 0: full_values = symmetry.expand_derivs_by_symmetry( disp_atoms, # disp -> atom disp_carts, # disp -> 3-vec disp_values, # disp -> T (displaced value, optionally minus equilibrium value) elph_callbacks(wfs_with_sym, supercell), # how to work with T oper_cart_rots, # oper -> 3x3 oper_perms=wfs_with_sym.kd.symmetry.a_sa, # oper -> atom' -> atom quotient_perms=quotient_perms, ) for a in range(len(full_values)): for c in range(3): full_Vt[a][c] = full_values[a][c][0] full_dH[a][c] = full_values[a][c][1] full_forces[a][c] = full_values[a][c][2] else: # FIXME # the symmetry part is meant to be done in serial but we should return back to # our original parallel state after it... pass return full_Vt, full_dH, full_forces
import sys import numpy as np from ase.structure import molecule from ase.parallel import parprint from gpaw import GPAW, PW from gpaw.analyse.multipole import Multipole from gpaw.cluster import Cluster from gpaw.test import equal h = 0.3 s = Cluster(molecule('H2O')) s.minimal_box(3., h) gpwname = 'H2O_h' + str(h) + '.gpw' try: # XXX check why this fails in parallel calc = GPAW(gpwname + 'failsinparallel', txt=None) atoms = calc.get_atoms() calc.density.set_positions(atoms.get_scaled_positions() % 1.0) calc.density.interpolate_pseudo_density() calc.density.calculate_pseudo_charge() except IOError: calc = GPAW(h=h, charge=0, txt=None) calc.calculate(s) calc.write(gpwname) dipole_c = calc.get_dipole_moment() parprint('Dipole', dipole_c)
from __future__ import print_function import sys import numpy as np from ase.structure import molecule from ase.parallel import parprint from gpaw import GPAW, PW from gpaw.analyse.multipole import Multipole from gpaw.cluster import Cluster from gpaw.test import equal h = 0.3 s = Cluster(molecule("H2O")) s.minimal_box(3.0, h) gpwname = "H2O_h" + str(h) + ".gpw" try: # XXX check why this fails in parallel calc = GPAW(gpwname + "failsinparallel", txt=None) atoms = calc.get_atoms() calc.density.set_positions(atoms.get_scaled_positions() % 1.0) calc.density.interpolate_pseudo_density() calc.density.calculate_pseudo_charge() except IOError: calc = GPAW(h=h, charge=0, txt=None) calc.calculate(s) calc.write(gpwname) dipole_c = calc.get_dipole_moment()
from ase import Atom from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.test import equal h=0.40 txt = None txt = 'mgga_sc.txt' s = Cluster([Atom('H')]) s.minimal_box(4., h=h) s.set_initial_magnetic_moments([1]) # see https://trac.fysik.dtu.dk/projects/gpaw/ticket/244 s.set_cell((8.400000,8.400000,8.400000)) c = GPAW(xc='TPSS', h=h, nbands=5, txt=txt, eigensolver='rmm-diis', fixmom=True, maxiter=300) c.calculate(s) cpbe = GPAW(xc='PBE', h=h, nbands=5, txt=txt, eigensolver='rmm-diis', fixmom=True, maxiter=300) cpbe.calculate(s) cpbe.set(xc='TPSS') cpbe.calculate() print "Energy difference", (cpbe.get_potential_energy() - c.get_potential_energy())
butadiene = """10 C 3.649801161546418 5.442281389577507 3.863313703750026 C 5.051651240044169 5.368220758269772 4.162165876906096 C 5.750174626862403 4.162261915959347 4.240449977068684 C 7.150130182125531 4.155384186721486 4.537328602062397 H 3.218154657585170 4.565210696328925 3.522601038049320 H 3.077656122062729 6.375092902842770 3.826039498180272 H 5.478464901706067 6.370680001794822 4.422235395756437 H 5.320549047980879 3.220584852467720 3.974551561510350 H 7.723359150977955 3.224855971783890 4.574146712279462 H 7.580803493981530 5.034479218283977 4.877211530909463 """ h = 0.3 atoms = Cluster(read_xyz(StringIO.StringIO(butadiene))) atoms.minimal_box(3.0, h) atoms.set_calculator(GPAW(h=h)) if 0: dyn = FIRE(atoms) dyn.run(fmax=0.05) atoms.write("butadiene.xyz") vibname = "fcvib" vib = Vibrations(atoms, name=vibname) vib.run() # Modul a = FranckCondon(atoms, vibname, minfreq=250) # excited state forces
import numpy as np from ASE import Atom from gpaw.utilities import equal from gpaw.cluster import Cluster from gpaw import Calculator from gpaw.analyse.expandyl import ExpandYl R = 1. H2 = Cluster([Atom('H',(0,0,0)), Atom('H',(0,0,R))]) H2.minimal_box(3.) calc = Calculator(h=0.2, width=0.01, nbands=2) H2.SetCalculator(calc) H2.GetPotentialEnergy() yl = ExpandYl(H2.center_of_mass(), calc.wfs.gd, Rmax=2.5) gl = [] for n in range(calc.nbands): psit_G = calc.kpt_u[0].psit_nG[n] norm = calc.wfs.gd.integrate(psit_G**2) g = yl.expand(psit_G) gsum = np.sum(g) # allow for 10 % inaccuracy in the norm print "norm, sum=", norm, gsum equal(norm, gsum, 0.1) gl.append(g/gsum*100)
def main__raman_ch4(structure, supercell, log): import ase.build from gpaw.lrtddft.spectrum import polarizability from gpaw.cluster import Cluster from gpaw import GPAW, FermiDirac #============================================= # Settings # Input structure relax_grid_sep = 0.22 # GPAW finite grid size vacuum_sep = 3.5 pbc = False if structure == 'ch4': def get_unrelaxed_structure(): atoms = Cluster(ase.build.molecule('CH4')) atoms.minimal_box(vacuum_sep, h=relax_grid_sep) return atoms elif structure == 'mos2': def get_unrelaxed_structure(): atoms = Cluster(ase.build.mx2('MoS2')) atoms.center(vacuum=vacuum_sep, axis=2) return atoms # Calculator (general settings) make_calc = functools.partial(GPAW, occupations=FermiDirac(width=0.1), symmetry={'point_group': False}, txt=log, ) # Relaxation settings make_calc_relax = functools.partial(make_calc, h=relax_grid_sep, ) # Args for computations on displaced structures raman_grid_sep = 0.25 # In the example, they use a larger spacing here than during relaxation. # (TODO: but why? On CH4 I observe that this to leads to equilibrium forces of # 0.067 ev/A, which seems to compromise our "energy minimum" state...) num_converged_bands = 10 num_total_bands = 20 make_calc_raman = functools.partial(make_calc, h=raman_grid_sep, convergence={ 'eigenstates': 1.e-5, 'bands': num_converged_bands, }, eigensolver='cg', nbands=num_total_bands, ) supercell_matrix = [[supercell[0], 0, 0], [0, supercell[1], 0], [0, 0, supercell[2]]] displacement_distance = 1e-2 # ---------- # Excitation settings (for polarizability) ex_kw = {'restrict': {'jend':num_converged_bands-1}} omega = 5.0 # eV get_polarizability = functools.partial(polarizability, omega=omega, form='v', tensor=True) subtract_equilibrium_polarizability = False #============================================= # Process disp_filenames = { 'ex': {'eq': 'raman-eq.ex.gz', 'disp': 'raman-{:04}.ex.gz'}, 'force': {'eq': 'force-set-eq.npy', 'disp': 'force-set-{:04}.npy'}, } # Relax unrelaxed_atoms = get_unrelaxed_structure() unrelaxed_atoms.pbc = pbc unrelaxed_atoms.calc = make_calc_relax() relax_atoms(outpath='relaxed.vasp', atoms=unrelaxed_atoms) # Phonopy displacements phonon = get_minimum_displacements(cachepath='phonopy_disp.yaml', unitcell=phonopy.interface.calculator.read_crystal_structure('relaxed.vasp', interface_mode='vasp')[0], supercell_matrix=supercell_matrix, displacement_distance=displacement_distance, ) # Computing stuff at displacements eq_atoms = Cluster(phonopy_atoms_to_ase(phonon.supercell)) eq_atoms.pbc = pbc if raman_grid_sep != relax_grid_sep: eq_atoms.minimal_box(vacuum_sep, h=raman_grid_sep) eq_atoms.calc = make_calc_raman() force_sets = make_force_sets_and_excitations(cachepath='force-sets.npy', disp_filenames=disp_filenames, phonon=phonon, atoms=eq_atoms, ex_kw=ex_kw, ) phonon.set_forces(force_sets) # Applying symmetry cart_pol_derivs = expand_raman_by_symmetry(cachepath='raman-cart.npy', phonon=phonon, disp_filenames=disp_filenames, get_polarizability=get_polarizability, ex_kw=ex_kw, subtract_equilibrium_polarizability=subtract_equilibrium_polarizability, ) # Phonopy part 2 gamma_eigendata = get_eigensolutions_at_q(cachepath='eigensolutions-gamma.npz', phonon=phonon, q=[0, 0, 0], ) # Raman of modes get_mode_raman(outpath='mode-raman-gamma.npy', eigendata=gamma_eigendata, cart_pol_derivs=cart_pol_derivs, )
def get_unrelaxed_structure(): atoms = Cluster(ase.build.mx2('MoS2')) atoms.center(vacuum=vacuum_sep, axis=2) return atoms
import numpy as np import ase.io from ase.calculators.vdwcorrection import vdWTkatchenko09prl from ase.parallel import barrier from ase.build import molecule from gpaw import GPAW from gpaw.analyse.hirshfeld import HirshfeldPartitioning from gpaw.analyse.vdwradii import vdWradii from gpaw.cluster import Cluster from gpaw.test import equal h = 0.4 s = Cluster(molecule('LiH')) s.minimal_box(3., h=h) def print_charge_and_check(hp, q=0, label='unpolarized'): q_a = np.array(hp.get_charges()) print('Charges ({0})='.format(label), q_a, ', sum=', q_a.sum()) equal(q_a.sum(), q, 0.03) return q_a # spin unpolarized if 1: out_traj = 'LiH.traj' out_txt = 'LiH.txt'
from ase.data.s22 import data, s22 from ase.calculators.vdwcorrection import vdWTkatchenko09prl from gpaw import * from gpaw.cluster import Cluster from gpaw.analyse.hirshfeld import HirshfeldDensity, HirshfeldPartitioning from gpaw.analyse.vdwradii import vdWradii h = 0.18 box = 4. xc = 'TS09' f = paropen('energies_' + xc +'.dat', 'w') print >> f, '# h=', h print >> f, '# box=', box print >> f, '# molecule E[1] E[2] E[1+2] E[1]+E[2]-E[1+2]' for molecule in data: print >> f, molecule, ss = Cluster(Atoms(data[molecule]['symbols'], data[molecule]['positions'])) # split the structures s1 = ss.find_connected(0) s2 = ss.find_connected(-1) assert(len(ss) == len(s1) + len(s2)) if xc == 'TS09' or xc == 'TPSS' or xc == 'M06L': c = GPAW(xc='PBE', h=h, nbands=-6, occupations=FermiDirac(width=0.1)) else: c = GPAW(xc=xc, h=h, nbands=-6, occupations=FermiDirac(width=0.1)) E = [] for s in [s1, s2, ss]: s.set_calculator(c) s.minimal_box(box, h=h) if xc == 'TS09': s.get_potential_energy() cc = vdWTkatchenko09prl(HirshfeldPartitioning(c),
from ase.parallel import parprint from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.analyse.hirshfeld import HirshfeldDensity, HirshfeldPartitioning from gpaw.analyse.wignerseitz import WignerSeitz from gpaw.test import equal h = 0.3 gpwname = 'H2O' + str(h) + '.gpw' try: calc = GPAW(gpwname + 'notfound', txt=None) # calc = GPAW(gpwname, txt=None) mol = calc.get_atoms() except: mol = Cluster(molecule('H2O')) mol.minimal_box(3, h=h) calc = GPAW(nbands=6, h=h, txt=None) calc.calculate(mol) calc.write(gpwname) # Hirshfeld ---------------------------------------- if 1: hd = HirshfeldDensity(calc) # check for the number of electrons expected = [ [None, 10], [[0, 1, 2], 10],
b = [2, 3, 4] CO.minimal_box(b, h=h) cc = CO.get_cell() for c in range(3): # print "cc[c,c], cc[c,c] / h % 4 =", cc[c, c], cc[c, c] / h % 4 for a in CO: print(a.symbol, b[c], a.position[c], cc[c, c] - a.position[c]) assert(a.position[c] > b[c]) equal(cc[c, c] / h % 4, 0.0, 1e-10) # ............................................. # connected atoms assert(len(CO.find_connected(0, 1.1 * R)) == 2) assert(len(CO.find_connected(0, 0.9 * R)) == 1) H2O = Cluster(molecule('H2O')) assert (len(H2O.find_connected(0)) == 3) assert (len(H2O.find_connected(0, scale=0.9)) == 1) # ............................................. # I/O fxyz='CO.xyz' fpdb='CO.pdb' cell = [2.,3.,R+2.] CO.set_cell(cell, scale_atoms=True) barrier() CO.write(fxyz) barrier() CO_b = Cluster(filename=fxyz) assert(len(CO) == len(CO_b))
from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.pes.state import BoundState, H1s from gpaw.pes.ds_beta import CrossSectionBeta xc = 'PBE' ngauss = 2 h = .3 box = 3. gpwname = 'H1s.gpw' if 1: c = GPAW(xc='PBE', nbands=-1, h=h) s = Cluster([Atom('H')]) s.minimal_box(box, h=h) c.calculate(s) c.write(gpwname, 'all') else: c = GPAW(gpwname) s = c.get_atoms() c.converge_wave_functions() cm = s.get_center_of_mass() Ekin = 1. ekin = Ekin / Ha for form, title in [('L', 'length form'), ('V', 'velocity form')]: parprint('--', title) ds = [] for analytic in [True, False]:
from ase import Atom from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.analyse.eed import ExteriorElectronDensity fwfname = 'H2_kpt441_wf.gpw' txt = None #txt = '-' # write first if needed try: c = GPAW(fwfname, txt=txt) s = c.get_atoms() except: s = Cluster([Atom('H'), Atom('H', [0, 0, 1])], pbc=[1, 1, 0]) s.minimal_box(3.) c = GPAW(xc='PBE', h=.3, kpts=(4, 4, 1), convergence={ 'density': 1e-3, 'eigenstates': 1e-3 }) c.calculate(s) c.write(fwfname, 'all') eed = ExteriorElectronDensity(c.wfs.gd, s) eed.write_mies_weights(c.wfs)
from gpaw import GPAW, setup_paths from gpaw.cluster import Cluster from gpaw.eigensolvers import RMMDIIS from gpaw.xc.hybrid import HybridXC from gpaw.occupations import FermiDirac from gpaw.test import equal, gen if setup_paths[0] != '.': setup_paths.insert(0, '.') for atom in ['Be']: gen(atom, xcname='PBE', scalarrel=True, exx=True, yukawa_gamma=0.83, gpernode=149) h = 0.35 be = Cluster(Atoms('Be', positions=[[0, 0, 0]])) be.minimal_box(3.0, h=h) c = {'energy': 0.05, 'eigenstates': 0.05, 'density': 0.05} IP = 8.79 xc = HybridXC('LCY-PBE', omega=0.83) fname = 'Be_rsf.gpw' calc = GPAW(txt='Be.txt', xc=xc, convergence=c, eigensolver=RMMDIIS(), h=h, occupations=FermiDirac(width=0.0), spinpol=False) be.set_calculator(calc) # energy = na2.get_potential_energy() # calc.set(xc=xc)
import os import sys from gpaw.test import equal from ase import Atom from gpaw import GPAW, MixerDif from gpaw.cluster import Cluster h = .25 q = 0 box = 3. spin=True # B should not have spin contamination s = Cluster([Atom('B')]) s.minimal_box(box, h=h) s.set_initial_magnetic_moments([-1]) c = GPAW(xc='LDA', nbands=-3, charge=q, spinpol=spin, h=h, convergence={'eigenstates':1e-3, 'density':1e-2, 'energy':0.1}, ) c.calculate(s) equal(c.density.get_spin_contamination(s, 1), 0., 0.01) # setup H2 at large distance with differnt spins for the atoms s = Cluster([Atom('H'), Atom('H',[0,0,3.0])]) s.minimal_box(box, h=h) s.set_initial_magnetic_moments([-1,1])
from ase import Atom from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.test import equal fname='H2_PBE.gpw' fwfname='H2_wf_PBE.gpw' txt = None # write first if needed try: c = GPAW(fname, txt=txt) c = GPAW(fwfname, txt=txt) except: s = Cluster([Atom('H'), Atom('H', [0,0,1])]) s.minimal_box(3.) c = GPAW(xc='PBE', h=.3, convergence={'density':1e-3, 'eigenstates':1e-3}) c.calculate(s) c.write(fname) c.write(fwfname, 'all') # full information c = GPAW(fwfname, txt=txt) E_PBE = c.get_potential_energy() try: # number of iterations needed in restart niter_PBE = c.get_number_of_iterations() except: pass dE = c.get_xc_difference('TPSS') E_1 = E_PBE + dE print "E PBE, TPSS=", E_PBE, E_1
from gpaw.analyse.overlap import Overlap from gpaw.lrtddft import LrTDDFT """Evaluate the overlap between two independent calculations Differences are forced by different eigensolvers and differing number of Kohn-Sham states. """ h = 0.4 box = 2 nbands = 4 txt = '-' txt = None np.set_printoptions(precision=3, suppress=True) H2 = Cluster(molecule('H2')) H2.minimal_box(box, h) c1 = GPAW(h=h, txt=txt, eigensolver='dav', nbands=nbands, convergence={'eigenstates': nbands}) c1.calculate(H2) lr1 = LrTDDFT(c1) parprint('sanity --------') ov = Overlap(c1).pseudo(c1) parprint('pseudo(normalized):\n', ov) ov = Overlap(c1).pseudo(c1, False) parprint('pseudo(not normalized):\n', ov)
from ase.structure import molecule from ase.parallel import parprint from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.occupations import FixedOccupations, ZeroKelvin from gpaw.test import equal h = 0.4 box = 2 nbands = 2 txt = '-' txt = None H2 = Cluster(molecule('H2')) H2.minimal_box(box, h) convergence = {'energy':0.01, 'eigenstates':1.e-3, 'density':1.e-2} if 1: # test ZeroKelvin vs FixedOccupations c = GPAW(h=h, nbands=nbands, occupations=ZeroKelvin(True), convergence=convergence, txt=txt) H2.set_calculator(c) E_zk = H2.get_potential_energy() c = GPAW(h=h, nbands=nbands, occupations=FixedOccupations([[2, 0]]), convergence=convergence, txt=txt) H2.set_calculator(c)
import os import sys from ase import Atoms, Atom, QuasiNewton, PickleTrajectory from gpaw import * from gpaw.cluster import Cluster from gpaw.utilities.viewmol import ViewmolTrajectory, write_viewmol s = Cluster([Atom('H'), Atom('H', (0, 0, 3))]) s.minimal_box(2) c = GPAW(h=0.3, nbands=2) s.set_calculator(c) vfname = 'traj.vmol' pfname = 'traj.pickle' vmt = ViewmolTrajectory(s, vfname) traj = PickleTrajectory(pfname, 'w', s) #c.attach(vmt.add, 100000) #sys.exit() # Find the theoretical bond length: dyn = QuasiNewton(s) dyn.attach(traj.write) dyn.attach(vmt.add) dyn.run(fmax=0.05) traj = PickleTrajectory(pfname, 'r') vfname2 = 'pickle.vmol' write_viewmol(traj, vfname2)
h = 0.3 vac = 3.0 u0 = .180 epsinf = 80. T = 298.15 vdw_radii = vdw_radii.copy() vdw_radii[1] = 1.09 atomic_radii = lambda atoms: [vdw_radii[n] for n in atoms.numbers] convergence = { 'energy': 0.05 / 8., 'density': 10., 'eigenstates': 10., } atoms = Cluster(molecule('H2O')) atoms.minimal_box(vac, h) atoms.pbc = True with warnings.catch_warnings(): # ignore production code warning for ADM12PoissonSolver warnings.simplefilter("ignore") psolver = ADM12PoissonSolver(eps=1e-7) atoms.calc = SolvationGPAW( xc='LDA', h=h, convergence=convergence, cavity=EffectivePotentialCavity( effective_potential=Power12Potential(atomic_radii=atomic_radii, u0=u0), temperature=T ), dielectric=LinearDielectric(epsinf=epsinf),
from gpaw.cluster import Cluster from gpaw.analyse.hirshfeld import HirshfeldPartitioning from gpaw.analyse.vdwradii import vdWradii h = 0.25 box = 3.0 molecule = 'Adenine-thymine_complex_stack' Energy = { 'PBE': [], 'vdW-DF': [], 'TS09': []} for molecule in ['Adenine-thymine_complex_stack']: ss = Cluster(Atoms(data[molecule]['symbols'], data[molecule]['positions'])) # split the structures s1 = ss.find_connected(0) s2 = ss.find_connected(-1) assert len(ss) == len(s1) + len(s2) c = GPAW(xc='PBE', h=h, nbands=-6, occupations=FermiDirac(width=0.1), txt=None) cdf = GPAW(xc='vdW-DF', h=h, nbands=-6, occupations=FermiDirac(width=0.1), txt=None) for s in [s1, s2, ss]: s.set_calculator(c) s.minimal_box(box, h=h) Energy['PBE'].append(s.get_potential_energy())
"""Test Hirshfeld for spin/no spin consitency""" from ase import Atom from gpaw import GPAW from ase.parallel import parprint from gpaw.analyse.hirshfeld import HirshfeldPartitioning from gpaw import FermiDirac from gpaw.cluster import Cluster from gpaw.test import equal h = 0.25 box = 3 atoms = Cluster() atoms.append(Atom('H')) atoms.minimal_box(box) volumes = [] for spinpol in [False, True]: calc = GPAW(h=h, occupations=FermiDirac(0.1, fixmagmom=True), experimental={'niter_fixdensity': 2}, spinpol=spinpol) calc.calculate(atoms) volumes.append(HirshfeldPartitioning(calc).get_effective_volume_ratios()) parprint(volumes) equal(volumes[0][0], volumes[1][0], 4e-9)
from ase.io.plt import write_plt, read_plt from gpaw.test import equal from gpaw import GPAW from gpaw.cluster import Cluster txt='-' txt='/dev/null' load = False #load = True R=0.7 # approx. experimental bond length a = 4. c = 4. H2 = Cluster([Atom('H', (a/2,a/2,(c-R)/2)), Atom('H', (a/2,a/2,(c+R)/2))], cell=(a,a,c)) H2.rotate([1.,1.,1.]) ##H2.write('H2.xyz') fname = 'H2.gpw' if (not load) or (not os.path.exists(fname)): calc = GPAW(xc='PBE', nbands=2, spinpol=False, txt=txt) H2.set_calculator(calc) H2.get_potential_energy() if load: calc.write(fname, 'all') else: calc = GPAW(fname, txt=txt) calc.initialize_wave_functions()
from __future__ import print_function import sys import numpy as np from ase.build import molecule from ase.parallel import parprint from gpaw import GPAW, PW from gpaw.analyse.multipole import Multipole from gpaw.cluster import Cluster from gpaw.test import equal h = 0.3 s = Cluster(molecule('H2O')) s.minimal_box(3., h) gpwname = 'H2O_h' + str(h) + '.gpw' try: # XXX check why this fails in parallel calc = GPAW(gpwname + 'failsinparallel', txt=None) atoms = calc.get_atoms() calc.density.set_positions(atoms.get_scaled_positions() % 1.0) calc.density.interpolate_pseudo_density() calc.density.calculate_pseudo_charge() except IOError: calc = GPAW(h=h, charge=0, txt=None) calc.calculate(s) calc.write(gpwname) dipole_c = calc.get_dipole_moment()
from __future__ import print_function from ase.build import molecule from ase.parallel import parprint from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.occupations import FixedOccupations, ZeroKelvin from gpaw.test import equal h = 0.4 box = 2 nbands = 2 txt = '-' txt = None H2 = Cluster(molecule('H2')) H2.minimal_box(box, h) convergence = {'energy': 0.01, 'eigenstates': 1.e-3, 'density': 1.e-2} if 1: # test ZeroKelvin vs FixedOccupations c = GPAW(h=h, nbands=nbands, occupations=ZeroKelvin(True), convergence=convergence, txt=txt) H2.set_calculator(c) E_zk = H2.get_potential_energy() c = GPAW(h=h, nbands=nbands, occupations=FixedOccupations([[2, 0]]),
SKIP_VAC_CALC = True h = 0.24 vac = 4.0 epsinf = 78.36 rho0 = 0.00078 / Bohr**3 beta = 1.3 st = 72. * 1e-3 * Pascal * m convergence = { 'energy': 0.05 / 8., 'density': 10., 'eigenstates': 10., } atoms = Cluster(Atoms('Cl')) atoms.minimal_box(vac, h) if not SKIP_VAC_CALC: atoms.calc = GPAW(xc='PBE', h=h, charge=-1, convergence=convergence) Evac = atoms.get_potential_energy() print(Evac) else: # h=0.24, vac=4.0, setups: 0.9.11271, convergence: only energy 0.05 / 8 Evac = -3.83245253419 atoms.calc = SolvationGPAW( xc='PBE', h=h, charge=-1, convergence=convergence,
def get_unrelaxed_structure(): atoms = Cluster(ase.build.molecule('CH4')) atoms.minimal_box(vacuum_sep, h=relax_grid_sep) return atoms
from ase.vibrations.resonant_raman import ResonantRaman from gpaw.cluster import Cluster from gpaw import GPAW, FermiDirac from gpaw.lrtddft import LrTDDFT h = 0.25 atoms = Cluster('relaxed.traj') atoms.minimal_box(3.5, h=h) # relax the molecule calc = GPAW(h=h, occupations=FermiDirac(width=0.1), eigensolver='cg', symmetry={'point_group': False}, nbands=10, convergence={ 'eigenstates': 1.e-5, 'bands': 4 }) atoms.set_calculator(calc) # use only the 4 converged states for linear response calculation rr = ResonantRaman(atoms, LrTDDFT, exkwargs={'jend': 3}) rr.run()
from ase.vibrations.resonant_raman import ResonantRaman from gpaw.cluster import Cluster from gpaw import GPAW, FermiDirac from gpaw.lrtddft import LrTDDFT h = 0.25 atoms = Cluster('relaxed.traj') atoms.minimal_box(3.5, h=h) # relax the molecule calc = GPAW(h=h, occupations=FermiDirac(width=0.1), eigensolver='cg', symmetry={'point_group': False}, nbands=10, convergence={ 'eigenstates': 1.e-5, 'bands': 4 }) atoms.calc = calc # use only the 4 converged states for linear response calculation rr = ResonantRaman(atoms, LrTDDFT, exkwargs={'jend': 3}) rr.run()
h = 0.24 vac = 4.0 epsinf = 78.36 rhomin = 0.0001 / Bohr**3 rhomax = 0.0050 / Bohr**3 st = 50. * 1e-3 * Pascal * m p = -0.35 * 1e9 * Pascal convergence = { 'energy': 0.05 / 8., 'density': 10., 'eigenstates': 10., } atoms = Cluster(molecule('H2O')) atoms.minimal_box(vac, h) if not SKIP_VAC_CALC: atoms.calc = GPAW(xc='PBE', h=h, convergence=convergence) Evac = atoms.get_potential_energy() print(Evac) else: # h=0.24, vac=4.0, setups: 0.9.11271, convergence: only energy 0.05 / 8 Evac = -14.857414548 with warnings.catch_warnings(): # ignore production code warning for ADM12PoissonSolver warnings.simplefilter("ignore") psolver = ADM12PoissonSolver()
from __future__ import print_function from ase import Atom from ase.units import Hartree from gpaw import GPAW, FermiDirac, Davidson, PoissonSolver from gpaw.cluster import Cluster from gpaw.test import equal h = .35 box = 3. energy_tolerance = 0.0004 s = Cluster([Atom('Zn')]) s.minimal_box(box, h=h) E = {} E_U = {} for spin in [0, 1]: c = GPAW(h=h, spinpol=spin, xc='oldLDA', mode='lcao', basis='sz(dzp)', poissonsolver=PoissonSolver(relax='GS', eps=1e-7), parallel=dict(kpt=1), charge=1, occupations=FermiDirac(width=0.1, fixmagmom=spin)) s.set_calculator(c) E[spin] = s.get_potential_energy() c.set(setups=':d,3.0,1') E_U[spin] = s.get_potential_energy()
import gpaw.mpi as mpi from gpaw import GPAW from gpaw.cluster import Cluster txt = '-' txt = '/dev/null' load = False # load = True R = 0.7 # approx. experimental bond length a = 4. c = 4. H2 = Cluster([Atom('H', (a / 2, a / 2, (c - R) / 2)), Atom('H', (a / 2, a / 2, (c + R) / 2))], cell=(a, a, c)) H2.rotate(57, [1, 1, 1]) fname = 'H2.gpw' if (not load) or (not os.path.exists(fname)): calc = GPAW(xc='PBE', nbands=2, spinpol=False, txt=txt) H2.set_calculator(calc) H2.get_potential_energy() if load: calc.write(fname, 'all') else: calc = GPAW(fname, txt=txt) calc.initialize_wave_functions() fname = 'aed.plt'
from gpaw import GPAW, FermiDirac from gpaw.cluster import Cluster from gpaw.test import equal h =.3 box = 4. energy_tolerance = 0.0004 l=2 # d-orbitals U_ev=3 # U in eV U_au=U_ev / Hartree # U in atomic units scale=1 # Do not scale (does not seem to matter much) store=0 # Do not store (not in use yet) s = Cluster([Atom('Zn')]) s.minimal_box(box, h=h) E = {} E_U = {} for spin in [0, 1]: c = GPAW(h=h, spinpol=bool(spin), charge=1, occupations=FermiDirac(width=0.1) ) s.set_calculator(c) E[spin] = s.get_potential_energy() for setup in c.hamiltonian.setups: setup.set_hubbard_u(U_au, l, scale, store) # Apply U c.scf.reset() E_U[spin] = s.get_potential_energy()
results.append(vr) # Wigner-Seitz ---------------------------------------- if 1: ws = WignerSeitz(calc.density.finegd, mol, calc) vr = ws.get_effective_volume_ratios() parprint('Wigner-Seitz:', vr) if len(lastres): equal(vr, lastres.pop(0), 1.e-10) results.append(vr) return results mol = Cluster(molecule('H2O')) mol.minimal_box(2.5, h=h) # calculate if 1: parprint('### fresh:') calc = GPAW(nbands=6, h = h, txt=None) if 1: calc.calculate(mol) calc.write(gpwname) lastres = run() # load previous calculation if 1: