Esempio n. 1
0
def test_combos():
    (atoms, constr, bondcombo_def, target_bondcombo, anglecombo_def,
     target_anglecombo, dihedralcombo_def,
     target_dihedralcombo) = setup_combos()

    ref_bondcombo = get_bondcombo(atoms, bondcombo_def)
    ref_anglecombo = get_anglecombo(atoms, anglecombo_def)
    ref_dihedralcombo = get_dihedralcombo(atoms, dihedralcombo_def)

    atoms.calc = EMT()
    atoms.set_constraint(constr)

    opt = BFGS(atoms, trajectory='opt.traj', logfile='opt.log')
    opt.run(fmax=0.01)

    new_bondcombo = get_bondcombo(atoms, bondcombo_def)
    new_anglecombo = get_anglecombo(atoms, anglecombo_def)
    new_dihedralcombo = get_dihedralcombo(atoms, dihedralcombo_def)

    err_bondcombo = new_bondcombo - ref_bondcombo
    err_anglecombo = new_anglecombo - ref_anglecombo
    err_dihedralcombo = new_dihedralcombo - ref_dihedralcombo

    print('error in bondcombo:', repr(err_bondcombo))
    print('error in anglecombo:', repr(err_anglecombo))
    print('error in dihedralcombo:', repr(err_dihedralcombo))

    for err in [err_bondcombo, err_anglecombo, err_dihedralcombo]:
        assert err < 1e-12
Esempio n. 2
0
def test_combos():
    # XXX https://gitlab.com/ase/ase/-/issues/868
    (atoms, constr, bondcombo_def, target_bondcombo, anglecombo_def,
     target_anglecombo, dihedralcombo_def,
     target_dihedralcombo) = setup_combos()

    ref_bondcombo = get_bondcombo(atoms, bondcombo_def)
    ref_anglecombo = get_anglecombo(atoms, anglecombo_def)
    ref_dihedralcombo = get_dihedralcombo(atoms, dihedralcombo_def)

    atoms.calc = EMT()
    atoms.set_constraint(constr)

    opt = BFGS(atoms)
    opt.run(fmax=0.01)

    new_bondcombo = get_bondcombo(atoms, bondcombo_def)
    new_anglecombo = get_anglecombo(atoms, anglecombo_def)
    new_dihedralcombo = get_dihedralcombo(atoms, dihedralcombo_def)

    err_bondcombo = new_bondcombo - ref_bondcombo
    err_anglecombo = new_anglecombo - ref_anglecombo
    err_dihedralcombo = new_dihedralcombo - ref_dihedralcombo

    print('error in bondcombo:', repr(err_bondcombo))
    print('error in anglecombo:', repr(err_anglecombo))
    print('error in dihedralcombo:', repr(err_dihedralcombo))

    for err in [err_bondcombo, err_anglecombo, err_dihedralcombo]:
        assert err < 1e-12
Esempio n. 3
0
def relax(atoms, name, calc_mag_state):
    # relax only along xy-axis to opitmize lattice
    sf = UnitCellFilter(atoms, mask=[1, 1, 0, 0, 0, 0])
    opt = BFGS(sf,
               trajectory='{0}_relaxed.traj'.format(name),
               logfile='{0}_relaxed.log'.format(name))
    opt.run(fmax=0.05)  # until forces < 0.05 eV/atom
    calc.write('relaxed.gpw')  #write gpw file for the magnetic relaxations
Esempio n. 4
0
def opt_emt_bfgs(atoms):
    from ase.calculators.emt import EMT
    from ase.optimize.bfgs import BFGS
    tmpAtoms = atoms.copy()
    tmpAtoms.calc = EMT()
    geomOpt = BFGS(tmpAtoms, maxstep=0.1, trajectory=None, logfile=None)
    geomOpt.run(fmax=0.01, steps=1000)
    return tmpAtoms
