Пример #1
0
    def test_harmonic_vibrations(self, testdir):
        """Check the numerics with a trivial case: one atom in harmonic well"""
        rng = np.random.RandomState(42)

        k = rng.rand()

        ref_atoms = Atoms('H', positions=np.zeros([1, 3]))
        atoms = ref_atoms.copy()
        mass = atoms.get_masses()[0]

        atoms.calc = ForceConstantCalculator(D=np.eye(3) * k,
                                             ref=ref_atoms,
                                             f0=np.zeros((1, 3)))
        vib = Vibrations(atoms, name='harmonic')
        vib.run()
        vib.read()

        expected_energy = (
            units._hbar  # In J/s
            * np.sqrt(k  # In eV/A^2
                      * units._e  # eV -> J
                      * units.m**2  # A^-2 -> m^-2
                      / mass  # in amu
                      / units._amu  # amu^-1 -> kg^-1
                      )) / units._e  # J/s -> eV/s

        assert np.allclose(vib.get_energies(), expected_energy)
Пример #2
0
def ase_vib(embedder, coords, atomnos, logfunction=None, title='temp'):
    '''
    '''
    atoms = Atoms(atomnos, positions=coords)
    atoms.calc = get_ase_calc(embedder)
    vib = Vibrations(atoms, name=title)

    if os.path.isdir(title):
        os.chdir(title)
        for f in os.listdir():
            os.remove(f)
        os.chdir(os.path.dirname(os.getcwd()))
    else:
        os.mkdir(title)

    os.chdir(title)

    t_start = time.perf_counter()

    with HiddenPrints():
        vib.run()

    # freqs = vib.get_frequencies()
    freqs = vib.get_energies() * 8065.544  # from eV to cm-1

    if logfunction is not None:
        elapsed = time.perf_counter() - t_start
        logfunction(
            f'{title} - frequency calculation completed ({time_to_string(elapsed)})'
        )

    os.chdir(os.path.dirname(os.getcwd()))

    return freqs, np.count_nonzero(freqs.imag > 1e-3)
Пример #3
0
    def get_thermo_correction(
            self,
            coords: simtk.unit.quantity.Quantity) -> unit.quantity.Quantity:
        """
        Returns the thermochemistry correction. This calls: https://wiki.fysik.dtu.dk/ase/ase/thermochemistry/thermochemistry.html
        and uses the Ideal gas rigid rotor harmonic oscillator approximation to calculate the Gibbs free energy correction that
        needs to be added to the single point energy to obtain the Gibb's free energy
        coords: [K][3]

        Raises:
            verror: if imaginary frequencies are detected a ValueError is raised

        Returns:
            float -- temperature correct [kT]
        """
        if not (len(coords.shape) == 3 and coords.shape[2] == 3
                and coords.shape[0] == 1):
            raise RuntimeError(
                f"Something is wrong with the shape of the provided coordinates: {coords.shape}. Only x.shape[0] == 1 is possible."
            )

        ase_mol = copy.deepcopy(self.ase_mol)
        for atom, c in zip(ase_mol, coords[0]):
            atom.x = c[0].value_in_unit(unit.angstrom)
            atom.y = c[1].value_in_unit(unit.angstrom)
            atom.z = c[2].value_in_unit(unit.angstrom)

        calculator = self.model.ase()
        ase_mol.set_calculator(calculator)

        vib = Vibrations(ase_mol, name=f"/tmp/vib{random.randint(1,10000000)}")
        vib.run()
        vib_energies = vib.get_energies()
        thermo = IdealGasThermo(
            vib_energies=vib_energies,
            atoms=ase_mol,
            geometry="nonlinear",
            symmetrynumber=1,
            spin=0,
        )

        try:
            G = thermo.get_gibbs_energy(
                temperature=temperature.value_in_unit(unit.kelvin),
                pressure=pressure.value_in_unit(unit.pascal),
            )
        except ValueError as verror:
            logger.critical(verror)
            vib.clean()
            raise verror
        # removes the vib tmp files
        vib.clean()
        return (
            G * eV_to_kJ_mol
        ) * unit.kilojoule_per_mole  # eV * conversion_factor(eV to kJ/mol)
