Пример #1
0
def test_combine(testdir):
    dirname = 'subdir'
    vibname = 'ir'
    with workdir(dirname, mkdir=True):
        atoms = molecule('C2H6')
        ir = Infrared(atoms)
        assert ir.name == vibname
        ir.calc = RandomCalculator()
        ir.run()
        freqs = ir.get_frequencies()
        ints = ir.intensities
        assert ir.combine() == 49

        ir = Infrared(atoms)
        assert (freqs == ir.get_frequencies()).all()
        assert (ints == ir.intensities).all()

        vib = Vibrations(atoms, name=vibname)
        assert (freqs == vib.get_frequencies()).all()

        # Read the data from other working directory
        with workdir('..'):
            ir = Infrared(atoms, name=f'{dirname}/{vibname}')
            assert (freqs == ir.get_frequencies()).all()

        ir = Infrared(atoms)
        assert ir.split() == 1
        assert (freqs == ir.get_frequencies()).all()
        assert (ints == ir.intensities).all()

        vib = Vibrations(atoms, name=vibname)
        assert (freqs == vib.get_frequencies()).all()

        assert ir.clean() == 49
Пример #2
0
def test_combine():
    import os
    from numpy.random import RandomState

    from ase.build import molecule
    from ase.vibrations import Vibrations
    from ase.vibrations import Infrared


    class RandomCalculator():
        """Fake Calculator class.

        """
        def __init__(self):
            self.rng = RandomState(42)

        def get_forces(self, atoms):
            return self.rng.rand(len(atoms), 3)

        def get_dipole_moment(self, atoms):
            return self.rng.rand(3)


    atoms = molecule('C2H6')
    ir = Infrared(atoms)
    ir.calc = RandomCalculator()
    ir.run()
    freqs = ir.get_frequencies()
    ints = ir.intensities
    assert ir.combine() == 49

    ir = Infrared(atoms)
    assert (freqs == ir.get_frequencies()).all()
    assert (ints == ir.intensities).all()

    vib = Vibrations(atoms, name='ir')
    assert (freqs == vib.get_frequencies()).all()

    # Read the data from other working directory
    dirname = os.path.basename(os.getcwd())
    os.chdir('..')  # Change working directory
    ir = Infrared(atoms, name=os.path.join(dirname, 'ir'))
    assert (freqs == ir.get_frequencies()).all()
    os.chdir(dirname)

    ir = Infrared(atoms)
    assert ir.split() == 1
    assert (freqs == ir.get_frequencies()).all()
    assert (ints == ir.intensities).all()

    vib = Vibrations(atoms, name='ir')
    assert (freqs == vib.get_frequencies()).all()

    assert ir.clean() == 49
Пример #3
0
def test_vib():
    import os
    from ase import Atoms
    from ase.calculators.emt import EMT
    from ase.optimize import QuasiNewton
    from ase.vibrations import Vibrations
    from ase.thermochemistry import IdealGasThermo

    n2 = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
    QuasiNewton(n2).run(fmax=0.01)
    vib = Vibrations(n2)
    vib.run()
    freqs = vib.get_frequencies()
    print(freqs)
    vib.summary()
    print(vib.get_mode(-1))
    vib.write_mode(n=None, nimages=20)
    vib_energies = vib.get_energies()

    for image in vib.iterimages():
        assert len(image) == 2

    thermo = IdealGasThermo(vib_energies=vib_energies,
                            geometry='linear',
                            atoms=n2,
                            symmetrynumber=2,
                            spin=0)
    thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)

    assert vib.clean(empty_files=True) == 0
    assert vib.clean() == 13
    assert len(list(vib.iterimages())) == 13

    d = dict(vib.iterdisplace(inplace=False))

    for name, atoms in vib.iterdisplace(inplace=True):
        assert d[name] == atoms

    vib = Vibrations(n2)
    vib.run()
    assert vib.combine() == 13
    assert (freqs == vib.get_frequencies()).all()

    vib = Vibrations(n2)
    assert vib.split() == 1
    assert (freqs == vib.get_frequencies()).all()

    assert vib.combine() == 13
    # Read the data from other working directory
    dirname = os.path.basename(os.getcwd())
    os.chdir('..')  # Change working directory
    vib = Vibrations(n2, name=os.path.join(dirname, 'vib'))
    assert (freqs == vib.get_frequencies()).all()
    assert vib.clean() == 1