Esempio n. 5
0
 def preopt_hooke(self, cutoff=1.5, toler=0.2, stepsize=0.05, nsteps=200):
     from gocia.calc.hooke import Hooke
     from ase.optimize.bfgs import BFGS
     tmpAtoms = self.get_allAtoms()
     tmpAtoms.calc = Hooke(cutoff=cutoff, tolerAngs=toler, tolerMult=toler)
     geomOpt = BFGS(tmpAtoms,
                    maxstep=stepsize,
                    trajectory=None,
                    logfile=None)
     geomOpt.run(fmax=0.01, steps=nsteps)
     print(' - Hookean pre-optimization: RMSD = %.3f Angstroms' %
           geom.RMSD(self.get_allAtoms(), tmpAtoms))
     self.set_allAtoms(tmpAtoms)
Esempio n. 6
0
 def __init__(self, atoms, restart=None, logfile='-', trajectory=None, maxstep=None, 
             master=None, initial=None, rmsd_dev=1000.0, molindixes=None, structure=None, 
             H0=None, fixed_frame=None, parameters=None, mu=None, A=None, known=None):
     BFGS.__init__(self, atoms, restart=restart, logfile=logfile, trajectory=trajectory, maxstep=0.04, master=None)
     
     # initial hessian
     
     self.H0 = H0 
     self.initial=initial
     self.rmsd_dev=rmsd_dev
     self.molindixes = molindixes
     self.structure = structure
     self.fixed_frame = fixed_frame
     self.parameters = parameters
Esempio n. 7
0
 def preopt_lj(self, fileBaseName='tmp',\
     toler=0.2, stepsize=0.05, nsteps=200):
     #        from ase.calculators.lj import LennardJones
     from gocia.calc.lj import LennardJones
     from ase.optimize.bfgs import BFGS
     tmpAtoms = self.get_allAtoms()
     tmpAtoms.calc = LennardJones(tolerAngs=toler, tolerMult=toler)
     geomOpt = BFGS(tmpAtoms,
                    maxstep=stepsize,
                    trajectory=None,
                    logfile=None)
     geomOpt.run(fmax=0.01, steps=nsteps)
     print(' - L-J pre-optimization: RMSD = %.3f Angstroms' %
           geom.RMSD(self.get_allAtoms(), tmpAtoms))
     self.set_allAtoms(tmpAtoms)
Esempio n. 8
0
def test_fixinternals():
    (atoms, constr, bond_def, target_bond, angle_def, target_angle,
     dihedral_def, target_dihedral) = setup_fixinternals()

    calc = EMT()

    opt = BFGS(atoms, trajectory='opt.traj', logfile='opt.log')

    previous_angle = atoms.get_angle(*angle_def)
    previous_dihedral = atoms.get_dihedral(*dihedral_def)

    print('angle before', previous_angle)
    print('dihedral before', previous_dihedral)
    print('bond length before', atoms.get_distance(*bond_def))
    print('target bondlength', target_bond)

    atoms.calc = calc
    atoms.set_constraint(constr)
    print('-----Optimization-----')
    opt.run(fmax=0.01)

    new_angle = atoms.get_angle(*angle_def)
    new_dihedral = atoms.get_dihedral(*dihedral_def)
    new_bondlength = atoms.get_distance(*bond_def)

    print('angle after', new_angle)
    print('dihedral after', new_dihedral)
    print('bondlength after', new_bondlength)

    err1 = new_angle - previous_angle
    err2 = new_dihedral - previous_dihedral
    err3 = new_bondlength - target_bond

    print('error in angle', repr(err1))
    print('error in dihedral', repr(err2))
    print('error in bondlength', repr(err3))

    assert err1 < 1e-11
    assert err2 < 1e-12
    assert err3 < 1e-12