Пример #4
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
Пример #5
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
Пример #6
0
    def test_consistency_with_vibrationsdata(self, testdir, n2_emt):
        atoms = n2_emt
        vib = Vibrations(atoms)
        vib.run()
        vib_data = vib.get_vibrations()

        assert_array_almost_equal(vib.get_energies(), vib_data.get_energies())

        # Compare the last mode as the others may be re-ordered by negligible
        # energy changes
        assert_array_almost_equal(vib.get_mode(5), vib_data.get_modes()[5])
Пример #7
0
    def test_vibrations_methods(self, testdir, random_dimer):
        vib = Vibrations(random_dimer)
        vib.run()
        vib_energies = vib.get_energies()

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

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

        with open(self.logfile, 'w') as fd:
            vib.summary(log=fd)

        with open(self.logfile, 'rt') as fd:
            log_txt = fd.read()
            assert log_txt == '\n'.join(
                VibrationsData._tabulate_from_energies(vib_energies)) + '\n'

        last_mode = vib.get_mode(-1)
        scale = 0.5
        assert_array_almost_equal(
            vib.show_as_force(-1, scale=scale, show=False).get_forces(),
            last_mode * 3 * len(vib.atoms) * scale)

        vib.write_mode(n=3, nimages=5)
        for i in range(3):
            assert not Path('vib.{}.traj'.format(i)).is_file()
        mode_traj = ase.io.read('vib.3.traj', index=':')
        assert len(mode_traj) == 5

        assert_array_almost_equal(mode_traj[0].get_all_distances(),
                                  random_dimer.get_all_distances())
        with pytest.raises(AssertionError):
            assert_array_almost_equal(mode_traj[4].get_all_distances(),
                                      random_dimer.get_all_distances())

        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] == random_dimer
def test_ideal_gas_thermo():
    atoms = Atoms('N2',
                  positions=[(0, 0, 0), (0, 0, 1.1)])
    atoms.calc = EMT()
    QuasiNewton(atoms).run(fmax=0.01)
    energy = atoms.get_potential_energy()
    vib = Vibrations(atoms, name='idealgasthermo-vib')
    vib.run()
    vib_energies = vib.get_energies()

    thermo = IdealGasThermo(vib_energies=vib_energies, geometry='linear',
                            atoms=atoms, symmetrynumber=2, spin=0,
                            potentialenergy=energy)
    thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)
Пример #9
0
    def test_consistency_with_vibrationsdata(self, testdir, random_dimer):
        vib = Vibrations(random_dimer, delta=1e-6, nfree=4)
        vib.run()
        vib_data = vib.get_vibrations()

        assert_array_almost_equal(vib.get_energies(), vib_data.get_energies())

        for mode_index in range(3 * len(vib.atoms)):
            assert_array_almost_equal(vib.get_mode(mode_index),
                                      vib_data.get_modes()[mode_index])

        # Hessian should be close to the ForceConstantCalculator input
        assert_array_almost_equal(random_dimer.calc.D,
                                  vib_data.get_hessian_2d(),
                                  decimal=6)
Пример #10
0
 def vib_zpe(self, job, atoms):
     from ase.vibrations import Vibrations
     self.log('-' * 60)
     self.log('Run ZEP calculation: {0}'.format(job))
     label = os.path.join(self.label, job)
     label = os.path.join(label, 'vib')
     # copy file
     calculator = deepcopy(self.calculator)
     dip = dipole_correction(atoms, edir=3)
     calculator.update(dip)
     calculator.update({
         'calculation': 'scf',
         'tstress': True,
         'tprnfor': True,
         'outdir': '../',
         'prefix': '%s' % job,
         'startingpot': 'file',
         'startingwfc': 'file',
         'etot_conv_thr': 1e-6,
         'disk_io': 'none',
     })
     # better to restart from previous geo_relax calculation
     calc = Espresso(
         label=label,
         **calculator,
     )
     atoms.calc = calc
     if job[-1] == 'O':
         indices = [-1]
     elif job[-2:] == 'OH' and job[-3:] != 'OOH':
         indices = [-1, -2]
     elif job[-3:] == 'OOH':
         indices = [-1, -2, -3]
     elif job[-2:] == 'O2':
         indices = [-1, -2]
     else:
         indices = []
         # print('%!!!')
         return job, 0
     vib = Vibrations(atoms, name=os.path.join(label, job), indices=indices)
     vib.run()
     vib_energies = np.real(vib.get_energies())
     zpe = 0.
     for energy in vib_energies:
         zpe += 0.5 * energy
     self.zpes[job] = zpe
     return job, zpe