Пример #4
0
    def test_vibrations_restart_dir(self, testdir, random_dimer):
        vib = Vibrations(random_dimer)
        vib.run()
        freqs = vib.get_frequencies()
        assert freqs is not None

        # write/read the data from another working directory
        atoms = random_dimer.copy()  # This copy() removes the Calculator

        with ase.utils.workdir('run_from_here', mkdir=True):
            vib = Vibrations(atoms, name=str(Path.cwd().parent / 'vib'))
            assert_array_almost_equal(freqs, vib.get_frequencies())
            assert vib.clean() == 13
Пример #5
0
 def characteriseTSinternal(self, mol):
     os.chdir((self.workingDir + '/Raw/' + self.procNum))
     if (self.lowMeth == 'nwchem'):
         mol = tl.setCalc(mol, self.lowString, 'nwchem2', self.lowLev)
         self.Reac.get_forces()
     else:
         mol = tl.setCalc(mol, self.lowString, self.lowMeth, self.lowLev)
     vib = Vibrations(mol)
     vib.clean()
     vib.run()
     viblist = vib.get_frequencies()
     print("getting vibs")
     TSFreqs, zpe = tl.getVibString(viblist, False, True)
     print("vibs done " + str(zpe))
     imaginaryFreq = tl.getImageFreq(viblist)
     vib.clean()
     os.chdir((self.workingDir))
     # Finally get single point energy
     mol = tl.setCalc(mol, self.singleString, self.singleMeth,
                      self.singleLev)
     print("Getting single point energy for TS = " +
           str(mol.get_potential_energy()) + "zpe = " + str(zpe) +
           "reactant energy = " + str(self.reactantEnergy))
     energy = mol.get_potential_energy() + zpe
     return TSFreqs, imaginaryFreq, zpe, energy
Пример #6
0
def test_Ag_Cu100():
    from math import sqrt
    from ase import Atom, Atoms
    from ase.neb import NEB
    from ase.constraints import FixAtoms
    from ase.vibrations import Vibrations
    from ase.calculators.emt import EMT
    from ase.optimize import QuasiNewton, BFGS

    # Distance between Cu atoms on a (100) surface:
    d = 3.6 / sqrt(2)
    initial = Atoms('Cu',
                    positions=[(0, 0, 0)],
                    cell=(d, d, 1.0),
                    pbc=(True, True, False))
    initial *= (2, 2, 1)  # 2x2 (100) surface-cell

    # Approximate height of Ag atom on Cu(100) surfece:
    h0 = 2.0
    initial += Atom('Ag', (d / 2, d / 2, h0))

    # Make band:
    images = [initial.copy() for i in range(6)]
    neb = NEB(images, climb=True)

    # Set constraints and calculator:
    constraint = FixAtoms(range(len(initial) - 1))
    for image in images:
        image.calc = EMT()
        image.set_constraint(constraint)

    # Displace last image:
    images[-1].positions[-1] += (d, 0, 0)

    # Relax height of Ag atom for initial and final states:
    dyn1 = QuasiNewton(images[0])
    dyn1.run(fmax=0.01)
    dyn2 = QuasiNewton(images[-1])
    dyn2.run(fmax=0.01)

    # Interpolate positions between initial and final states:
    neb.interpolate()

    for image in images:
        print(image.positions[-1], image.get_potential_energy())

    dyn = BFGS(neb, trajectory='mep.traj')
    dyn.run(fmax=0.05)

    for image in images:
        print(image.positions[-1], image.get_potential_energy())

    a = images[0]
    vib = Vibrations(a, [4])
    vib.run()
    print(vib.get_frequencies())
    vib.summary()
    print(vib.get_mode(-1))
    vib.write_mode(-1, nimages=20)
Пример #7
0
 def characteriseFreqInternal(self, mol):
     os.chdir((self.workingDir + '/' + '/Raw/' + self.procNum))
     vib = Vibrations(mol)
     vib.clean()
     vib.run()
     viblist = vib.get_frequencies()
     freqs, zpe = tl.getVibString(viblist, False, False)
     vib.clean()
     os.chdir((self.workingDir))
     return freqs, zpe
Пример #8
0
    def test_vibrations_on_surface(self, testdir):
        atoms = self.n2_on_ag.copy()
        atoms.calc = EMT()
        vibs = Vibrations(atoms, indices=[-2, -1])
        vibs.run()

        freqs = vibs.get_frequencies()

        vib_data = vibs.get_vibrations()
        assert_array_almost_equal(freqs, vib_data.get_frequencies())