Esempio n. 9
0
def test_gfn1xtb_bfgs():
    """Perform geometry optimization with GFN1-xTB and BFGS"""

    thr = 1.0e-5

    atoms = Atoms(
        symbols="NHCHC2H3OC2H3ONHCH3",
        positions=np.array([
            [1.40704587284727, -1.26605342016611, -1.93713466561923],
            [1.85007200612454, -0.46824072777417, -1.50918242392545],
            [-0.03362432532150, -1.39269245193812, -1.74003582081606],
            [-0.56857009928108, -1.01764444489068, -2.61263467107342],
            [-0.44096297340282, -2.84337808903410, -1.48899734014499],
            [-0.47991761226058, -0.55230954385212, -0.55520222968656],
            [-1.51566045903090, -2.89187354810876, -1.32273881320610],
            [-0.18116520746778, -3.45187805987944, -2.34920431470368],
            [0.06989722340461, -3.23298998903001, -0.60872832703814],
            [-1.56668253918793, 0.00552120970194, -0.52884675001441],
            [1.99245341064342, -1.73097165236442, -3.08869239114486],
            [3.42884244212567, -1.30660069291348, -3.28712665743189],
            [3.87721962540768, -0.88843123009431, -2.38921453037869],
            [3.46548545761151, -0.56495308290988, -4.08311788302584],
            [4.00253374168514, -2.16970938132208, -3.61210068365649],
            [1.40187968630565, -2.43826111827818, -3.89034127398078],
            [0.40869198386066, -0.49101709352090, 0.47992424955574],
            [1.15591901335007, -1.16524842262351, 0.48740266650199],
            [0.00723492494701, 0.11692276177442, 1.73426297572793],
            [0.88822128447468, 0.28499001838229, 2.34645658013686],
            [-0.47231557768357, 1.06737634000561, 1.52286682546986],
            [-0.70199987915174, -0.50485938116399, 2.28058247845421],
        ]),
    )

    atoms.calc = XTB(method="GFN1-xTB", accuracy=2.0, cache_api=False)
    opt = BFGS(atoms)
    opt.run(fmax=0.1)

    assert approx(atoms.get_potential_energy(), thr) == -951.9006674709672
    assert approx(np.linalg.norm(atoms.get_forces(), ord=2),
                  thr) == 0.2052117803208497
Esempio n. 10
0
from ase.structure import molecule
from ase.optimize.bfgs import BFGS
from ase.calculators.nwchem import NWChem
from ase.data.g2_1 import molecule_names, atom_names


c = ase.db.connect('g2-1.db')

for name in molecule_names + atom_names:
    id = c.reserve(name=name, calculator='nwchem')
    if id is None:
        continue
    atoms = molecule(name)
    atoms.calc = NWChem(command='mpiexec -np 4 nwchem PREFIX.nw > PREFIX.out',
                        geometry='noautosym nocenter noautoz',
                        task='gradient',
                        xc='PBE',
                        grid='nodisk',
                        tolerances='tight',
                        basis='def2-qzvppd',
                        basispar='spherical',
                        direct='noio',
                        label=name)
    atoms.get_forces()
    c.write(atoms, name=name, relaxed=False)
    if len(atoms) > 1:
        opt = BFGS(atoms, logfile=name + '.nwchem.log')
        opt.run(0.01)
        c.write(atoms, name=name, relaxed=True)
    del c[id]
Esempio n. 11
0
import ase.io as fio
from gocia.interface import Interface

from ase.calculators.emt import EMT
from ase.optimize.bfgs import BFGS

subs = fio.read('subs-ini.vasp')
subs.calc = EMT()
geomOpt = BFGS(subs, maxstep=0.05)
geomOpt.run(fmax=0.001, steps=200)
fio.write('subs-opt.vasp', subs)