Пример #11
0
def test_harmonic_thermo():
    atoms = fcc100('Cu', (2, 2, 2), vacuum=10.)
    atoms.calc = EMT()
    add_adsorbate(atoms, 'Pt', 1.5, 'hollow')
    atoms.set_constraint(FixAtoms(indices=[atom.index for atom in atoms
                                           if atom.symbol == 'Cu']))
    QuasiNewton(atoms).run(fmax=0.01)
    vib = Vibrations(atoms, name='harmonicthermo-vib',
                     indices=[atom.index for atom in atoms
                              if atom.symbol != 'Cu'])
    vib.run()
    vib.summary()
    vib_energies = vib.get_energies()

    thermo = HarmonicThermo(vib_energies=vib_energies,
                            potentialenergy=atoms.get_potential_energy())
    thermo.get_helmholtz_energy(temperature=298.15)
Пример #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 test_co_vibespresso_vibrations(tmpdir):

    tmpdir.chdir()

    co = Atoms('CO', positions=[[1.19382389081, 0.0, 0.0], [0.0, 0.0, 0.0]])
    co.set_cell(np.ones(3) * 12.0 * Bohr)

    calc = Vibespresso(pw=34.0 * Rydberg,
                       dw=144.0 * Rydberg,
                       kpts='gamma',
                       xc='PBE',
                       calculation='scf',
                       ion_dynamics='None',
                       spinpol=False,
                       outdir='vibs')

    co.set_calculator(calc)

    # calculate the vibrations
    vib = Vibrations(co, indices=range(len(co)), delta=0.01, nfree=2)
    vib.run()

    assert np.allclose(vib.get_energies(), REF_ENE)
Пример #15
0
    def get_zpe_energy(self, path_to_vib_species):
        zpe_energy_dict = {}
        atoms = read(path_to_vib_species)
        vib_path = os.path.dirname(path_to_vib_species)
        os.chdir(vib_path)

        prefix, species = os.path.basename(path_to_vib_species).split(
            '.')[0].split('_')
        indices = [
            atom.index for atom in atoms
            if atom.position[2] > atoms.cell[2, 2] / 2.
        ]
        vib = Vibrations(atoms, indices=indices)
        vib_energies = vib.get_energies()
        key = prefix + '_' + species
        try:
            thermo = IdealGasThermo(vib_energies, atoms)
            zpe_energy = thermo.get_ZPE_correction()
            zpe_energy_dict[key] = zpe_energy

        except ValueError:
            pass
        return zpe_energy_dict
Пример #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
		            'nmix':10,
                'maxsteps': maxsteps,
                'diag': 'david'},
              #mode = 'scf',
              output = {'avoidio':False,
                        'removewf':True,
                        'wf_collect':False},
	             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()

#dyn = QuasiNewton(atoms, logfile='qn.log', trajectory='qn.traj')
#dyn.run(fmax=0.05)

energy = atoms.get_potential_energy()

vibs = vib.get_energies()

with open('vibrations.txt','r') as f: ZPE = f.readlines()[-1]
gibbs   = HarmonicThermo(vib_energies=vibs)
entropy = gibbs.get_entropy(temperature)

with open('converged.log', 'w') as f: f.write("Energy: %f eV\nEntropy: %f eV/K \n%s"%(energy,entropy,ZPE))

Пример #18
0
atoms.write("out.traj")

# | - TEMP *********************************************************************

from ase.vibrations import Vibrations
from ase_modules.ase_methods import thermochem_IG_corr

vib = Vibrations(
    atoms,
    indices=None,
)

vib.run()

# print("an_ads_vib | Getting vibrational energies")
vib_e_list = vib.get_energies()

vib.summary(log="vib_summ.out")

thermochem_IG_corr(
    vib_e_list,
    Temperature=300.0,
    Pressure=100000.0,
    potentialenergy=0.,
    symmetrynumber=2,
    spin=1,
    atoms=atoms,
    linear=True,
)