Пример #9
0
def test_gs_minimum():
    """Test ground state minimum distance, energy and
    vibrational frequency"""
    atoms = H2Morse()
    assert atoms.get_distance(0, 1) == pytest.approx(Re[0], 1.e-12)
    assert atoms.get_potential_energy() == -De[0]
    # check ground state vibrations
    vib = Vibrations(atoms)
    vib.run()
    assert (vib.get_frequencies().real[-1] == pytest.approx(ome[0], 1e-2))
Пример #10
0
def VibScript():
    from ase.vibrations import Vibrations
    import glob, json, cPickle, ase, os

    #######################
    print "Initializing..."
    #----------------------

    params, atoms = initialize(
    )  # Remove old .out/.err files, load from fw_spec, and write 'init.traj'

    prev = glob.glob(
        '*.pckl')  #delete incomplete pckls - facilitating restarted jobs

    if rank() == 0:
        for p in prev:
            if os.stat(p).st_size < 100: os.remove(p)

    atoms.set_calculator(makeCalc(params))
    vib = Vibrations(atoms,
                     delta=params['delta'],
                     indices=json.loads(params['vibids_json']))

    vib.run()
    vib.write_jmol()

    ##########################
    print "Storing Results..."
    #-------------------------

    vib.summary(log='vibrations.txt')

    with open('vibrations.txt', 'r') as f:
        vibsummary = f.read()

    ase.io.write('final.traj', atoms)
    optAtoms = ase.io.read('final.traj')

    vib_energies, vib_frequencies = vib.get_energies(), vib.get_frequencies()

    resultDict = mergeDicts([
        params,
        trajDetails(optAtoms), {
            'vibfreqs_pckl': cPickle.dumps(vib_frequencies),
            'vibsummary': vibsummary,
            'vibengs_pckl': cPickle.dumps(vib_energies)
        }
    ])

    with open('result.json', 'w') as outfile:
        outfile.write(json.dumps(resultDict))
    with open('result.json', 'r') as outfile:
        json.loads(outfile.read())  #test that dictionary isn't 'corrupted'
    if rank() == 0: log(params, optAtoms)
    return 0
Пример #11
0
 def get_modes(self,atm,freqname="vib."):
     for f in [f for f in os.listdir(".") if freqname in f and  '.pckl' in f]:
         os.remove(f)
     new_target = open(os.devnull, "w")
     old_target, sys.stdout = sys.stdout, new_target
     atm.set_calculator(ANIENS(self.ens))
     vib = Vibrations(atm, nfree=2, name=freqname)
     vib.run()
     freq = vib.get_frequencies()
     modes = np.stack(vib.get_mode(i) for i in range(freq.size))
     vib.clean()
     sys.stdout = old_target
     return modes
Пример #12
0
    def __init__(self, atoms, vibname, minfreq=None, maxfreq=None):
        """Input is a atoms object and the corresponding vibrations. 
        With minfreq and maxfreq frequencies can    
        be excluded from the calculation"""

        self.atoms = atoms
        # V = a * v is the combined atom and xyz-index
        self.mm05_V = np.repeat(1.0 / np.sqrt(atoms.get_masses()), 3)
        self.minfreq = minfreq
        self.maxfreq = maxfreq
        self.shape = (len(self.atoms), 3)

        vib = Vibrations(atoms, name=vibname)
        self.energies = np.real(vib.get_energies(method="frederiksen"))  # [eV]
        self.frequencies = np.real(vib.get_frequencies(method="frederiksen"))  # [cm^-1]
        self.modes = vib.modes
        self.H = vib.H
Пример #13
0
    def __init__(self, atoms, vibname, minfreq=-np.inf, maxfreq=np.inf):
        """Input is a atoms object and the corresponding vibrations.
        With minfreq and maxfreq frequencies can
        be excluded from the calculation"""

        self.atoms = atoms
        # V = a * v is the combined atom and xyz-index
        self.mm05_V = np.repeat(1. / np.sqrt(atoms.get_masses()), 3)
        self.minfreq = minfreq
        self.maxfreq = maxfreq
        self.shape = (len(self.atoms), 3)

        vib = Vibrations(atoms, name=vibname)
        self.energies = np.real(vib.get_energies(method='frederiksen'))  # [eV]
        self.frequencies = np.real(
            vib.get_frequencies(method='frederiksen'))  # [cm^-1]
        self.modes = vib.modes
        self.H = vib.H