Esempio n. 12
0
        atoms = Atoms('N2', positions=[(0, 0, 0), (0, 0, d_bond + d_disp)])
        atoms.set_pbc(False)
        atoms.center(vacuum=6.0)
        cell_c = np.sum(atoms.get_cell()**2, axis=1)**0.5
        N_c = 8 * np.round(cell_c / (0.2 * 8))
        calc = GPAW(
            gpts=N_c,
            nbands=5,
            basis='dzp',  #TODO xc='PBE'
            txt=name + '_gs.txt',
            parallel={'band': 1})
        atoms.set_calculator(calc)

        # QuasiNewton relaxation before we increase the number of bands
        qn = BFGS(atoms,
                  logfile=name + '_gs.log',
                  trajectory=name + '_gs.traj')
        qn.run(0.01, steps=100)

        # Converge enough unoccupied bands for dSCF expansion
        calc.set(nbands=10,
                 spinpol=True,
                 occupations=FermiDirac(0.1),
                 convergence={
                     'bands': -2,
                     'eigenstates': 1.0e-9
                 })
        atoms.get_potential_energy()
        calc.write(name + '_gs.gpw', mode='all')
        del qn, calc, atoms
        time.sleep(10)
Esempio n. 13
0
from ase import io
from ase.calculators.orca import ORCA
from ase.optimize.fire import FIRE
from ase.optimize.bfgs import BFGS

#Optimise molecule
ethan = io.read('xyz_files/ethan.xyz')
orca_calc= ORCA(
    label="orca",
    maxiter=200,
    task="gradient",
    orcasimpleinput="HF-3c"
)
ethan.set_calculator(orca_calc)

#opt = FIRE(ethan, trajectory='ethan.traj')
#opt.run(fmax=0.00241)
opt = BFGS(ethan, trajectory='ethan.traj')
opt.run(fmax=0.0005)
def test_dihedralconstraint():
    from math import pi
    from ase.calculators.emt import EMT
    from ase.constraints import FixInternals
    from ase.optimize.bfgs import BFGS
    from ase.build import molecule

    system = molecule('CH3CH2OH', vacuum=5.0)
    system.rattle(stdev=0.3)

    # Angles, Bonds, Dihedrals are built up with  pairs of constraint
    # value and indices defining the constraint

    # Fix this dihedral angle to whatever it was from the start
    indices = [6, 0, 1, 2]
    dihedral1 = system.get_dihedral(*indices)

    # Fix angle to whatever it was from the start
    indices2 = [6, 0, 1]
    angle1 = system.get_angle(*indices2)
    # system.set_dihedral(indices, pi/20, mask=[0,1,1,1,1,1,0,0,0])

    # Fix bond between atoms 1 and 2 to 1.4
    target_bondlength = 1.4
    indices_bondlength = [1, 2]

    constraint = FixInternals(bonds=[(target_bondlength, indices_bondlength)],
                              angles=[(angle1 * pi / 180, indices2)],
                              dihedrals=[(dihedral1 * pi / 180, indices)],
                              epsilon=1e-10)

    print(constraint)

    calc = EMT()

    opt = BFGS(system, trajectory='opt.traj', logfile='opt.log')

    previous_angle = system.get_angle(*indices2)
    previous_dihedral = system.get_dihedral(*indices)

    print('angle before', previous_angle)
    print('dihedral before', previous_dihedral)
    print('bond length before', system.get_distance(*indices_bondlength))
    print('(target bondlength %s)', target_bondlength)

    system.set_calculator(calc)
    system.set_constraint(constraint)
    print('-----Optimization-----')
    opt.run(fmax=0.01)

    new_angle = system.get_angle(*indices2)
    new_dihedral = system.get_dihedral(*indices)
    new_bondlength = system.get_distance(*indices_bondlength)

    print('angle after', new_angle)
    print('dihedral after', new_dihedral)
    print('bondlength after', new_bondlength)

    err1 = new_angle - previous_angle
    err2 = new_dihedral - previous_dihedral
    err3 = new_bondlength - target_bondlength

    print('error in angle', repr(err1))
    print('error in dihedral', repr(err2))
    print('error in bondlength', repr(err3))

    assert err1 < 1e-11
    assert err2 < 1e-12
    assert err3 < 1e-12
