Example #1
0
    def __call__(self, name, atoms):
        kpts = self.calculate_kpts(atoms)

        kwargs = self.kwargs.copy()  # modify a copy
        
        if (not atoms.pbc.any() and len(atoms) == 1 and
            atoms.get_initial_magnetic_moments().any() and
            'hund' not in kwargs):
            kwargs['hund'] = True

        if atoms.pbc.any() and 'gpts' not in kwargs:
            # Use fixed number of gpts:
            h = kwargs.get('h')
            if h is not None:
                h /= Bohr

            cell_cv = atoms.cell / Bohr

            mode = kwargs.get('mode')
            if mode == 'pw':
                mode = PW()

            gpts = get_number_of_grid_points(cell_cv, h, mode,
                                             kwargs.get('realspace'))
            kwargs['h'] = None
            kwargs['gpts'] = gpts
            
            if isinstance(mode, PW):
                kwargs['mode'] = PW(mode.ecut * Hartree,
                                    mode.fftwflags,
                                    atoms.cell)

        if self.show_text_output:
            txt = '-'
        else:
            txt = name + '.txt'


        from gpaw import GPAW
        return GPAW(txt=txt, kpts=kpts, **kwargs)
    def read(self, reader):
        """Read state from file."""

        r = reader

        version = r['version']
        
        assert version >= 0.3
    
        self.xc = r['XCFunctional']
        self.nbands = r.dimension('nbands')
        self.spinpol = (r.dimension('nspins') == 2)

        bzk_kc = r.get('BZKPoints', broadcast=True)
        if r.has_array('NBZKPoints'):
            self.kpts = r.get('NBZKPoints', broadcast=True)
            if r.has_array('MonkhorstPackOffset'):
                offset_c = r.get('MonkhorstPackOffset', broadcast=True)
                if offset_c.any():
                    self.kpts = monkhorst_pack(self.kpts) + offset_c
        else:
            self.kpts = bzk_kc

        if version < 4:
            self.symmetry = usesymm2symmetry(r['UseSymmetry'])
        else:
            self.symmetry = {'point_group': r['SymmetryOnSwitch'],
                             'symmorphic': r['SymmetrySymmorphicSwitch'],
                             'time_reversal': r['SymmetryTimeReversalSwitch'],
                             'tolerance': r['SymmetryToleranceCriterion']}

        try:
            self.basis = r['BasisSet']
        except KeyError:
            pass

        if version >= 2:
            try:
                h = r['GridSpacing']
            except KeyError:  # CMR can't handle None!
                h = None
            if h is not None:
                self.h = Bohr * h
            if r.has_array('GridPoints'):
                self.gpts = r.get('GridPoints')
        else:
            if version >= 0.9:
                h = r['GridSpacing']
            else:
                h = None

            gpts = ((r.dimension('ngptsx') + 1) // 2 * 2,
                    (r.dimension('ngptsy') + 1) // 2 * 2,
                    (r.dimension('ngptsz') + 1) // 2 * 2)

            if h is None:
                self.gpts = gpts
            else:
                self.h = Bohr * h

        self.lmax = r['MaximumAngularMomentum']
        self.setups = r['SetupTypes']
        self.fixdensity = r['FixDensity']
        if version <= 0.4:
            # Old version: XXX
            print(('# Warning: Reading old version 0.3/0.4 restart files ' +
                  'will be disabled some day in the future!'))
            self.convergence['eigenstates'] = r['Tolerance']
        else:
            nbtc = r['NumberOfBandsToConverge']
            if not isinstance(nbtc, (int, str)):
                # The string 'all' was eval'ed to the all() function!
                nbtc = 'all'
            if version < 5:
                force_crit = None
            else:
                force_crit = r['ForcesConvergenceCriterion']
                if force_crit is not None:
                    force_crit *= (Hartree / Bohr)
            self.convergence = {'density': r['DensityConvergenceCriterion'],
                                'energy':
                                r['EnergyConvergenceCriterion'] * Hartree,
                                'eigenstates':
                                r['EigenstatesConvergenceCriterion'],
                                'bands': nbtc,
                                'forces': force_crit}

            if version < 1:
                # Volume per grid-point:
                dv = (abs(np.linalg.det(r.get('UnitCell'))) /
                      (gpts[0] * gpts[1] * gpts[2]))
                self.convergence['eigenstates'] *= Hartree**2 * dv

            if version <= 0.6:
                mixer = 'Mixer'
                weight = r['MixMetric']
            elif version <= 0.7:
                mixer = r['MixClass']
                weight = r['MixWeight']
                metric = r['MixMetric']
                if metric is None:
                    weight = 1.0
            else:
                mixer = r['MixClass']
                weight = r['MixWeight']

            if mixer == 'Mixer':
                from gpaw.mixer import Mixer
            elif mixer == 'MixerSum':
                from gpaw.mixer import MixerSum as Mixer
            elif mixer == 'MixerSum2':
                from gpaw.mixer import MixerSum2 as Mixer
            elif mixer == 'MixerDif':
                from gpaw.mixer import MixerDif as Mixer
            elif mixer == 'DummyMixer':
                from gpaw.mixer import DummyMixer as Mixer
            else:
                Mixer = None

            if Mixer is None:
                self.mixer = None
            else:
                self.mixer = Mixer(r['MixBeta'], r['MixOld'], weight)
            
        if version == 0.3:
            # Old version: XXX
            print(('# Warning: Reading old version 0.3 restart files is ' +
                  'dangerous and will be disabled some day in the future!'))
            self.stencils = (2, 3)
            self.charge = 0.0
            fixmom = False
        else:
            self.stencils = (r['KohnShamStencil'],
                             r['InterpolationStencil'])
            if r['PoissonStencil'] == 999:
                self.poissonsolver = FFTPoissonSolver()
            else:
                self.poissonsolver = PoissonSolver(nn=r['PoissonStencil'])
            self.charge = r['Charge']
            fixmom = r['FixMagneticMoment']

        self.occupations = FermiDirac(r['FermiWidth'] * Hartree,
                                      fixmagmom=fixmom)

        try:
            self.mode = r['Mode']
        except KeyError:
            self.mode = 'fd'

        if self.mode == 'pw':
            self.mode = PW(ecut=r['PlaneWaveCutoff'] * Hartree)
            
        if len(bzk_kc) == 1 and not bzk_kc[0].any():
            # Gamma point only:
            if r['DataType'] == 'Complex':
                self.dtype = complex
Example #3
0
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', 'a')

H = Atoms('H', [(0, 0, 0)])
H.set_pbc(True)
H.center(vacuum=2.0)
calc = GPAW(mode=PW(300),
            hund=True,
            dtype=complex,
            txt='H.ralda_01_lda.output.txt',
            xc='PBE')

H.set_calculator(calc)
E_lda = H.get_potential_energy()
E_c_lda = -calc.get_xc_difference('GGA_X_PBE')

resultfile.write('PBE correlation: %s eV' % E_c_lda)
resultfile.write('\n')

calc.diagonalize_full_hamiltonian()
calc.write('H.ralda.pbe_wfcs.gpw', mode='all')
Example #4
0
import pickle

import numpy as np
from ase.build import bulk

from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW
from gpaw.response.g0w0 import G0W0


a = 3.567
atoms = bulk('C', 'diamond', a=a)

k = 8

calc = GPAW(mode=PW(600, force_complex_dtype=True),
            parallel={'domain': 1},
            kpts={'size': (k, k, k), 'gamma': True},
            dtype=complex,
            xc='LDA',
            occupations=FermiDirac(0.001),
            txt='C_converged_ppa.txt')

atoms.set_calculator(calc)
atoms.get_potential_energy()

calc.diagonalize_full_hamiltonian()
calc.write('C_converged_ppa.gpw', 'all')

for ecut in [300, 400]:
    gw = G0W0(calc='C_converged_ppa.gpw',
Example #5
0
from ase.build import bulk
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW

a = 3.567
atoms = bulk('C', 'diamond', a=a)

calc = GPAW(
    mode=PW(300),  # energy cutoff for plane wave basis (in eV)
    kpts={
        'size': (3, 3, 3),
        'gamma': True
    },
    xc='LDA',
    occupations=FermiDirac(0.001),
    parallel={'domain': 1},
    txt='C_groundstate.txt')

atoms.set_calculator(calc)
atoms.get_potential_energy()

calc.diagonalize_full_hamiltonian()  # determine all bands
calc.write('C_groundstate.gpw', 'all')  # write out wavefunctions
Example #6
0
# fails with On entry to ZGEMV parameter number 8 had an illegal value

from ase.build import molecule
from gpaw import GPAW
from gpaw.wavefunctions.pw import PW

m = molecule('H')
m.center(vacuum=2.0)
m.set_calculator(GPAW(mode=PW(), eigensolver='cg'))
m.get_potential_energy()
Example #7
0
from ase.build import bulk

from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW
from gpaw.response.g0w0 import G0W0
import pickle
import numpy as np


a = 3.567
atoms = bulk('C', 'diamond', a=a)

k = 8

calc = GPAW(mode=PW(600),
            kpts={'size': (k, k, k), 'gamma': True},
            dtype=complex,
            xc='LDA',
            occupations=FermiDirac(0.001),
            txt='C_converged_ppa.txt')

atoms.set_calculator(calc)
atoms.get_potential_energy()

calc.diagonalize_full_hamiltonian()
calc.write('C_converged_ppa.gpw', 'all')

for ecut in [300,400]:
    gw = G0W0(calc='C_converged_ppa.gpw',
              kpts=[0],
              bands=(3, 5),
Example #8
0
from ase.build import bulk
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW

bulk_si = bulk('Si', a=5.42935602)
calc = GPAW(
    mode=PW(400.0),
    xc='LDA',
    occupations=FermiDirac(width=0.01),
    kpts={
        'size': (4, 4, 4),
        'gamma': True
    },
    txt='si.gs.txt',
)

bulk_si.set_calculator(calc)
E_lda = bulk_si.get_potential_energy()
calc.diagonalize_full_hamiltonian()
calc.write('si.lda_wfcs.gpw', mode='all')
Example #9
0
def read(paw, reader, read_projections=True):
    r = reader
    timer = paw.timer
    timer.start('Read')

    wfs = paw.wfs
    density = paw.density
    hamiltonian = paw.hamiltonian
    natoms = len(paw.atoms)

    world = paw.wfs.world
    gd = wfs.gd
    kd = wfs.kd
    bd = wfs.bd

    master = (world.rank == 0)
    parallel = (world.size > 1)

    version = r['version']

    hdf5 = hasattr(r, 'hdf5')

    # Verify setup fingerprints and count projectors and atomic matrices:
    for setup in wfs.setups.setups.values():
        try:
            key = atomic_names[setup.Z] + 'Fingerprint'
            if setup.type != 'paw':
                key += '(%s)' % setup.type
            if setup.fingerprint != r[key]:
                str = 'Setup for %s (%s) not compatible with restart file.' \
                    % (setup.symbol, setup.filename)
                if paw.input_parameters['idiotproof']:
                    raise RuntimeError(str)
                else:
                    warnings.warn(str)
        except (AttributeError, KeyError):
            str = 'Fingerprint of setup for %s (%s) not in restart file.' \
                % (setup.symbol, setup.filename)
            if paw.input_parameters['idiotproof']:
                raise RuntimeError(str)
            else:
                warnings.warn(str)
    nproj = sum([setup.ni for setup in wfs.setups])
    nadm = sum([setup.ni * (setup.ni + 1) // 2 for setup in wfs.setups])

    # Verify dimensions for minimally required netCDF variables:
    ng = gd.get_size_of_global_array()
    shapes = {
        'ngptsx': ng[0],
        'ngptsy': ng[1],
        'ngptsz': ng[2],
        'nspins': wfs.nspins,
        'nproj': nproj,
        'nadm': nadm
    }
    for name, dim in shapes.items():
        if r.dimension(name) != dim:
            raise ValueError('shape mismatch: expected %s=%d' % (name, dim))

    timer.start('Density')
    density.read(r, parallel, wfs.kptband_comm)
    timer.stop('Density')

    timer.start('Hamiltonian')
    hamiltonian.read(r, parallel)
    timer.stop('Hamiltonian')

    from gpaw.utilities.partition import AtomPartition
    atom_partition = AtomPartition(gd.comm, np.zeros(natoms, dtype=int))
    # <sarcasm>let's set some variables directly on some objects!</sarcasm>
    wfs.atom_partition = atom_partition
    wfs.rank_a = np.zeros(natoms, int)
    density.atom_partition = atom_partition
    hamiltonian.atom_partition = atom_partition

    if version > 0.3:
        Etot = hamiltonian.Etot
        energy_error = r['EnergyError']
        if energy_error is not None:
            paw.scf.energies = [Etot, Etot + energy_error, Etot]
        wfs.eigensolver.error = r['EigenstateError']
        if version < 1:
            wfs.eigensolver.error *= gd.dv
    else:
        paw.scf.converged = r['Converged']

    if version > 0.6:
        if paw.occupations.fixmagmom:
            if 'FermiLevel' in r.get_parameters():
                paw.occupations.set_fermi_levels_mean(r['FermiLevel'])
            if 'FermiSplit' in r.get_parameters():
                paw.occupations.set_fermi_splitting(r['FermiSplit'])
        else:
            if 'FermiLevel' in r.get_parameters():
                paw.occupations.set_fermi_level(r['FermiLevel'])
    else:
        if (not paw.input_parameters.fixmom
                and 'FermiLevel' in r.get_parameters()):
            paw.occupations.set_fermi_level(r['FermiLevel'])

    # Try to read the current time and kick strength in time-propagation TDDFT:
    for attr, name in [('time', 'Time'), ('niter', 'TimeSteps'),
                       ('kick_strength', 'AbsorptionKick')]:
        if hasattr(paw, attr):
            try:
                if r.has_array(name):
                    value = r.get(name, read=master)
                else:
                    value = r[name]
                setattr(paw, attr, value)
            except KeyError:
                pass

    # Try to read FDTD-related data
    try:
        use_fdtd = r['FDTD']
    except:
        use_fdtd = False

    if use_fdtd:
        from gpaw.fdtd.poisson_fdtd import FDTDPoissonSolver
        # fdtd_poisson will overwrite the poisson at a later stage
        paw.hamiltonian.fdtd_poisson = FDTDPoissonSolver(restart_reader=r,
                                                         paw=paw)

    # Try to read the number of Delta SCF orbitals
    try:
        norbitals = r.dimension('norbitals')
        paw.occupations.norbitals = norbitals
    except (AttributeError, KeyError):
        norbitals = None

    nibzkpts = r.dimension('nibzkpts')
    nbands = r.dimension('nbands')
    nslice = bd.get_slice()

    if (nibzkpts != len(wfs.kd.ibzk_kc)
            or nbands != bd.comm.size * bd.mynbands):
        paw.scf.reset()
    else:
        # Verify that symmetries for for k-point reduction hasn't changed:
        tol = 1e-12

        if master:
            bzk_kc = r.get('BZKPoints', read=master)
            weight_k = r.get('IBZKPointWeights', read=master)
            assert np.abs(bzk_kc - kd.bzk_kc).max() < tol
            assert np.abs(weight_k - kd.weight_k).max() < tol

        for kpt in wfs.kpt_u:
            # Eigenvalues and occupation numbers:
            timer.start('Band energies')
            k = kpt.k
            s = kpt.s
            if hdf5:  # fully parallelized over spins, k-points
                do_read = (gd.comm.rank == 0)
                indices = [s, k]
                indices.append(nslice)
                kpt.eps_n = r.get('Eigenvalues',
                                  parallel=parallel,
                                  read=do_read,
                                  *indices)
                gd.comm.broadcast(kpt.eps_n, 0)
                kpt.f_n = r.get('OccupationNumbers',
                                parallel=parallel,
                                read=do_read,
                                *indices)
                gd.comm.broadcast(kpt.f_n, 0)
            else:
                eps_n = r.get('Eigenvalues', s, k, read=master)
                f_n = r.get('OccupationNumbers', s, k, read=master)
                kpt.eps_n = eps_n[nslice].copy()
                kpt.f_n = f_n[nslice].copy()
            timer.stop('Band energies')

            if norbitals is not None:  # XXX will probably fail for hdf5
                timer.start('dSCF expansions')
                kpt.ne_o = np.empty(norbitals, dtype=float)
                kpt.c_on = np.empty((norbitals, bd.mynbands), dtype=complex)
                for o in range(norbitals):
                    kpt.ne_o[o] = r.get('LinearExpansionOccupations',
                                        s,
                                        k,
                                        o,
                                        read=master)
                    c_n = r.get('LinearExpansionCoefficients',
                                s,
                                k,
                                o,
                                read=master)
                    kpt.c_on[o, :] = c_n[nslice]
                timer.stop('dSCF expansions')

        if (r.has_array('PseudoWaveFunctions')
                and paw.input_parameters.mode != 'lcao'):

            timer.start('Pseudo-wavefunctions')
            wfs.read(r, hdf5)
            timer.stop('Pseudo-wavefunctions')

        if (r.has_array('WaveFunctionCoefficients')
                and paw.input_parameters.mode == 'lcao'):
            wfs.read_coefficients(r)

        timer.start('Projections')
        if hdf5 and read_projections:
            # Domain masters read parallel over spin, kpoints and band groups
            cumproj_a = np.cumsum([0] + [setup.ni for setup in wfs.setups])
            all_P_ni = np.empty((bd.mynbands, cumproj_a[-1]), dtype=wfs.dtype)
            for kpt in wfs.kpt_u:
                kpt.P_ani = {}
                indices = [kpt.s, kpt.k]
                indices.append(bd.get_slice())
                do_read = (gd.comm.rank == 0)
                # timer.start('ProjectionsCritical(s=%d,k=%d)' % (kpt.s,kpt.k))
                r.get('Projections',
                      out=all_P_ni,
                      parallel=parallel,
                      read=do_read,
                      *indices)
                # timer.stop('ProjectionsCritical(s=%d,k=%d)' % (kpt.s,kpt.k))
                if gd.comm.rank == 0:
                    for a in range(natoms):
                        ni = wfs.setups[a].ni
                        P_ni = np.empty((bd.mynbands, ni), dtype=wfs.dtype)
                        P_ni[:] = all_P_ni[:, cumproj_a[a]:cumproj_a[a + 1]]
                        kpt.P_ani[a] = P_ni

            del all_P_ni  # delete a potentially large matrix
        elif read_projections and r.has_array('Projections'):
            wfs.read_projections(r)
        timer.stop('Projections')

    # Manage mode change:
    paw.scf.check_convergence(density, wfs.eigensolver, wfs, hamiltonian,
                              paw.forces)
    newmode = paw.input_parameters.mode
    try:
        oldmode = r['Mode']
        if oldmode == 'pw':
            from gpaw.wavefunctions.pw import PW
            oldmode = PW(ecut=r['PlaneWaveCutoff'] * Hartree)
    except (AttributeError, KeyError):
        oldmode = 'fd'  # This is an old gpw file from before lcao existed

    if newmode == 'lcao':
        spos_ac = paw.atoms.get_scaled_positions() % 1.0
        wfs.load_lazily(hamiltonian, spos_ac)

    if newmode != oldmode:
        paw.scf.reset()

    # Get the forces from the old calculation:
    if r.has_array('CartesianForces'):
        paw.forces.F_av = r.get('CartesianForces', broadcast=True)
    else:
        paw.forces.reset()

    hamiltonian.xc.read(r)

    timer.stop('Read')
Example #10
0
from ase import Atoms
from ase.data.molecules import molecule
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW
from gpaw.mpi import world

k = 2
if world.size == 1:
    a = molecule('H', pbc=1, magmoms=[0])
    a.center(vacuum=2)
    a.set_calculator(GPAW(mode=PW(250), kpts=(k, k, k)))
    a.get_potential_energy()
Example #11
0
from ase import Atoms
from ase.build import bulk
from gpaw import GPAW
from gpaw.wavefunctions.pw import PW
from gpaw.occupations import FermiDirac

cell = bulk('Si', 'fcc', a=5.421).get_cell()
a = Atoms('Si2',
          cell=cell,
          pbc=True,
          scaled_positions=((0, 0, 0), (0.25, 0.25, 0.25)))

calc = GPAW(mode=PW(400),
            xc='PBE',
            occupations=FermiDirac(width=0.001),
            parallel={
                'domain': 1,
                'band': 1
            },
            kpts={
                'size': (8, 8, 8),
                'gamma': True
            },
            txt='gs_Si.txt')

a.set_calculator(calc)
a.get_potential_energy()

calc.diagonalize_full_hamiltonian(nbands=100)
calc.write('gs_Si.gpw', mode='all')
Example #12
0
from __future__ import print_function
import numpy as np
from ase import Atoms
from gpaw import GPAW
from gpaw.wavefunctions.pw import PW
from gpaw.test import equal

bulk = Atoms('Li', pbc=True)
k = 4
calc = GPAW(mode=PW(200), kpts=(k, k, k), eigensolver='rmm-diis')
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())

a = np.roots(np.polyder(np.polyfit(A, e, 2), 1))[0]
print('a =', a)
equal(a, 2.65247379609, 0.001)
Example #13
0
def wrap_old_gpw_reader(filename):
    warnings.warn('You are reading an old-style gpw-file.  Please check '
                  'the results carefully!')

    r = Reader(filename)

    data = {
        'version': -1,
        'gpaw_version': '1.0',
        'ha': Ha,
        'bohr': Bohr,
        'scf.': {
            'converged': True
        },
        'atoms.': {},
        'wave_functions.': {}
    }

    class DictBackend:
        def write(self, **kwargs):
            data['atoms.'].update(kwargs)

    write_atoms(DictBackend(), read_atoms(r))

    e_total_extrapolated = r.get('PotentialEnergy').item() * Ha
    magmom_a = r.get('MagneticMoments')
    data['results.'] = {
        'energy': e_total_extrapolated,
        'magmoms': magmom_a,
        'magmom': magmom_a.sum()
    }

    if r.has_array('CartesianForces'):
        data['results.']['forces'] = r.get('CartesianForces') * Ha / Bohr

    p = data['parameters.'] = {}

    p['xc'] = r['XCFunctional']
    p['nbands'] = r.dimension('nbands')
    p['spinpol'] = (r.dimension('nspins') == 2)

    bzk_kc = r.get('BZKPoints', broadcast=True)
    if r.has_array('NBZKPoints'):
        p['kpts'] = r.get('NBZKPoints', broadcast=True)
        if r.has_array('MonkhorstPackOffset'):
            offset_c = r.get('MonkhorstPackOffset', broadcast=True)
            if offset_c.any():
                p['kpts'] = monkhorst_pack(p['kpts']) + offset_c
    else:
        p['kpts'] = bzk_kc

    if r['version'] < 4:
        usesymm = r['UseSymmetry']
        if usesymm is None:
            p['symmetry'] = {'time_reversal': False, 'point_group': False}
        elif usesymm:
            p['symmetry'] = {'time_reversal': True, 'point_group': True}
        else:
            p['symmetry'] = {'time_reversal': True, 'point_group': False}
    else:
        p['symmetry'] = {
            'point_group': r['SymmetryOnSwitch'],
            'symmorphic': r['SymmetrySymmorphicSwitch'],
            'time_reversal': r['SymmetryTimeReversalSwitch'],
            'tolerance': r['SymmetryToleranceCriterion']
        }

    p['basis'] = r['BasisSet']

    try:
        h = r['GridSpacing']
    except KeyError:  # CMR can't handle None!
        h = None
    if h is not None:
        p['h'] = Bohr * h
    if r.has_array('GridPoints'):
        p['gpts'] = r.get('GridPoints')

    p['lmax'] = r['MaximumAngularMomentum']
    p['setups'] = r['SetupTypes']
    p['fixdensity'] = r['FixDensity']
    nbtc = r['NumberOfBandsToConverge']
    if not isinstance(nbtc, (int, str)):
        # The string 'all' was eval'ed to the all() function!
        nbtc = 'all'
    p['convergence'] = {
        'density': r['DensityConvergenceCriterion'],
        'energy': r['EnergyConvergenceCriterion'] * Ha,
        'eigenstates': r['EigenstatesConvergenceCriterion'],
        'bands': nbtc
    }
    mixer = r['MixClass']
    weight = r['MixWeight']

    for key in ['basis', 'setups']:
        dct = p[key]
        if isinstance(dct, dict) and None in dct:
            dct['default'] = dct.pop(None)

    if mixer == 'Mixer':
        from gpaw.mixer import Mixer
    elif mixer == 'MixerSum':
        from gpaw.mixer import MixerSum as Mixer
    elif mixer == 'MixerSum2':
        from gpaw.mixer import MixerSum2 as Mixer
    elif mixer == 'MixerDif':
        from gpaw.mixer import MixerDif as Mixer
    elif mixer == 'DummyMixer':
        from gpaw.mixer import DummyMixer as Mixer
    else:
        Mixer = None

    if Mixer is None:
        p['mixer'] = None
    else:
        p['mixer'] = Mixer(r['MixBeta'], r['MixOld'], weight)

    p['stencils'] = (r['KohnShamStencil'], r['InterpolationStencil'])

    vt_sG = r.get('PseudoPotential') * Ha
    ps = r['PoissonStencil']
    if isinstance(ps, int) or ps == 'M':
        poisson = {'name': 'fd'}
        poisson['nn'] = ps
        if data['atoms.']['pbc'] == [1, 1, 0]:
            v1, v2 = vt_sG[0, :, :, [0, -1]].mean(axis=(1, 2))
            if abs(v1 - v2) > 0.01:
                warnings.warn('I am guessing that this calculation was done '
                              'with a dipole-layer correction?')
                poisson['dipolelayer'] = 'xy'
        p['poissonsolver'] = poisson

    p['charge'] = r['Charge']
    fixmom = r['FixMagneticMoment']

    p['occupations'] = FermiDirac(r['FermiWidth'] * Ha, fixmagmom=fixmom)

    p['mode'] = r['Mode']

    if p['mode'] == 'pw':
        p['mode'] = PW(ecut=r['PlaneWaveCutoff'] * Ha)

    if len(bzk_kc) == 1 and not bzk_kc[0].any():
        # Gamma point only:
        if r['DataType'] == 'Complex':
            p['dtype'] = complex

    data['occupations.'] = {
        'fermilevel': r['FermiLevel'] * Ha,
        'split': r.parameters.get('FermiSplit', 0) * Ha,
        'h**o': np.nan,
        'lumo': np.nan
    }

    data['density.'] = {
        'density': r.get('PseudoElectronDensity') * Bohr**-3,
        'atomic_density_matrices': r.get('AtomicDensityMatrices')
    }

    data['hamiltonian.'] = {
        'e_coulomb': r['Epot'] * Ha,
        'e_entropy': -r['S'] * Ha,
        'e_external': r['Eext'] * Ha,
        'e_kinetic': r['Ekin'] * Ha,
        'e_total_extrapolated': e_total_extrapolated,
        'e_xc': r['Exc'] * Ha,
        'e_zero': r['Ebar'] * Ha,
        'potential': vt_sG,
        'atomic_hamiltonian_matrices': r.get('NonLocalPartOfHamiltonian') * Ha
    }
    data['hamiltonian.']['e_total_free'] = (sum(
        data['hamiltonian.'][e] for e in [
            'e_coulomb', 'e_entropy', 'e_external', 'e_kinetic', 'e_xc',
            'e_zero'
        ]))

    if r.has_array('GLLBPseudoResponsePotential'):
        data['hamiltonian.']['xc.'] = {
            'gllb_pseudo_response_potential':
            r.get('GLLBPseudoResponsePotential') * Ha,
            'gllb_dxc_pseudo_response_potential':
            r.get('GLLBDxcPseudoResponsePotential') * Ha / Bohr,
            'gllb_atomic_density_matrices':
            r.get('GLLBAtomicDensityMatrices'),
            'gllb_atomic_response_matrices':
            r.get('GLLBAtomicResponseMatrices'),
            'gllb_dxc_atomic_density_matrices':
            r.get('GLLBDxcAtomicDensityMatrices'),
            'gllb_dxc_atomic_response_matrices':
            r.get('GLLBDxcAtomicResponseMatrices')
        }

    special = [('eigenvalues', 'Eigenvalues'),
               ('occupations', 'OccupationNumbers'),
               ('projections', 'Projections')]

    if r['Mode'] == 'pw':
        special.append(('coefficients', 'PseudoWaveFunctions'))
        try:
            data['wave_functions.']['indices'] = r.get('PlaneWaveIndices')
        except KeyError:
            pass
    elif r['Mode'] == 'fd':
        special.append(('values', 'PseudoWaveFunctions'))
    else:
        special.append(('coefficients', 'WaveFunctionCoefficients'))

    for name, old in special:
        try:
            fd, shape, size, dtype = r.get_file_object(old, ())
        except KeyError:
            continue
        offset = fd
        data['wave_functions.'][name + '.'] = {
            'ndarray': (shape, dtype.name, offset)
        }

    new = ulm.Reader(devnull,
                     data=data,
                     little_endian=r.byteswap ^ np.little_endian)

    for ref in new._data['wave_functions']._data.values():
        try:
            ref.fd = ref.offset
        except AttributeError:
            continue
        ref.offset = 0

    return new
Example #14
0
from __future__ import print_function
from ase.dft.kpoints import monkhorst_pack
from ase.lattice import bulk
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW

nk = 4
for mode in ('pw', 'fd'):
    kpts = monkhorst_pack((nk, nk, nk))
    kshift = 1.0 / (2 * nk)
    kpts += kshift

    atoms = bulk('MgO', 'rocksalt', a=4.212)

    if mode == 'pw':
        calc = GPAW(mode=PW(800),
                    basis='dzp',
                    xc='PBE',
                    maxiter=300,
                    kpts=kpts,
                    parallel={
                        'band': 1,
                        'domain': 1
                    },
                    setups={'Mg': '2'},
                    occupations=FermiDirac(0.01))
        atoms.set_calculator(calc)
        E1 = atoms.get_potential_energy()
        from gpaw.xc.hybridg import HybridXC
        exx = HybridXC('EXX', method='acdf')
        E_hf1 = E1 + calc.get_xc_difference(exx)
c = 3.22

pbc = [True, True, False]

GR = Atoms(symbols='C2', positions=[(0.5 * a, -np.sqrt(3) / 6 * a, 0.0),
                                    (0.5 * a, np.sqrt(3) / 6 * a, 0.0)],
           cell=[(0.5 * a, -0.5 * 3**0.5 * a, 0),
                 (0.5 * a, 0.5 * 3**0.5 * a, 0),
                 (0.0, 0.0, c * 2.0)], pbc=True)
old_cell = GR.get_cell()
old_cell[2, 2] = 2 * c
GR.set_cell(old_cell)
atoms = GR

calc = GPAW(h=0.18,
            mode=PW(400),
            kpts={'density': 10.0, 'gamma': True},
            occupations=FermiDirac(0.1))

atoms.set_calculator(calc)
atoms.get_potential_energy()
calc.write('gs.gpw')

kpts = find_high_symmetry_monkhorst_pack('gs.gpw', density=30,
                                         pbc=pbc)
responseGS = GPAW('gs.gpw',
                  fixdensity=True,
                  kpts=kpts,
                  parallel={'band': 1},
                  nbands=30,
                  occupations=FermiDirac(0.001),
from ase.build import bulk
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW

bulk_c = bulk('C', a=3.5454859)
calc = GPAW(
    mode=PW(600.0),
    xc='LDA',
    occupations=FermiDirac(width=0.01),
    kpts={
        'size': (6, 6, 6),
        'gamma': True
    },
    txt='diam_kern.ralda_01_lda.txt',
)

bulk_c.set_calculator(calc)
E_lda = bulk_c.get_potential_energy()
calc.diagonalize_full_hamiltonian()
calc.write('diam_kern.ralda.lda_wfcs.gpw', mode='all')
import numpy as np
from ase.lattice import bulk
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW
from gpaw.response.gw import GW

a = 5.431
atoms = bulk('Si', 'diamond', a=a)

for k in [3, 5, 7, 9]:

    kpts = (k, k, k)

    for ecut in [50, 100, 150, 200]:

        calc = GPAW(mode=PW(ecut),
                    kpts=kpts,
                    xc='LDA',
                    eigensolver='cg',
                    occupations=FermiDirac(0.001),
                    parallel={'band': 1},
                    txt='Si_groundstate_k%s_ecut%s.txt' % (k, ecut))

        atoms.set_calculator(calc)
        atoms.get_potential_energy()

        calc.diagonalize_full_hamiltonian()
        calc.write('Si_groundstate_k%s_ecut%s.gpw' % (k, ecut), 'all')

        gw = GW(file='Si_groundstate_k%s_ecut%s.gpw' % (k, ecut),
                nbands=None,
Example #18
0
myresults = paropen('si.atom.pbe_and_exx_energies.txt', 'a')

# Plane wave cutoff
pwcutoff = 400.0

# Do the isolated calculation

for L in [6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]:

    isolated_silicon = Atoms(symbols=['Si'],
                             positions=[[0.5 * L, 0.5 * L, 0.5 * L]],
                             cell=([L, 0, 0], [0, L, 0], [0, 0, L]),
                             pbc=(1, 1, 1))

    isolated_calc = GPAW(mode=PW(pwcutoff),
                         dtype=complex,
                         kpts=(1, 1, 1),
                         xc='PBE',
                         txt='si_isolated_pbe.txt',
                         occupations=FermiDirac(0.01, fixmagmom=True),
                         spinpol=True,
                         hund=True,
                         convergence={'density': 1.e-6},
                         mixer=Mixer(beta=0.05, nmaxold=5, weight=50.0))

    isolated_silicon.set_calculator(isolated_calc)

    e0_isolated_pbe = isolated_silicon.get_potential_energy()
    isolated_calc.write('si.pbe+exx.isolated.gpw', mode='all')
Example #19
0
               'disable_time_reversal': True},
              {'disable_point_group': False,
               'disable_time_reversal': True},
              {'disable_point_group': True,
               'disable_time_reversal': False},
              {'disable_point_group': False,
               'disable_time_reversal': False}]

if world.size > 1 and compiled_with_sl():
    DFsettings.append({'disable_point_group': False,
                       'disable_time_reversal': False,
                       'nblocks': 2})
              
for GSkwargs in GSsettings:
    calc = GPAW(h=0.18,
                mode=PW(600),
                occupations=FermiDirac(0.2),
                **GSkwargs)
 
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    calc.write('gr.gpw', 'all')

    dfs = []
    for kwargs in DFsettings:
        DF = DielectricFunction(calc='gr.gpw',
                                domega0=0.2,
                                eta=0.2,
                                ecut=40.0,
                                **kwargs)
        df1, df2 = DF.get_dielectric_function()
Example #20
0
from ase import Atoms
from gpaw import GPAW
from gpaw.mixer import FFTMixer
from gpaw.wavefunctions.pw import PW
from gpaw.test import equal

bulk = Atoms('Li', pbc=True)
bulk.set_cell((2.6, 2.6, 2.6))
k = 4
calc = GPAW(mode=PW(200),
            kpts=(k, k, k),
            mixer=FFTMixer(),
            verbose=1,
            eigensolver='rmm-diis')
bulk.set_calculator(calc)
e = bulk.get_potential_energy()
equal(e, -1.98481281259, 1.0e-6)
Example #21
0
from ase.build import molecule
from gpaw import GPAW
from gpaw.wavefunctions.pw import 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()
Example #22
0
    scale_atoms=False)
magmoms = [0.0 for n in range(len(bulk))]
for n, a in enumerate(bulk):
    if a.symbol == 'O':
        magmoms[n] = 0.5
bulk.set_initial_magnetic_moments(magmoms)

bulk.pbc = (True, True, True)

nk = 4
kpts = monkhorst_pack((nk, nk, nk))
kshift = 1. / (2 * nk)
kpts += np.array([kshift, kshift, kshift])

calc = GPAW(
    mode=PW(),
    xc='PBE',
    kpts=kpts,
    parallel={'band': 1},
    eigensolver='cg',
    txt='na2o4.txt',
)

bulk.set_calculator(calc)

try:
    bulk.get_potential_energy()
except ConvergenceError:
    pass

assert not calc.scf.converged
Example #23
0
H2 = Atoms('HH', [(a / 2, a / 2, (c - R) / 2),
                  (a / 2, a / 2, (c + R) / 2)],
           cell=(a, a, c),
           pbc=False)

txt = None

convergence = {'eigenstates': 1.e-6 * 40 * 1.5**3,
               'density': 1.e-2,
               'energy': 0.1}

# without potential
if True:
    if txt:
        print('\n################## no potential')
    c00 = GPAW(mode=PW(200), nbands=-1,
               convergence=convergence,
               txt=txt)
    c00.calculate(H2)
    eps00_n = c00.get_eigenvalues()

# 0 potential
if True:
    if txt:
        print('\n################## 0 potential')
    cp0 = ConstantPotential(0.0)
    c01 = GPAW(mode=PW(200), nbands=-2, external=cp0,
               convergence=convergence,
               txt=txt)
    c01.calculate(H2)
Example #24
0
resultfile = paropen('si.pbe+exx.results.txt', 'a')

# Plane wave cutoff
pwcutoff = 400.0

# NxNxN k-point sampling, gamma-centred grid
k = 6

# Si lattice constant
alat = 5.421

# Do the bulk calculation

bulk_crystal = bulk('Si', 'diamond', a=alat)
bulk_calc = GPAW(mode=PW(pwcutoff),
                 kpts={
                     'size': (k, k, k),
                     'gamma': True
                 },
                 xc='PBE',
                 occupations=FermiDirac(0.01),
                 txt='si.pbe+exx.pbe_output.txt',
                 parallel={'band': 1})

bulk_crystal.set_calculator(bulk_calc)
e0_bulk_pbe = bulk_crystal.get_potential_energy()

#  Write to file
bulk_calc.write('bulk.gpw', mode='all')
Example #25
0
if world.size == 1:
    scalapack1 = None
    scalapack2 = None
elif world.size == 2:
    scalapack1 = (2, world.size // 2, 32)
    scalapack2 = None
else:
    scalapack1 = (2, world.size // 2, 32)
    scalapack2 = (2, world.size // 4, 32)

# H2 --------------------------------------
H2 = Atoms('H2', [(0, 0, 0), (0, 0, 0.7413)])
H2.set_pbc(True)
H2.set_cell((2., 2., 3.))
H2.center()
calc = GPAW(mode=PW(210),
            eigensolver='rmm-diis',
            dtype=complex,
            xc='LDA',
            basis='dzp',
            nbands=8,
            convergence={'density': 1.e-6})
H2.set_calculator(calc)
H2.get_potential_energy()
calc.diagonalize_full_hamiltonian(nbands=80, scalapack=scalapack1)
calc.write('H2.gpw', mode='all')

ralda = FXCCorrelation('H2.gpw', xc='rALDA')
E_ralda_H2 = ralda.calculate(ecut=[200])

rapbe = FXCCorrelation('H2.gpw', xc='rAPBE')
Example #26
0
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW

# Plane wave cutoff
pwcutoff = 400.0

# NxNxN k-point sampling
k = 4

# Si lattice constant
alat = 5.421

# bulk calculation
bulk_crystal = bulk('Si', 'diamond', a=alat)
bulk_calc = GPAW(
    mode=PW(pwcutoff),
    kpts={
        'size': (k, k, k),
        'gamma': True
    },  # gamma-centred grid
    xc='PBE',
    occupations=FermiDirac(0.01),
    txt='si.rpa.pbe_output.txt',
    parallel={'band': 1})

bulk_crystal.set_calculator(bulk_calc)
e0_bulk_pbe = bulk_crystal.get_potential_energy()

# Now we have the density, but only the occupied states;
# at this point we diagonalise the full Hamiltonian to get
# the empty states as well (expensive)
Example #27
0
bulk = read('na2o4.xyz')
bulk.set_cell([4.31110615, 5.60646198, 3.48126881], scale_atoms=False)
magmoms = [0.0 for n in range(len(bulk))]
for n, a in enumerate(bulk):
    if a.symbol == 'O':
        magmoms[n] = 0.5
bulk.set_initial_magnetic_moments(magmoms)

bulk.pbc = (True, True, True)

nk = 4
kpts = monkhorst_pack((nk, nk, nk))
kshift = 1.0 / (2 * nk)
kpts += np.array([kshift, kshift, kshift])

calc = GPAW(mode=PW(),
            xc='PBE',
            kpts=kpts,
            parallel={'band': 1},
            eigensolver='cg',
            txt='na2o4.txt')

bulk.set_calculator(calc)

try:
    bulk.get_potential_energy()
except ConvergenceError:
    pass

assert not calc.scf.converged
Example #28
0
# This calculation is too heavy to run as an exercise!!

# Plane wave cutoff
pwcutoff = 400.0

# box length for isolated atom
L = 8.0

# Do the isolated calculation

isolated_silicon = Atoms(symbols=['Si'],
                         positions=[[0.5 * L, 0.5 * L, 0.5 * L]],
                         cell=([L, 0, 0], [0, L, 0], [0, 0, L]),
                         pbc=(1, 1, 1))

isolated_calc = GPAW(mode=PW(pwcutoff, force_complex_dtype=True),
                     parallel={'domain': 1},
                     xc='PBE',
                     txt='si_isolated_rpa.init_pbe.txt',
                     occupations=FermiDirac(0.01, fixmagmom=True),
                     spinpol=True,
                     hund=True,
                     convergence={'density': 1.e-6},
                     mixer=Mixer(beta=0.05, nmaxold=5, weight=50.0))

isolated_silicon.set_calculator(isolated_calc)

isolated_silicon.get_potential_energy()
isolated_calc.diagonalize_full_hamiltonian()  # ouch
isolated_calc.write('si.rpa.isolated.gpw', mode='all')
Example #29
0
from ase.lattice import bulk
from gpaw import GPAW, FermiDirac
from gpaw.wavefunctions.pw import PW
from gpaw.mpi import size

kpts = monkhorst_pack((10, 10, 10))
kpts += np.array([1 / 20., 1 / 20., 1 / 20.])

bulk = bulk('Na', 'bcc', a=4.23)

tag = 'Nabulk'

if 1:
    ecut = 350
    calc = GPAW(
        mode=PW(ecut),
        dtype=complex,
        basis='dzp',
        kpts=kpts,
        xc='PBE',
        eigensolver='rmm-diis',
        parallel={'band': size},
        txt='gs_occ_%s.txt' % (tag),
        nbands=4,
        occupations=FermiDirac(0.01),
        setups={'Na': '1'},
    )
    bulk.set_calculator(calc)
    bulk.get_potential_energy()
    calc.write('gs_occ_%s.gpw' % (tag))