Пример #14
0
	def run_task(self,fw_spec): 
		"""ONLY WORKS FOR QUANTUM ESPRESSO"""

		from ase.vibrations       import Vibrations

		jobID	= fw_spec['jobID']
		job 	= db2object(jobID)
		t0 		= time.time()
		atoms 	= job.atoms()
		
		atoms.set_calculator(job.vibCalc())

		vib = Vibrations(atoms,delta=job.delta(),indicies=job.vibids)

		vib.run()
		vib.summary(log='vibrations.txt')
		vib.write_jmol()

		vibs 	= vib.get_frequencies()
		t 		= (time.time()-t0)/60.0 #min
	
		return FWAction(stored_data= {'vibs':vibs,'avgtime':t},mod_spec=[{'_push': {'vibs':vibs,'time':t}}])
Пример #15
0
    def test_vibrations_on_surface(self, testdir):
        atoms = self.n2_on_ag.copy()
        atoms.calc = EMT()
        vibs = Vibrations(atoms, indices=[-2, -1])
        vibs.run()

        freqs = vibs.get_frequencies()
        assert len(freqs) == 6

        vib_data = vibs.get_vibrations()
        assert_array_almost_equal(freqs, vib_data.get_frequencies())

        # These should blow up if the vectors don't match number of atoms
        vibs.summary()
        vibs.write_jmol()

        for i in range(6):
            # Frozen atoms should have zero displacement
            assert_array_almost_equal(vibs.get_mode(i)[0], [0., 0., 0.])

            # At least one of the N atoms should have finite displacement
            # (It's a strange test system, the N aren't interacting.)

            assert np.any(vibs.get_mode(i)[-2:, :])
Пример #16
0
	def run_task(self,fw_spec): 
		"""ONLY WORKS FOR QUANTUM ESPRESSO"""
		from ase.vibrations       import Vibrations
		job,params,atoms = initialize(fw_spec)
		
		prev = g.glob('*.pckl') #delete incomplete pckls - facilitating restarted jobs
		for p in prev:
			if os.stat(p).st_size < 100: os.remove(p)
		
		atoms.set_calculator(job.vibCalc())
		vib = Vibrations(atoms,delta=job.delta(),indices=job.vibids())


		vib.run(); vib.write_jmol()
		vib.summary(log='vibrations.txt')
		with open('vibrations.txt','r') as f: vibsummary = f.read()

		vib_energies,vib_frequencies = vib.get_energies(),vib.get_frequencies()
		resultDict 	= misc.mergeDicts([params,	{'vibfreqs_pckl': pickle.dumps(vib_frequencies)
												,'vibsummary':vibsummary
												,'vibengs_pckl':pickle.dumps(vib_energies)}])

		with open('result.json', 'w') as outfile: json.dumps(resultDict, outfile)
		return fireworks.core.firework.FWAction(stored_data=resultDict)
Пример #17
0
 def characteriseMinInternal(self, mol):
     os.chdir((self.workingDir + '/' + '/Raw/' + self.procNum))
     if (self.lowMeth == 'nwchem'):
         mol = tl.setCalc(mol, self.lowString, 'nwchem2', self.lowLev)
         self.Reac.get_forces()
     else:
         mol = tl.setCalc(mol, self.lowString, self.lowMeth, self.lowLev)
     min = BFGS(mol)
     min.run(fmax=0.05, steps=50)
     vib = Vibrations(mol)
     vib.clean()
     vib.run()
     viblist = vib.get_frequencies()
     Freqs, zpe = tl.getVibString(viblist, False, False)
     vib.clean()
     os.chdir((self.workingDir))
     # Finally get single point energy
     mol = tl.setCalc(mol, self.singleString, self.singleMeth,
                      self.singleLev)
     print("Getting single point energy for TS = " +
           str(mol.get_potential_energy()) + "zpe = " + str(zpe) +
           "reactant energy = " + str(self.reactantEnergy))
     energy = mol.get_potential_energy() + zpe
     return Freqs, energy, mol
Пример #18
0
Файл: vib.py Проект: btodac/ase
from __future__ import print_function
from ase import Atoms
from ase.calculators.emt import EMT
from ase.optimize import QuasiNewton
from ase.vibrations import Vibrations
from ase.thermochemistry import IdealGasThermo