Esempio n. 15
0
#calc.set(xc = 'PBE', lreal = False,
calc.set(
    xc='PBE',
    mode=PW(400),
    #            nsw=30, ediff=1e-8, ibrion=2, kpts=[3,3,3])
    #            ediff=1e-8, ibrion=2, kpts=[3,3,3])
    #            ibrion=2, kpts=[3,3,3])
    kpts=[3, 3, 3])

# Set the calculation mode first.
# Full structure optimization in this case.
# Not all calculators have this type of internal minimizer!
#calc.set(isif=3)

# from ase/GPAW stress example

print("Potential Energy: " + str(cryst.get_potential_energy()))

uf = UnitCellFilter(cryst)
relax = BFGS(uf)
relax.run(fmax=0.05)

stress = cryst.get_stress()
print(stress)

a = cryst.get_cell()[0, 0]

print("optimized lattice constant: " + a)

### EOF ###
Esempio n. 16
0
import ase.db
from ase.build import molecule
from ase.optimize.bfgs import BFGS
from ase.data.g2_1 import molecule_names, atom_names

from gpaw import GPAW, PW, Mixer, FermiDirac

c = ase.db.connect('g2-1.db')

for name in molecule_names + atom_names:
    id = c.reserve(name=name, calculator='gpaw')
    if id is None:
        continue
    atoms = molecule(name)
    atoms.cell = [12, 13.01, 14.02]
    atoms.center()
    atoms.calc = GPAW(mode=PW(800),
                      xc='PBE',
                      occupations=FermiDirac(0.0, fixmagmom=True),
                      txt=name + '.txt')
    if name in ['Na2', 'NaCl', 'NO', 'ClO', 'Cl', 'Si']:
        atoms.calc.set(eigensolver='dav', mixer=Mixer(0.05, 2))
    atoms.get_forces()
    c.write(atoms, id=id, name=name, relaxed=False)
    if len(atoms) > 1:
        opt = BFGS(atoms, logfile=name + '.gpaw.log')
        opt.run(0.01)
        c.write(atoms, name=name, relaxed=True)
Esempio n. 17
0
#system.set_dihedral(indices, pi/20, mask=[0,1,1,1,1,1,0,0,0])

# Fix bond between atoms 1 and 2 to 1.4
target_bondlength = 1.4
indices_bondlength = [1, 2]

constraint = FixInternals(bonds=[(target_bondlength, indices_bondlength)],
                          angles=[(angle1, indices2)],
                          dihedrals=[(dihedral1, indices)],
                          epsilon=1e-10)

print(constraint)

calc = EMT()

opt = BFGS(system, trajectory='opt.traj', logfile='opt.log')

previous_angle = system.get_angle(indices2)
previous_dihedral = system.get_dihedral(indices)

print('angle before', previous_angle)
print('dihedral before', previous_dihedral)
print('bond length before', system.get_distance(*indices_bondlength))
print('(target bondlength %s)', target_bondlength)

system.set_calculator(calc)
system.set_constraint(constraint)
print('-----Optimization-----')
opt.run(fmax=0.01)

new_angle = system.get_angle(indices2)
                           relativistic=relativistic)
            if id is None:
                continue
            # set calculator
            atoms.calc = GPAW(
                txt=label + '.txt',
                xc='PBE',
                kpts=kpts,
                maxiter=777,
                eigensolver='dav',
                parallel={'band': 1},
                idiotproof=False,
                )
            atoms.calc.set(**kwargs)  # remaining calc keywords
            if optimize:
                opt = BFGS(atoms, logfile=label + '.opt',
                           trajectory=label + '.traj')
                opt.run(fmax=0.01)
            t = time.time()
            atoms.get_potential_energy()
            c.write(atoms,
                    name=name, adsorbate=adsorbate, category=category,
                    site=site,
                    ecut=ecut,
                    kptdensity=kptdensity, width=width,
                    relativistic=relativistic,
                    niter=atoms.calc.get_number_of_iterations(),
                    time=time.time()-t)
            traj.write(atoms)
            del c[id]