# # H2O, H2, O2: 2,
def test_thermochemistry():
    """Tests of the major methods (HarmonicThermo, IdealGasThermo,
    CrystalThermo) from the thermochemistry module."""

    # Ideal gas thermo.
    atoms = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
    QuasiNewton(atoms).run(fmax=0.01)
    energy = atoms.get_potential_energy()
    vib = Vibrations(atoms, name='idealgasthermo-vib')
    vib.run()
    vib_energies = vib.get_energies()

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

    # Harmonic thermo.

    atoms = fcc100('Cu', (2, 2, 2), vacuum=10.)
    atoms.set_calculator(EMT())
    add_adsorbate(atoms, 'Pt', 1.5, 'hollow')
    atoms.set_constraint(
        FixAtoms(indices=[atom.index for atom in atoms
                          if atom.symbol == 'Cu']))
    QuasiNewton(atoms).run(fmax=0.01)
    vib = Vibrations(
        atoms,
        name='harmonicthermo-vib',
        indices=[atom.index for atom in atoms if atom.symbol != 'Cu'])
    vib.run()
    vib.summary()
    vib_energies = vib.get_energies()

    thermo = HarmonicThermo(vib_energies=vib_energies,
                            potentialenergy=atoms.get_potential_energy())
    thermo.get_helmholtz_energy(temperature=298.15)

    # Crystal thermo.
    atoms = bulk('Al', 'fcc', a=4.05)
    calc = EMT()
    atoms.set_calculator(calc)
    energy = atoms.get_potential_energy()

    # Phonon calculator
    N = 7
    ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
    ph.run()

    ph.read(acoustic=True)
    phonon_energies, phonon_DOS = ph.dos(kpts=(4, 4, 4), npts=30, delta=5e-4)

    thermo = CrystalThermo(phonon_energies=phonon_energies,
                           phonon_DOS=phonon_DOS,
                           potentialenergy=energy,
                           formula_units=4)
    thermo.get_helmholtz_energy(temperature=298.15)

    # Hindered translator / rotor.
    # (Taken directly from the example given in the documentation.)

    vibs = np.array([
        3049.060670, 3040.796863, 3001.661338, 2997.961647, 2866.153162,
        2750.855460, 1436.792655, 1431.413595, 1415.952186, 1395.726300,
        1358.412432, 1335.922737, 1167.009954, 1142.126116, 1013.918680,
        803.400098, 783.026031, 310.448278, 136.112935, 112.939853, 103.926392,
        77.262869, 60.278004, 25.825447
    ])
    vib_energies = vibs / 8065.54429  # Convert to eV from cm^-1.
    trans_barrier_energy = 0.049313  # eV
    rot_barrier_energy = 0.017675  # eV
    sitedensity = 1.5e15  # cm^-2
    rotationalminima = 6
    symmetrynumber = 1
    mass = 30.07  # amu
    inertia = 73.149  # amu Ang^-2

    thermo = HinderedThermo(vib_energies=vib_energies,
                            trans_barrier_energy=trans_barrier_energy,
                            rot_barrier_energy=rot_barrier_energy,
                            sitedensity=sitedensity,
                            rotationalminima=rotationalminima,
                            symmetrynumber=symmetrynumber,
                            mass=mass,
                            inertia=inertia)

    helmholtz = thermo.get_helmholtz_energy(temperature=298.15)
    target = 1.593  # Taken from documentation example.
    assert (helmholtz - target) < 0.001
Пример #20
0
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))

for name, atoms in vib.iterdisplace(inplace=True):
Пример #21
0
                dw = 5000.,
                nbands = -10,
            kpts=(1, 1, 1), 
            xc = 'BEEF', 
            outdir='outdir',
            psppath = "/scratch/users/colinfd/psp/gbrv",
            sigma = 10e-4)

atoms.set_calculator(calc)

dyn = QuasiNewton(atoms,logfile='out.log',trajectory='out.traj')
dyn.run(fmax=0.01) 
electronicenergy = atoms.get_potential_energy()

vib = Vibrations(atoms) # run vibrations on all atoms
vib.run()
vib_energies = vib.get_energies()

thermo = IdealGasThermo(vib_energies=vib_energies,
                        electronicenergy=electronicenergy,
                        atoms=atoms,
                        geometry='linear', # linear/nonlinear
                        symmetrynumber=2, spin=0) # symmetry numbers from point group

G = thermo.get_free_energy(temperature=300, pressure=101325.) # vapor pressure of water at room temperature

e = open('e_energy.out','w')
g = open('g_energy.out','w')
e.write(str(electronicenergy))
g.write(str(G))
Пример #22
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)

Пример #23
0
 def get_energies(self, method='standard', direction='central'):
     Vibrations.get_energies(self, method, direction)
     return self.om_v
Пример #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')