n2 = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
QuasiNewton(n2).run(fmax=0.01)
vib = Vibrations(n2)
vib.run()
freqs = vib.get_frequencies()
print(freqs)
vib.summary()
print(vib.get_mode(-1))
vib.write_mode(n=None, nimages=20)
vib_energies = vib.get_energies()

for image in vib.iterimages():
    assert len(image) == 2

thermo = IdealGasThermo(vib_energies=vib_energies,
                        geometry='linear',
                        atoms=n2,
                        symmetrynumber=2,
                        spin=0)
thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)

assert vib.clean(empty_files=True) == 0
assert vib.clean() == 13
assert len(list(vib.iterimages())) == 13
Пример #19
0
def calculate(element, ref_data, p):
    values_dict = {}
    values_dict[p['xc']] = {}
    for XY, data in ref_data[p['xc']].items():
        X = XY.split('-')[0]
        Y = XY.split('-')[1]
        if (X == Y and X == element) or (X != Y and (X == element or Y == element)):
            # compound contains the requested element
            re_ref = data['re']
            we_ref = data['we']
            m0_ref = data.get('m0', 0.0)
            #
            compound = Atoms(X+Y,
                             [
                (0,       0,     0.5  ),
                (0,       0,     0.5+re_ref/a),
                ],
                             pbc=0)
            compound.set_cell([a, b, c], scale_atoms=1)
            compound.center()

            # calculation on the reference geometry
            calc = Calculator(**p)
            compound.set_calculator(calc)
            e_compound = compound.get_potential_energy()
            finegd = calc.density.finegd
            dip = finegd.calculate_dipole_moment(calc.density.rhot_g)*calc.a0
            vib = Vibrations(compound)
            vib.run()
            vib_compound = vib.get_frequencies(method='frederiksen').real[-1]
            world.barrier()
            vib_pckl = glob('vib.*.pckl')
            if rank == 0:
                for file in vib_pckl: remove(file)

            # calculation on the relaxed geometry
            qn = QuasiNewton(compound)
            #qn.attach(PickleTrajectory('compound.traj', 'w', compound).write)
            qn.run(fmax=0.05)
            e_compound_r = compound.get_potential_energy()
            dist_compound_r = compound.get_distance(0,1)
            dip_r = finegd.calculate_dipole_moment(calc.density.rhot_g)*calc.a0
            vib = Vibrations(compound)
            vib.run()
            vib_compound_r = vib.get_frequencies(method='frederiksen').real[-1]
            world.barrier()
            vib_pckl = glob('vib.*.pckl')
            if rank == 0:
                for file in vib_pckl: remove(file)

            del compound
            e = e_compound
            we = vib_compound
            m0 = dip
            e_r = e_compound_r
            we_r = vib_compound_r
            re_r = dist_compound_r
            m0_r = dip_r
            #
            values_dict[p['xc']][XY] = {'re': re_r, 'we': (we_r, we), 'm0': (m0_r, m0)}
    #
    return values_dict
               maxiter=777,
               convergence={'lshift': 0.0},
               basis=basis,
               basispar='spherical',
               direct='noio',
               raw='set int:txs:limxmem 134217728\nmemory total 8000 Mb noverify\n',
               label=label)
 atoms.set_calculator(calc)
 t = time.time()
 if len(atoms) > 1:
     # need a copy of atoms for calculation of vibrations
     vibatoms = atoms.copy()
     vibatoms.set_calculator(calc)
     vib = Vibrations(vibatoms, name=label + '_fixed')
     vib.run()
     f = vib.get_frequencies()[-1].real
     # clean nwchem restart
     if os.path.exists(name + '_' + code + '.db'):
         os.remove(name + '_' + code + '.db')
     atoms.get_potential_energy()
     c.write(atoms, name=name, relaxed=False, basis=basis,
             frequency=f,
             time=time.time()-t)
 else:
     atoms.get_potential_energy()
     c.write(atoms, name=name, relaxed=False, basis=basis,
             time=time.time()-t)
 if len(atoms) > 1:
     opt = BFGS(atoms,
                logfile=name + '_' + code + '.log',
                trajectory=name + '_' + code + '.traj')
Пример #21
0
                Analysis_CalculateForces = 'Yes')

# Mixing calculators
    QMMMcalc =  ase.calculators.mixing.SumCalculator([DFTBcalc,SchNetcalc], atoms)

    atoms.set_calculator(QMMMcalc)