Esempio n. 19
0
def test_dihedralconstraint():
    from ase.calculators.emt import EMT
    from ase.constraints import FixInternals
    from ase.optimize.bfgs import BFGS
    from ase.build import molecule

    system = molecule('CH3CH2OH', vacuum=5.0)
    system.rattle(stdev=0.3)

    # Angles, Bonds, Dihedrals are built up with pairs of constraint
    # value and indices defining the constraint
    # Linear combinations of bond lengths are built up similarly with the
    # coefficients appended to the indices defining the constraint

    # Fix this dihedral angle to whatever it was from the start
    indices = [6, 0, 1, 2]
    dihedral1 = system.get_dihedral(*indices)

    # Fix angle to whatever it was from the start
    indices2 = [6, 0, 1]
    angle1 = system.get_angle(*indices2)

    # Fix bond between atoms 1 and 2 to 1.4
    target_bondlength = 1.4
    indices_bondlength = [1, 2]

    # Fix linear combination of two bond lengths with atom indices 0-8 and
    # 0-6 with weighting coefficients 1.0 and -1.0 to the current value.
    # In other words, fulfil the following constraint:
    # 1 * system.get_distance(0, 8) -1 * system.get_distance(0, 6) = const.
    bondcombo_def = [[0, 8, 1.0], [0, 6, -1.0]]

    def get_bondcombo(system, bondcombo_def):
        return sum([
            defin[2] * system.get_distance(defin[0], defin[1])
            for defin in bondcombo_def
        ])

    target_bondcombo = get_bondcombo(system, bondcombo_def)

    constraint = FixInternals(bonds=[(target_bondlength, indices_bondlength)],
                              angles_deg=[(angle1, indices2)],
                              dihedrals_deg=[(dihedral1, indices)],
                              bondcombos=[(target_bondcombo, bondcombo_def)],
                              epsilon=1e-10)

    print(constraint)

    calc = EMT()

    opt = BFGS(system, trajectory='opt.traj', logfile='opt.log')

    previous_angle = system.get_angle(*indices2)
    previous_dihedral = system.get_dihedral(*indices)
    previous_bondcombo = get_bondcombo(system, bondcombo_def)

    print('angle before', previous_angle)
    print('dihedral before', previous_dihedral)
    print('bond length before', system.get_distance(*indices_bondlength))
    print('(target bondlength %s)', target_bondlength)
    print('linear bondcombination before', previous_bondcombo)

    system.calc = calc
    system.set_constraint(constraint)
    print('-----Optimization-----')
    opt.run(fmax=0.01)

    new_angle = system.get_angle(*indices2)
    new_dihedral = system.get_dihedral(*indices)
    new_bondlength = system.get_distance(*indices_bondlength)
    new_bondcombo = get_bondcombo(system, bondcombo_def)

    print('angle after', new_angle)
    print('dihedral after', new_dihedral)
    print('bondlength after', new_bondlength)
    print('linear bondcombination after', new_bondcombo)

    err1 = new_angle - previous_angle
    err2 = new_dihedral - previous_dihedral
    err3 = new_bondlength - target_bondlength
    err4 = new_bondcombo - previous_bondcombo

    print('error in angle', repr(err1))
    print('error in dihedral', repr(err2))
    print('error in bondlength', repr(err3))
    print('error in bondcombo', repr(err4))

    assert err1 < 1e-11
    assert err2 < 1e-12
    assert err3 < 1e-12
    assert err4 < 1e-12
Esempio n. 20
0
from ase import Atoms
from ase.lattice import bulk
from ase.optimize.bfgs import BFGS
from ase.constraints import UnitCellFilter
from gpaw import GPAW
from gpaw import PW
import numpy as np