# Optmizing geometry
    qn = BFGS(atoms, trajectory='mol.traj')
    qn.run(fmax=0.0001)
    write('final.xyz', atoms)

# Computing vibrational modes
    vib = Vibrations(atoms, delta=0.01,nfree=4)
    vib.run()
    vib.summary()
    vb_ev = vib.get_energies()
    vb_cm = vib.get_frequencies()
    ENE = float(atoms.get_total_energy())

    o1 = open('info-modes.dat', 'w')
    o1.write("# Potential energy:   " + "{: >24}".format(ENE) + "\n")
    for i in range(0, len(vb_ev)):
      o1.write("{: >24}".format(vb_ev.real[i]) + "{: >24}".format(vb_ev.imag[i]) + "{: >24}".format(vb_cm.real[i]) + "{: >24}".format(vb_cm.imag[i]) + "\n")

    vib.write_jmol()

    o1.close()
    chdir(odir)

Пример #22
0
    # Relax structure
    dyn = BFGS(atoms, trajectory=f'traj/Al{N}.traj')
    dyn.run(fmax=0.05)
    # Get vibrational spectrum
    str1 = f'--------        N={N}'
    str2 = '        ---------'
    print(str1 + str2.ljust(40 - len(str1)))

    ##### Using Vibrations module
    v = Vibrations(atoms, name=f'./vibs/vib_{N}')
    if not p.isfile(f'./vibs/vib_{N}.all.pckl'):
        print('Running vibration calculation')
        v.run()
        v.combine()  # Combine pickle files
    # Get frequencies and DOS - i.e # of states per frequency
    all_freq = v.get_frequencies()
    # if N==38:
    #     print(v.summary())
    #     print(all_freq)
    (freq, counts) = np.unique(all_freq, return_counts=True)
    fold_freq = v.fold(np.real(freq),
                       np.real(counts),
                       start=0,
                       end=np.real(freq.max()),
                       width=12,
                       normalize=False)
    f_freq = np.array(fold_freq[0])
    f_dos = np.array(fold_freq[1])
    freq = np.array(freq)
    dos = np.array(counts)
Пример #23
0
def calculate(element, ref_data, p):
    values_dict = {}
    values_dict[p['xc']] = {}
    for XY, data in ref_data[p['xc']].items():
        X = XY.split('-')[0]
        Y = XY.split('-')[1]
        if (X == Y and X == element) or (X != Y and
                                         (X == element or Y == element)):
            # compound contains the requested element
            re_ref = data['re']
            we_ref = data['we']
            m0_ref = data.get('m0', 0.0)
            #
            compound = Atoms(X + Y, [
                (0, 0, 0.5),
                (0, 0, 0.5 + re_ref / a),
            ],
                             pbc=0)
            compound.set_cell([a, b, c], scale_atoms=1)
            compound.center()

            # calculation on the reference geometry
            calc = Calculator(**p)
            compound.set_calculator(calc)
            e_compound = compound.get_potential_energy()
            finegd = calc.density.finegd
            dip = finegd.calculate_dipole_moment(calc.density.rhot_g) * calc.a0
            vib = Vibrations(compound)
            vib.run()
            vib_compound = vib.get_frequencies(method='frederiksen').real[-1]
            world.barrier()
            vib_pckl = glob('vib.*.pckl')
            if rank == 0:
                for file in vib_pckl:
                    remove(file)

            # calculation on the relaxed geometry
            qn = QuasiNewton(compound)
            #qn.attach(PickleTrajectory('compound.traj', 'w', compound).write)
            qn.run(fmax=0.05)
            e_compound_r = compound.get_potential_energy()
            dist_compound_r = compound.get_distance(0, 1)
            dip_r = finegd.calculate_dipole_moment(
                calc.density.rhot_g) * calc.a0
            vib = Vibrations(compound)
            vib.run()
            vib_compound_r = vib.get_frequencies(method='frederiksen').real[-1]
            world.barrier()
            vib_pckl = glob('vib.*.pckl')
            if rank == 0:
                for file in vib_pckl:
                    remove(file)

            del compound
            e = e_compound
            we = vib_compound
            m0 = dip
            e_r = e_compound_r
            we_r = vib_compound_r
            re_r = dist_compound_r
            m0_r = dip_r
            #
            values_dict[p['xc']][XY] = {
                're': re_r,
                'we': (we_r, we),
                'm0': (m0_r, m0)
            }
    #
    return values_dict
Пример #24
0
    def test_vibrations(self, testdir, n2_emt, n2_optimized):
        atoms = n2_emt
        vib = Vibrations(atoms)
        vib.run()
        freqs = vib.get_frequencies()
        vib.write_mode(n=None, nimages=5)
        vib.write_jmol()
        vib_energies = vib.get_energies()

        for image in vib.iterimages():
            assert len(image) == 2

        thermo = IdealGasThermo(vib_energies=vib_energies,
                                geometry='linear',
                                atoms=atoms,
                                symmetrynumber=2,
                                spin=0)
        thermo.get_gibbs_energy(temperature=298.15,
                                pressure=2 * 101325.,
                                verbose=False)

        vib.summary(log=self.logfile)
        with open(self.logfile, 'rt') as f:
            log_txt = f.read()
            assert log_txt == vibrations_n2_log

        mode1 = vib.get_mode(-1)
        assert_array_almost_equal(mode1,
                                  [[0., 0., -0.188935], [0., 0., 0.188935]])

        assert_array_almost_equal(
            vib.show_as_force(-1, show=False).get_forces(),
            [[0., 0., -2.26722e-1], [0., 0., 2.26722e-1]])

        for i in range(3):
            assert not os.path.isfile('vib.{}.traj'.format(i))
        mode_traj = ase.io.read('vib.3.traj', index=':')
        assert len(mode_traj) == 5
        assert_array_almost_equal(mode_traj[0].get_all_distances(),
                                  atoms.get_all_distances())
        with pytest.raises(AssertionError):
            assert_array_almost_equal(mode_traj[4].get_all_distances(),
                                      atoms.get_all_distances())

        with open('vib.xyz', 'rt') as f:
            jmol_txt = f.read()
            assert jmol_txt == jmol_txt_ref

        assert vib.clean(empty_files=True) == 0
        assert vib.clean() == 13
        assert len(list(vib.iterimages())) == 13

        d = dict(vib.iterdisplace(inplace=False))

        for name, image in vib.iterdisplace(inplace=True):
            assert d[name] == atoms

        atoms2 = n2_emt
        vib2 = Vibrations(atoms2)
        vib2.run()

        assert_array_almost_equal(freqs, vib.get_frequencies())

        # write/read the data from another working directory
        atoms3 = n2_optimized.copy()  # No calculator needed!

        workdir = os.path.abspath(os.path.curdir)
        try:
            os.mkdir('run_from_here')
            os.chdir('run_from_here')
            vib = Vibrations(atoms3, name=os.path.join(os.pardir, 'vib'))
            assert_array_almost_equal(freqs, vib.get_frequencies())
            assert vib.clean() == 13
        finally:
            os.chdir(workdir)
            if os.path.isdir('run_from_here'):
                os.rmdir('run_from_here')
Пример #25
0
    dw=8000,  # density cutoff
    nbands=-10,  # number of bands
    kpts=(8, 8, 8),  # k points
    xc='rpbe',  # exchange correlation method
    sigma=0.2,  # Fermi temperature
    dipole={'status': False},
    spinpol=False,
    convergence={
        'energy': 0.0005,
        'mixing': 0.1,
        'nmix': 10,
        'maxsteps': 500,
        'diag': 'david'
    },
    outdirprefix='vibdir')

atoms.set_calculator(calc)

vib = Vibrations(atoms, delta=0.04, indices=vib_atoms)
vib.run()
vib.summary(log='vibrations.txt')
vib.write_jmol()

realFreq = [
    x * 0.00012 for x in vib.get_frequencies() if not isinstance(x, complex)
]  #eV

S = HarmonicThermo(realFreq).get_entropy(300)
with open('vibrations.txt', 'a') as f:
    f.write('\nTS at 300K: ' + str(S))
Пример #26
0
from ase import Atoms
from ase.calculators.emt import EMT
from ase.optimize import QuasiNewton
from ase.vibrations import Vibrations
from ase.thermochemistry import IdealGasThermo

n2 = Atoms('N2',
           positions=[(0, 0, 0), (0, 0, 1.1)],
           calculator=EMT())
QuasiNewton(n2).run(fmax=0.01)
vib = Vibrations(n2)
vib.run()
print vib.get_frequencies()
vib.summary()
print vib.get_mode(-1)
vib.write_mode(-1, nimages=20)
vib_energies = vib.get_energies()

thermo = IdealGasThermo(vib_energies=vib_energies, geometry='linear', 
                        atoms=n2, symmetrynumber=2, spin=0)