cell = bulk('Si', 'fcc', a=6.0).get_cell()
# Experimental Lattice constant is a=5.421 A
a = Atoms('Si2',
          cell=cell,
          pbc=True,
          scaled_positions=((0, 0, 0), (0.25, 0.25, 0.25)))

calc = GPAW(
    xc='PBE',
    mode=PW(400),
    # mode=PW(400, cell=a.get_cell()),  # fix no of planewaves!
    kpts=(4, 4, 4),
    # convergence={'eigenstates': 1.e-10},  # converge tightly!
    txt='stress.txt')
a.set_calculator(calc)

uf = UnitCellFilter(a)
relax = BFGS(uf)
relax.run(fmax=0.05)  # Consider much tighter fmax!

a = np.dot(a.get_cell()[0], a.get_cell()[0])**0.5 * 2**0.5
print('Relaxed lattice parameter: a = %s A' % a)
Esempio n. 21
0
from ase import Atoms
from ase.lattice import bulk
from ase.optimize.bfgs import BFGS
from ase.constraints import UnitCellFilter
from gpaw import GPAW
from gpaw import PW
import numpy as np

cell = bulk('Si', 'fcc', a=6.0).get_cell()
# Experimental Lattice constant is a=5.421 A
a = Atoms('Si2', cell=cell, pbc=True,
          scaled_positions=((0,0,0), (0.25,0.25,0.25)))

calc = GPAW(xc='PBE',
            mode=PW(400),
            #mode=PW(400, cell=a.get_cell()),  # fix no of planewaves!
            kpts=(4,4,4),
            #convergence={'eigenstates': 1.e-10},  # converge tightly!
            txt='stress.txt')
a.set_calculator(calc)

uf = UnitCellFilter(a)
relax = BFGS(uf)
relax.run(fmax=0.05)  # Consider much tighter fmax!

a = np.dot(a.get_cell()[0], a.get_cell()[0])**0.5 * 2**0.5
print 'Relaxed lattice parameter: a = %s A' % a
Esempio n. 22
0
    def optimise_positions(self, fmax=0.01, use_precon=None, use_armijo=None):
        """ Relax atoms positions with the fixed cell to a given force
        threshold """
        if use_precon is None:
            use_precon = self.parameters.use_precon
        if use_armijo is None:
            use_armijo = self.parameters.use_armijo

        if use_precon:
            precon = Exp(A=3, use_pyamg=False)
        else:
            precon = None
        if self.parameters.optimizer == 'BFGS':
            relax = BFGS(self.atoms)
        elif self.parameters.optimizer == 'FIRE':
            relax = PreconFIRE(self.atoms, precon=precon)
        elif self.parameters.optimizer == 'ase-FIRE':
            relax = ASEFIRE(self.atoms)
        elif self.parameters.optimizer == 'LBFGS':
            relax = PreconLBFGS(self.atoms,
                                precon=precon,
                                use_armijo=use_armijo)
        elif self.parameters.optimizer == 'ase-LBFGS':
            relax = ASELBFGS(self.atoms)
        else:
            parprint("ERROR: unknown optimizer {}. "
                     "Reverting to BFGS".format(self.parameters.optimizer))
            relax = BFGS(self.atoms)
        name = self.atoms.get_chemical_formula()
        relax.attach(
            lambda: self.atoms.calc.write(name + '_relax.gpw', mode='all'))
        relax.attach(lambda: write_atat_input(self.atoms, 'str_last.out'))
        relax.run(fmax=fmax, steps=100)
        if not relax.converged():
            relax = ASELBFGS(self.atoms)
            relax.run(fmax=fmax, steps=100)
            if not relax.converged():
                max_force = self.atoms.get_forces()
                max_force = np.sqrt((max_force**2).sum(axis=1).max())
                print('WARNING: optimisation not converged.' +
                      ' Maximum force: %.4f' % max_force)