thermo.get_free_energy(temperature=298.15, pressure=2*101325.)
Пример #27
0
from ase import Atoms
from ase.calculators.emt import EMT
from ase.optimize import QuasiNewton
from ase.vibrations import Vibrations
from ase.thermochemistry import IdealGasThermo

n2 = Atoms('N2',
           positions=[(0, 0, 0), (0, 0, 1.1)],
           calculator=EMT())
QuasiNewton(n2).run(fmax=0.01)
vib = Vibrations(n2)
vib.run()
print(vib.get_frequencies())
vib.summary()
print(vib.get_mode(-1))
vib.write_mode(n=None, nimages=20)
vib_energies = vib.get_energies()

thermo = IdealGasThermo(vib_energies=vib_energies, geometry='linear',
                        atoms=n2, symmetrynumber=2, spin=0)
thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)
Пример #28
0
from __future__ import print_function
from ase import Atoms
from ase.calculators.emt import EMT
from ase.optimize import QuasiNewton
from ase.vibrations import Vibrations
from ase.thermochemistry import IdealGasThermo

n2 = Atoms('N2',
           positions=[(0, 0, 0), (0, 0, 1.1)],
           calculator=EMT())
QuasiNewton(n2).run(fmax=0.01)
vib = Vibrations(n2)
vib.run()
print(vib.get_frequencies())
vib.summary()
print(vib.get_mode(-1))
vib.write_mode(n=None, nimages=20)
vib_energies = vib.get_energies()

for image in vib.iterimages():
    assert len(image) == 2

thermo = IdealGasThermo(vib_energies=vib_energies, geometry='linear',
                        atoms=n2, symmetrynumber=2, spin=0)
thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)

assert vib.clean(empty_files=True) == 0
assert vib.clean() == 13
assert len(list(vib.iterimages())) == 13

d = dict(vib.iterdisplace(inplace=False))
Пример #29
0
from ase import *
from ase.vibrations import Vibrations

n2 = Atoms('N2',
           positions=[(0, 0, 0), (0, 0, 1.1)],
           calculator=EMT())
QuasiNewton(n2).run(fmax=0.01)
vib = Vibrations(n2)
vib.run()
print vib.get_frequencies()
vib.summary()
print vib.get_mode(-1)
vib.write_mode(-1, nimages=20)
Пример #30
0
# Using optimal lattice parameter from task 2
a = 4.043  # A
atoms = bulk('Al', 'fcc', a)
# view(atoms)  # DEBUG

#### Calculate vibrational spectrum
# Attach EAM calculator to atoms
mishin = EAM(potential='../CourseGitRepo/HA5_al_potential.alloy')  # Set up EAM
atoms.set_calculator(mishin)

# Get vibrational spectrum
v = Vibrations(atoms, name='./vibs/vib_bulk')
v.run()
v.summary()
# Get frequencies and DOS - i.e # of states per frequency
(freq, counts) = np.unique(v.get_frequencies(), return_counts=True)
freq = np.array(freq)
dos = np.array(counts)
# Save to db
vibDB.write(atoms, data={'frequency': freq, 'DOS': dos})

#### Calculate band structure
N = 7  # Use a supercell of size 7x7x7
ph = Phonons(atoms,
             mishin,
             name='./phonons/ph_bulk',
             supercell=(N, N, N),
             delta=0.05)
ph.run()
# Read the results from the run and obtain the bandpath and DOS
ph.read(acoustic=True)
# Calc minimized energies
e = geometry.get_potential_energy()
print('Total energy', e, 'eV')

# Get the forces again
print('Forces:')
print(geometry.get_forces())

# Run the vibrational analysis
vib = Vibrations(geometry, nfree=2)
vib.run()
print(vib.summary())
print(vib.get_zero_point_energy())

# Get freqs
f = vib.get_frequencies()

# Print modes + freq
for i in range(0, len(f)):
    print('Mode(' + str(i) + ') Freq: ' + "{:.7e}".format(f[i]))
    print(vib.get_mode(i))
'''
# We will alse need to use these functions to get thermo-chem data
thermo = IdealGasThermo(vib_energies=vib_energies,
                       potentialenergy=potentialenergy,
                       atoms=atoms,
                       geometry='linear',
                       symmetrynumber=2, spin=0)
G = thermo.get_gibbs_energy(temperature=298.15, pressure=101325.)
'''