Esempio n. 23
0
niter = ndiv * int(np.ceil(2 * period / (ndiv * timestep)))

if __name__ == '__main__':
    if not os.path.isfile(name + '_gs.gpw'):
        # Calculator for quick ground state relaxation
        atoms = Atoms('N2', positions=[(0, 0, 0), (0, 0, d_bond + d_disp)])
        atoms.set_pbc(False)
        atoms.center(vacuum=6.0)
        cell_c = np.sum(atoms.get_cell()**2, axis=1)**0.5
        N_c = 8 * np.round(cell_c / (0.2 * 8))
        calc = GPAW(gpts=N_c, nbands=5, basis='dzp', #TODO xc='PBE'
                    txt=name + '_gs.txt', parallel={'band': 1})
        atoms.set_calculator(calc)

        # QuasiNewton relaxation before we increase the number of bands
        qn = BFGS(atoms, logfile=name + '_gs.log', trajectory=name + '_gs.traj')
        qn.run(0.01, steps=100)

        # Converge enough unoccupied bands for dSCF expansion
        calc.set(nbands=10, spinpol=True, occupations=FermiDirac(0.1),
                 convergence={'bands': -2, 'eigenstates': 1.0e-9})
        atoms.get_potential_energy()
        calc.write(name + '_gs.gpw', mode='all')
        del qn, calc, atoms
        time.sleep(10)

    while not os.path.isfile(name + '_gs.gpw'):
        print 'Node %d waiting for %s...' % (world.rank, name + '_gs.gpw')
        time.sleep(10)
    world.barrier()
    if atoms.get_initial_magnetic_moments().any():  # spin-polarization
        kwargs.update({'spinpol': True})
        kwargs.update({'fix_magmom': True})
    atoms.calc = espresso(outdir=label,
                          xc='PBE',
                          pw=pw*Rydberg,
                          dw=dw*Rydberg,
                          sigma=0.0,
                          mode='scf',
                          # will overwrite disk_io parameter if True
                          output={'avoidio':True},
                          convergence={'mixing': 0.05, 'maxsteps':500,},
                          dontcalcforces=True,
                          )
    atoms.calc.set(**kwargs)  # remaining calc keywords
    t = time.time()
    atoms.calc.results = {'energy': atoms.get_potential_energy()}
    c.write(atoms, name=name, relaxed=False, pw=pw, dw=dw,
            time=time.time()-t)
    # no optimization: espresso does not conform yet to ASE interface style
    if 0 and len(atoms) > 1:
        opt = BFGS(atoms,
                   logfile=name + '_' + code + '.log',
                   trajectory=name + '_' + code + '.traj')
        t = time.time()
        opt.run(0.005)
        atoms.get_potential_energy()
        c.write(atoms, name=name, relaxed=True, pw=pw, dw=dw,
                time=time.time()-t)
    del c[id]
Esempio n. 25
0
import ase.db
from ase.structure import molecule
from ase.optimize.bfgs import BFGS
from ase.calculators.nwchem import NWChem
from ase.data.g2_1 import molecule_names, atom_names

c = ase.db.connect('g2-1.db')

for name in molecule_names + atom_names:
    id = c.reserve(name=name, calculator='nwchem')
    if id is None:
        continue
    atoms = molecule(name)
    atoms.calc = NWChem(command='mpiexec -np 4 nwchem PREFIX.nw > PREFIX.out',
                        geometry='noautosym nocenter noautoz',
                        task='gradient',
                        xc='PBE',
                        grid='nodisk',
                        tolerances='tight',
                        basis='def2-qzvppd',
                        basispar='spherical',
                        direct='noio',
                        label=name)
    atoms.get_forces()
    c.write(atoms, name=name, relaxed=False)
    if len(atoms) > 1:
        opt = BFGS(atoms, logfile=name + '.nwchem.log')
        opt.run(0.01)
        c.write(atoms, name=name, relaxed=True)
    del c[id]