Exemple #1
0
def relaxGPAW(structure, label, forcemax=0.1, niter_max=1, steps=10):
    # Set calculator
    calc = get_calculator()
    calc.set(txt=label+'_true.txt')

    # Set calculator 
    structure.set_calculator(calc)
    
    # loop a number of times to capture if minimization stops with high force
    # due to the VariansBreak calls
    niter = 0

    # If the structure is already fully relaxed just return it
    if (structure.get_forces()**2).sum(axis = 1).max()**0.5 < forcemax:
        return structure
    
    traj = Trajectory(label+'_lcao.traj','w', structure)
    while (structure.get_forces()**2).sum(axis = 1).max()**0.5 > forcemax and niter < niter_max:
        dyn = BFGS(structure,
                   logfile=label+'.log')
        vb = VariansBreak(structure, dyn, min_stdev = 0.01, N = 15)
        dyn.attach(traj)
        dyn.attach(vb)
        dyn.run(fmax = forcemax, steps = steps)
        niter += 1

    E = structure.get_potential_energy()
    F = structure.get_forces()

    del calc
    del dyn
    
    return structure, E, F
def test_relax_co_ase_bfgs(tmpdir):

    tmpdir.chdir()

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

    calc = Espresso(pw=24.0 * Rydberg,
                    dw=144.0 * Rydberg,
                    kpts='gamma',
                    xc='PBE',
                    calculation='scf',
                    ion_dynamics=None,
                    spinpol=False,
                    outdir='qe_ase_bfgs')

    co.set_calculator(calc)

    minimizer = BFGS(co, logfile='minimizer.log', trajectory='relaxed.traj')
    minimizer.run(fmax=0.01)

    print('ase(scf) bfgs:')
    print('energy: ', co.get_potential_energy())
    print('positions: ', co.positions)
    print('forces: ', co.get_forces())
Exemple #3
0
def test_emt1():
    from ase import Atoms
    from ase.calculators.emt import EMT
    from ase.constraints import FixBondLength
    from ase.io import Trajectory
    from ase.optimize import BFGS

    a = 3.6
    b = a / 2
    cu = Atoms('Cu2Ag',
               positions=[(0, 0, 0), (b, b, 0), (a, a, b)],
               calculator=EMT())
    e0 = cu.get_potential_energy()
    print(e0)

    d0 = cu.get_distance(0, 1)
    cu.set_constraint(FixBondLength(0, 1))
    t = Trajectory('cu2ag.traj', 'w', cu)
    qn = BFGS(cu)
    qn.attach(t.write)

    def f():
        print(cu.get_distance(0, 1))

    qn.attach(f)
    qn.run(fmax=0.001)
    assert abs(cu.get_distance(0, 1) - d0) < 1e-14
Exemple #4
0
def test_stress(atoms):
    cell0 = atoms.get_cell()

    atoms.set_cell(np.dot(
        atoms.cell, [[1.02, 0, 0.03], [0, 0.99, -0.02], [0.1, -0.01, 1.03]]),
                   scale_atoms=True)

    atoms *= (1, 2, 3)
    cell0 *= np.array([1, 2, 3])[:, np.newaxis]

    atoms.rattle()

    # Verify analytical stress tensor against numerical value
    s_analytical = atoms.get_stress()
    s_numerical = atoms.calc.calculate_numerical_stress(atoms, 1e-5)
    s_p_err = 100 * (s_numerical - s_analytical) / s_numerical

    print("Analytical stress:\n", s_analytical)
    print("Numerical stress:\n", s_numerical)
    print("Percent error in stress:\n", s_p_err)
    assert np.all(abs(s_p_err) < 1e-5)

    # Minimize unit cell
    opt = BFGS(UnitCellFilter(atoms))
    opt.run(fmax=1e-3)

    # Verify minimized unit cell using Niggli tensors
    g_minimized = np.dot(atoms.cell, atoms.cell.T)
    g_theory = np.dot(cell0, cell0.T)
    g_p_err = 100 * (g_minimized - g_theory) / g_theory

    print("Minimized Niggli tensor:\n", g_minimized)
    print("Theoretical Niggli tensor:\n", g_theory)
    print("Percent error in Niggli tensor:\n", g_p_err)
    assert np.all(abs(g_p_err) < 1)
def test_relax_co_ase_interactive_bfgs(tmpdir):

    tmpdir.chdir()

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

    calc = iEspresso(pw=24.0 * Rydberg,
                     dw=144.0 * Rydberg,
                     kpts='gamma',
                     xc='PBE',
                     calculation='relax',
                     ion_dynamics='ase3',
                     spinpol=False,
                     outdir='qe_ase_interactive_bfgs')

    co.set_calculator(calc)

    minimizer = BFGS(co, logfile='minimizer.log', trajectory='relaxed.traj')
    minimizer.run(fmax=0.01)

    ref_ene = -616.9017404193379

    ref_pos = np.array([[1.19233393e+00, 0.0e+00, 0.00000000e+00],
                        [1.48996586e-03, 0.00000000e+00, 0.00000000e+00]])

    ref_for = np.array([[0.00162288, 0.0, 0.0],
                        [-0.00162288, 0.0, 0.0]])

    assert np.allclose(co.get_potential_energy(), ref_ene)
    #assert np.allclose(co.positions, ref_pos)
    #assert np.allclose(co.get_forces(), ref_for)

    print(co.positions)
    print(co.get_forces())
def run_server(launchclient=True):
    atoms = getatoms()

    with SocketIOCalculator(log=sys.stdout, port=port,
                            timeout=timeout) as calc:
        if launchclient:
            thread = launch_client_thread()
        atoms.calc = calc
        opt = BFGS(atoms)
        opt.run()

    if launchclient:
        thread.join()

    forces = atoms.get_forces()
    energy = atoms.get_potential_energy()

    atoms.calc = EMT()
    ref_forces = atoms.get_forces()
    ref_energy = atoms.get_potential_energy()

    refatoms = run_normal()
    ref_energy = refatoms.get_potential_energy()
    eerr = abs(energy - ref_energy)
    ferr = np.abs(forces - ref_forces).max()

    perr = np.abs(refatoms.positions - atoms.positions).max()
    print('errs e={} f={} pos={}'.format(eerr, ferr, perr))
    assert eerr < 1e-11, eerr
    assert ferr < 1e-11, ferr
    assert perr < 1e-11, perr
def get_optimal_h(atoms, bottom, top, natoms, dyn = False):
    
    # This find the optimal h - when the top is sliding:
    
    if not dyn:
        from scipy.optimize import fmin
        pos_init    =   atoms.positions.copy()
        
        zmax        =   np.amax(atoms.positions[bottom][:,2])
        
        def get_epot(z):
            
            new_pos     =   pos_init
            for iat in range(len(atoms)):
                if top[iat]:
                    new_pos[iat][2] = z + zmax
            
            atoms.positions =   new_pos
            e   = atoms.get_potential_energy()/natoms
            print z, e
            return e  
        
        hmin    =   fmin(get_epot, 3.34)
        emin    =   get_epot(hmin)
        
        atoms.positions = pos_init
        print 'optimal height= %.2f and e=%.2f' %(hmin, emin) 
        return emin, hmin
    else:
        dyn         =   BFGS(atoms)
        dyn.run(fmax=0.03)
        e           =   atoms.get_potential_energy()/natoms
        layers      =   find_layers(atoms.positions)[0]
        hmin        =   layers[1] - layers[0]
        return e, hmin
Exemple #8
0
    def do_constrained_optimization(self):
        logfile = self.log_prefix + 'relax_' + str(self.a) + '.log'
        trajectory = self.traj_prefix + 'relax_' + str(self.a) + '.traj'

        if self.adaptive_threshold is None:
            dyn = BFGS(self.atoms, logfile=logfile, trajectory=trajectory, maxstep=self.maxstep)
            dyn.run(fmax=self.fmax * self.fixed_conv_ratio)
        else:
            dyn = scan_bfgs(self.atoms, logfile=logfile, trajectory=trajectory, maxstep=self.maxstep)
            dyn.pass_constraint(self.scanned_constraint, totfmax=self.fmax)
            dyn.run(fmax=self.adaptive_threshold)

        pg = self.scanned_constraint.projected_force

        self.atoms.set_constraint(self.only_other_constraints)
        e = self.atoms.get_potential_energy()
        f = self.atoms.get_forces()
        fi_max = max([np.linalg.norm(f_1 + f_2) for f_1, f_2 in zip(f, self.scanned_constraint.projected_forces)])
        self.atoms.set_constraint(self.constraintlist)

        if self.a not in self.dopt:
            self.dopt[self.a] = {}
        self.dopt[self.a][fi_max] = {}
        self.dopt[self.a][fi_max]['pf'] = pg
        self.dopt[self.a][fi_max]['e'] = e
        self.dopt[self.a][fi_max]['xyz'] = self.atoms.get_positions()
        self.dopt[self.a][fi_max]['na_step'] = self.na_step
        self.write_restart()

        return e, pg, fi_max, f
Exemple #9
0
    def scan_dihed_qforce(self,
                          all_config,
                          frag,
                          scan_dir,
                          mol,
                          n_run,
                          nsteps=1000):
        md_energies = []

        for i, coord in enumerate(frag.coords):
            restraints = self.find_restraints(frag, frag.qm_coords[i], n_run)
            atom = Atoms(frag.elements,
                         positions=coord,
                         calculator=QForce(frag.terms,
                                           dihedral_restraints=restraints))

            traj_name = f'{scan_dir}/{frag.id}_run{n_run+1}_{i:02d}.traj'
            log_name = f'{scan_dir}/opt_{frag.id}_run{n_run+1}.log'
            e_minimiz = BFGS(atom, trajectory=traj_name, logfile=log_name)
            e_minimiz.run(fmax=0.01, steps=nsteps)
            coords = atom.get_positions()
            self.calc_fit_angles(frag, coords)
            md_energies.append(atom.get_potential_energy())
            frag.coords[i] = coords
        return np.array(md_energies)
Exemple #10
0
 def optimize(self):
     self.calc = EMT()
     dyn = BFGS(self)
     dyn.run(fmax=0.05)
     self.optimized = ZMatrix()
     for _atom in dyn.atoms:
         self.optimized += _atom
def test_dftb_relax_dimer():
    import os
    from ase import Atoms
    from ase.test import require
    from ase.test.testsuite import datafiles_directory
    from ase.calculators.dftb import Dftb
    from ase.optimize import BFGS

    require('dftb')

    os.environ['DFTB_PREFIX'] = datafiles_directory

    calc = Dftb(
        label='dftb',
        Hamiltonian_SCC='No',
        Hamiltonian_PolynomialRepulsive='SetForAll {Yes}',
    )

    atoms = Atoms('Si2',
                  positions=[[5., 5., 5.], [7., 5., 5.]],
                  cell=[12.] * 3,
                  pbc=False)
    atoms.set_calculator(calc)

    dyn = BFGS(atoms, logfile='-')
    dyn.run(fmax=0.1)

    e = atoms.get_potential_energy()
    assert abs(e - -64.830901) < 1., e
Exemple #12
0
def get_energies(autotst_object):

    if isinstance(autotst_object, autotst.molecule.AutoTST_Molecule):
        ase_object = autotst_object.ase_molecule
        labels = []

    if isinstance(autotst_object, autotst.reaction.AutoTST_Reaction):
        ase_object = autotst_object.ts.ase_ts

        labels = []
        for atom in autotst_object.ts.rmg_ts.getLabeledAtoms().values():
            labels.append(atom.sortingLabel)

    if isinstance(autotst_object, autotst.reaction.AutoTST_TS):
        ase_object = autotst_object.ase_ts

        labels = []
        for atom in autotst_object.ts.rmg_ts.getLabeledAtoms().values():
            labels.append(atom.sortingLabel)

    constrained_energy = ase_object.get_potential_energy()

    ase_copy = ase_object.copy()
    ase_copy.set_calculator(ase_object.get_calculator())

    ase_copy.set_constraint(
        FixBondLengths(list(itertools.combinations(labels, 2))))

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

    relaxed_energy = ase_copy.get_potential_energy()

    return constrained_energy, relaxed_energy, ase_copy
Exemple #13
0
def create_lst_images(freactant, fproduct, nimages=11, mic=False):
    """create images with original LST algorithm without NEB force projection as in IDPP

    Parameters
    ----------
    freactant : path to initial atoms
    fproduct  : path to final atoms
    nimages   : the number of images to be interpolated including two endpoints
    mic       : apply mic or not (PBC)
    """
    from ase.neb import IDPP
    from ase.optimize import BFGS
    from ase.build import minimize_rotation_and_translation

    # create linearly interpolated images
    images = _create_images(freactant, fproduct, nimages)
    neb = NEB(images, remove_rotation_and_translation=True)
    neb.interpolate()

    # refine images with LST algorithm
    d1 = images[0].get_all_distances(mic=mic)
    d2 = images[-1].get_all_distances(mic=mic)
    d = (d2 - d1) / (nimages - 1)
    for i, image in enumerate(images):
        image.set_calculator(IDPP(d1 + i * d, mic=mic))
        qn = BFGS(image)
        qn.run(fmax=0.1)
    # apply optimal translation and rotation
    for i in range(nimages - 1):
        minimize_rotation_and_translation(images[i], images[i + 1])

    return images
Exemple #14
0
def minimize(
    atomno,
    coord,
    method="GFN2-xTB",
    accuracy=1.0,
    electronic_temperature=300.0,
    max_iterations=250,
    solvent="water",
    cache_api=True,
    constraints=None,
):
    atoms = Atoms(numbers=atomno, positions=coord)
    calc = XTB(
        method=method,
        accuracy=accuracy,
        electronic_temperature=electronic_temperature,
        max_iterations=max_iterations,
        solvent=solvent,
        cache_api=cache_api,
    )
    atoms.set_calculator(calc)

    if constraints is not None:
        for c in constraints:
            atoms.set_constraint(c)

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

    return atoms.numbers, atoms.get_positions()
Exemple #15
0
def test_relax():
    """
    Test that a static relaxation that requires multiple neighbor list
    rebuilds can be carried out successfully.  This is verified by relaxing
    an icosahedral cluster of atoms and checking that the relaxed energy
    matches a known precomputed value for an example model.
    """
    import numpy as np
    from ase.cluster import Icosahedron
    from pytest import importorskip
    importorskip('kimpy')
    from ase.calculators.kim import KIM
    from ase.optimize import BFGS

    energy_ref = -0.5420939378624228  # eV

    # Create structure and calculator
    atoms = Icosahedron("Ar", latticeconstant=3.0, noshells=2)
    calc = KIM("ex_model_Ar_P_Morse_07C")
    atoms.calc = calc

    opt = BFGS(atoms, logfile=None)
    opt.run(fmax=0.05)

    assert np.isclose(atoms.get_potential_energy(), energy_ref)
Exemple #16
0
def push_apart(atoms,
               blmin,
               variable_cell=False,
               maxsteps=500,
               logfile=None,
               trajectory=None):
    """ Push atoms apart so as to (try) satisfy the blmin dictionary
    of minimal interatomic distances while not displacing the
    atoms too much. The default SHPP calculator is used for
    this purpose.

    atoms: an Atoms object
    blmin: dictionary with the minimal interatomic distance
           for each (sorted) pair of atomic numbers
    variable_cell: whether to allow the cell vectors to vary
    maxsteps: maximum number of optimizer steps
    trajectory: (filename of the) trajectory to attach to the optimizer
    logfile: (filename of the) logfile for the optimizer
    """
    if variable_cell:
        blminmax = max([blmin[k] for k in blmin if k[0] == k[1]])
        cell = atoms.get_cell()
        for i in range(3):
            cell[i] *= max(1, blminmax / np.linalg.norm(cell[i]))
        atoms.set_cell(cell, scale_atoms=True)

    calc = SHPP(atoms, blmin)
    atoms.set_calculator(calc)
    dyn = BFGS(atoms, maxstep=0.05, logfile=logfile, trajectory=trajectory)
    dyn.run(fmax=0.05, steps=maxsteps)
    return atoms
def test_au111(wrap):
    zpos = cos(134.3 / 2.0 * pi / 180.0) * 1.197
    xpos = sin(134.3 / 2.0 * pi / 180.0) * 1.19
    co2 = Atoms('COO',
                positions=[(-xpos + 1.2, 0, -zpos), (-xpos + 1.2, -1.1, -zpos),
                           (-xpos + 1.2, 1.1, -zpos)])

    slab = fcc111('Au', size=(2, 2, 4), vacuum=2 * 5, orthogonal=True)
    slab.center()
    add_adsorbate(slab, co2, 1.5, 'bridge')
    slab.set_pbc((True, True, False))
    d0 = co2.get_distance(-3, -2)
    d1 = co2.get_distance(-3, -1)
    d2 = co2.get_distance(-2, -1)

    calc = EMT()
    slab.set_calculator(calc)
    if wrap:
        # Remap into the cell so bond is actually wrapped:
        slab.set_scaled_positions(slab.get_scaled_positions() % 1.0)
    constraint = FixLinearTriatomic(triples=[(-2, -3, -1)])
    slab.set_constraint(constraint)

    dyn = BFGS(slab, trajectory='relax_%d.traj' % wrap)
    dyn.run(fmax=0.05)
    assert abs(slab.get_distance(-3, -2, mic=1) - d0) < 1e-9
    assert abs(slab.get_distance(-3, -1, mic=1) - d1) < 1e-9
    assert abs(slab.get_distance(-2, -1, mic=1) - d2) < 1e-9
Exemple #18
0
def calc(id):
    db = connect(db_name)
    atoms_orig = db.get_atoms(id=id)
    kvp = db.get(id=id).key_value_pairs
    atoms = atoms_orig.copy()

    # Do linear interpolation of the cell size
    a_au = 4.0782
    a_cu = 3.6149

    symbs = atoms.get_chemical_symbols()
    count = {"Au": 0, "Cu": 0}
    for s in symbs:
        count[s] += 1
    c_au = float(count["Au"]) / len(atoms)
    a = a_au * c_au + a_cu * (1.0 - c_au)
    a_orig = 3.9
    cell = atoms.get_cell()
    atoms.set_cell(cell * a / a_orig, scale_atoms=True)
    calc = EMT()
    atoms.set_calculator(calc)
    relaxer = BFGS(atoms)
    relaxer.run(fmax=0.025)
    res = minimize(relax_cell, a, args=(atoms, cell))
    print(res["x"])
    relaxer = BFGS(atoms)
    relaxer.run(fmax=0.025)
    energy = atoms.get_potential_energy()

    del db[id]
    calc = SinglePointCalculator(atoms_orig, energy=energy)
    atoms_orig.set_calculator(calc)
    kvp["converged"] = True
    db.write(atoms_orig, key_value_pairs=kvp)
Exemple #19
0
def run_cp2k(template_file):
    from ase.calculators.cp2k import CP2K, parse_input
    from ase.build import molecule
    from ase.optimize import BFGS

    with open('cp2k_mm_energy.inp', 'r') as f:
        content = f.read()
    calc = CP2K()
    #print("input parameters")
    #print(calc.inp)
    print(calc)
    print("input parameters")
    #print(calc.todict())

    print("parsing input")
    parsed = parse_input(content)
    print(parsed)
    print(parsed.name)
    print(parsed.params)
    print(parsed.keywords)
    print(parsed.subsections)

    exit(0)
    atoms = molecule('H2O', calculator=calc)
    atoms.center(vacuum=2.0)
    gopt = BFGS(atoms, logfile=None)
    gopt.run(fmax=1e-6)

    print(atoms.get_potential_energy())
    return
Exemple #20
0
def relax_VarianceBreak(structure, calc, label='', niter_max=10, forcemax=0.1):
    '''
    Relax a structure and saves the trajectory based in the index i

    Parameters
    ----------
    structure : ase Atoms object to be relaxed

    Returns
    -------
    '''

    # Set calculator 
    structure.set_calculator(calc)

    # loop a number of times to capture if minimization stops with high force
    # due to the VariansBreak calls
    niter = 0

    # If the structure is already fully relaxed just return it
    if (structure.get_forces()**2).sum(axis = 1).max()**0.5 < forcemax:
        return structure
    
    while (structure.get_forces()**2).sum(axis = 1).max()**0.5 > forcemax and niter < niter_max:
        dyn = BFGS(structure,
                   logfile=label+'.log')
        vb = VariansBreak(structure, dyn, min_stdev = 0.01, N = 15)
        dyn.attach(vb)
        dyn.run(fmax = forcemax, steps = 200)
        niter += 1
        
    return structure
Exemple #21
0
def optimize_molecule(nuclear_charges, coordinates):

    # LOAD AND SET MODEL
    parameters = {}
    parameters["offset"] = -97084.83100465109
    parameters["sigma"] = 10.0

    alphas = np.load(FILENAME_ALPHAS)
    X = np.load(FILENAME_REPRESENTATIONS)
    Q = np.load(FILENAME_CHARGES)

    calculator = QMLCalculator(parameters, X, Q, alphas)

    molecule = ase.Atoms(nuclear_charges, coordinates)
    molecule.set_calculator(calculator)

    energy = molecule.get_potential_energy()
    forces = molecule.get_forces()

    dyn = BFGS(molecule)
    dyn.run(fmax=0.5)

    dump_xyz(molecule, "tmp_opt.xyz")

    return
    def run_one_in_plane_distance(self,
                                  cell_length_x=2.0,
                                  cell_length_y=2.0,
                                  direction=(0, 0, 1),
                                  smax=0.003):
        # Rotate the atoms object such that the z-direction points along target_z_direction
        self.atoms = align_direction_with_z(self.atoms, direction=direction)
        lengths_angles = self.atoms.get_cell_lengths_and_angles()
        ratio_x = cell_length_x / lengths_angles[0]
        ratio_y = cell_length_y / lengths_angles[1]
        cell = self.atoms.get_cell()
        cell[0, :] *= ratio_x
        cell[1, :] *= ratio_y
        self.atoms.set_cell(cell.T, scale_atoms=True)

        strfilter = StrainFilter(self.atoms, mask=[0, 0, 1, 1, 1, 1])
        relaxer = BFGS(self.atoms)
        V = self.atoms.get_volume()
        relaxer.run(fmax=smax * V)

        # Store the results to ase db
        db = connect(self.db_name)
        kvp = {
            "cell_length_x": cell_length_x,
            "cell_length_y": cell_length_y,
            "direction_x": direction[0],
            "direction_y": direction[1],
            "direction_z": direction[2]
        }
        db.write(self.atoms, key_value_pairs=kvp)
    def run_NEB():
        if method == 'dyn':
            neb = DyNEB(images, fmax=fmax, dynamic_relaxation=True)
            neb.interpolate()
        elif method == 'dyn_scale':
            neb = DyNEB(images,
                        fmax=fmax,
                        dynamic_relaxation=True,
                        scale_fmax=6.)
            neb.interpolate()
        else:
            # Default NEB
            neb = DyNEB(images, dynamic_relaxation=False)
            neb.interpolate()

        # Optimize and check number of calculations.
        # We use a hack with a global counter to count the force evaluations:
        force_evaluations[0] = 0
        opt = BFGS(neb)
        opt.run(fmax=fmax)
        force_calls.append(force_evaluations[0])

        # Get potential energy of transition state.
        Emax.append(
            np.sort([image.get_potential_energy()
                     for image in images[1:-1]])[-1])
Exemple #24
0
def get_neb(in_file='input.traj'):
    """Performs a ASE NEB optimization with the ase-espresso
    calculator with the keywords defined inside the atoms object information.

    Parameters
    ----------
    in_file : str
        Name of the input file to load from the local directory.
    """
    images = read(in_file, ':')

    for atoms in images[1:-1]:
        calc = espresso(**atoms.info)
        atoms.set_calculator(calc)

    neb = NEB(images)
    opt = BFGS(neb, trajectory='output.traj', logfile=None)
    opt.run(fmax=atoms.info.get('fmax'))
    out_images = read('output.traj', ':')

    # Save the calculator to the local disk for later use.
    try:
        calc.save_flev_output()
    except (RuntimeError):
        calc.save_output()

    return atoms_to_encode(out_images)
Exemple #25
0
def test_emt1(testdir):
    a = 3.6
    b = a / 2
    cu = Atoms('Cu2Ag',
               positions=[(0, 0, 0),
                          (b, b, 0),
                          (a, a, b)],
               calculator=EMT())
    e0 = cu.get_potential_energy()
    print(e0)

    d0 = cu.get_distance(0, 1)
    cu.set_constraint(FixBondLength(0, 1))

    def f():
        print(cu.get_distance(0, 1))

    qn = BFGS(cu)
    with Trajectory('cu2ag.traj', 'w', cu) as t:
        qn.attach(t.write)

        qn.attach(f)
        qn.run(fmax=0.001)

    assert abs(cu.get_distance(0, 1) - d0) < 1e-14
    def Surface001(self, EMT, PARAMETERS):
        """ The Method calculates and returns the surface energy for the given element along the [0,0,1] direction in   
            the FCC crystal structure. """
        # The size of the crystals are set:
        S001 = 3, 3, 5
        # The surfaces (slabs) are created (pbc=(1,1,0) creates periodic boudry conditions
        # in two of three directions and thus leaves the last direction as two surfaces.
        Surface001 = FaceCenteredCubic(size=S001,
                                       symbol=self.Element,
                                       pbc=(1, 1, 0))
        Surface001.set_calculator(EMT)

        # A structural relaxsation is run for the surface crystal in order to secure
        # the correct structure of the crystal.
        dyn001 = BFGS(Surface001, logfile=None)
        dyn001.run(fmax=0.01)

        # The referance bulk crystals are created
        Bulk001 = FaceCenteredCubic(size=S001, symbol=self.Element)

        # The calculator is assigned
        Bulk001.set_calculator(EMT)

        # The surface area is calculated
        # The cross product between the x and y axis in the crystal is determined
        Cross001 = numpy.cross(Bulk001.get_cell()[:, 0],
                               Bulk001.get_cell()[:, 1])
        # The area of the surface is determined from the formular A = |X x Y|.
        area001 = numpy.sqrt(numpy.dot(Cross001, Cross001))

        # The surface energy is calculated and returned (two surfaces are present in
        # SurfaceRelaxed)
        return ((Surface001.get_potential_energy() -
                 Bulk001.get_potential_energy()) / 2 / area001)
Exemple #27
0
def fixOverlap(clus_to_fix):
    """
    Support function to fix any overlaps that may arise due to the mutations by radially moving the atoms that have overlap
    """
    natoms = len(clus_to_fix)
    CoM(clus_to_fix)
    for i in range(natoms):
        for j in range(i):
            r1 = np.array(clus_to_fix[j].position)
            r2 = np.array(clus_to_fix[i].position)
            rij = r2 - r1
            distance = np.sqrt(np.dot(rij, rij))
            dmin = (covalent_radii[clus_to_fix[i].number] +
                    covalent_radii[clus_to_fix[j].number]) * 0.9
            if distance < 0.9 * dmin:
                a = np.dot(r2, r2)
                b = np.dot(r1, r2)
                c = np.dot(r1, r1) - dmin**2
                alpha = 1.000001 * (b + np.sqrt(b * b - a * c)) / a
                clus_to_fix[i].x *= alpha
                clus_to_fix[i].y *= alpha
                clus_to_fix[i].z *= alpha
    clus_to_fix.center(vacuum=9)
    clus_to_fix_sorted = sort(clus_to_fix)
    clus_to_fix_sorted.pbc = (True, True, True)
    clus_to_fix_sorted.calc = EMT()
    dyn = BFGS(clus_to_fix_sorted, logfile=None)
    dyn.run(fmax=0.05, steps=1000)
    return clus_to_fix_sorted
Exemple #28
0
def relaxGPAW(structure, label, calc, forcemax=0.1, niter_max=1, steps=10):
    calc.set(txt=label + '_init.txt')

    # Set calculator
    structure.set_calculator(calc)

    # loop a number of times to capture if minimization stops with high force
    # due to the VariansBreak calls
    niter = 0

    # If the structure is already fully relaxed just return it
    if (structure.get_forces()**2).sum(axis=1).max()**0.5 < forcemax:
        return structure
    #print('relaxgpaw start',flush=True)
    traj = Trajectory(label + '_lcao.traj', 'w', structure)
    while (structure.get_forces()**
           2).sum(axis=1).max()**0.5 > forcemax and niter < niter_max:
        dyn = BFGS(structure, logfile=label + '.log')
        vb = VariansBreak(structure, dyn, min_stdev=0.01, N=15)
        dyn.attach(traj)
        dyn.attach(vb)
        dyn.run(fmax=forcemax, steps=steps)
        niter += 1
    #print('relaxgpaw over',flush=True)
    return structure
Exemple #29
0
def main():
    '''Main driver routine.'''

    initial = read('NH3_initial.traj')
    final = read('NH3_final.traj')

    images = [initial]
    images += [initial.copy() for ii in range(NIMAGES)]
    images += [final]

    neb = NEB(images)
    neb.interpolate()

    opt = BFGS(neb, trajectory='i2f.traj')

    calcs = [
        Dftb(label='NH3_inversion',
             Hamiltonian_SCC='Yes',
             Hamiltonian_SCCTolerance='1.00E-06',
             Hamiltonian_MaxAngularMomentum_N='"p"',
             Hamiltonian_MaxAngularMomentum_H='"s"') for ii in range(NIMAGES)
    ]

    for ii, calc in enumerate(calcs):
        images[ii + 1].set_calculator(calc)

    opt.run(fmax=1.00E-02)
Exemple #30
0
    def compute_energy(self, particle, relax_atoms=False):
        """Compute the energy using EMT.

        BFGS is used for relaxation. By default, the atoms are NOT relaxed, i.e. the
        geometry remains unchanged unless this is explicitly stated.

        Parameters:
            particle : Nanoparticle
            relax_atoms : bool
        """
        cell_width = 1e3
        cell_height = 1e3
        cell_length = 1e3

        atoms = particle.get_ase_atoms(exclude_x=True)
        if not relax_atoms:
            atoms = atoms.copy()

        atoms.set_cell(np.array([[cell_width, 0, 0], [0, cell_length, 0], [0, 0, cell_height]]))
        atoms.set_calculator(EMT())
        dyn = BFGS(atoms)
        dyn.run(fmax=self.fmax, steps=self.steps)

        energy = atoms.get_potential_energy()
        particle.set_energy(self.energy_key, energy)
Exemple #31
0
def get_optimal_h(atoms, natoms, dyn = False, show = False):
    
    # This find the optimal h - when the top is sliding:
    
    if not dyn:
        from scipy.optimize import fmin
        pos_init    =   atoms.positions.copy()
        
        def get_epot(z):
            
            new_pos         =   pos_init
            new_pos[:,2]    =   z 
            atoms.positions =   new_pos
            
            e   = atoms.get_potential_energy()/natoms
            #print   z, e
            return  e  
        
        hmin    =   fmin(get_epot, 3.4, disp = 0)
        emin    =   get_epot(hmin)
        
        atoms.positions = pos_init
        
        if show:    print 'optimal height= %.2f and e=%.2f' %(hmin, emin) 
        return emin, hmin
    else:
        dyn         =   BFGS(atoms)
        dyn.run(fmax=0.03)
        e           =   atoms.get_potential_energy()/natoms
        hmin        =   np.average(atoms.positions[:,2])
        return e, hmin
Exemple #32
0
def test(size, R, nk):

    
    atoms_flat  =   get_square_uCell(size)
    
    view(atoms_flat)
    
    # CALCULATOR FLAT
    calc_f      =   Hotbit(SCC=False, kpts=(nk,nk,1),  \
                           txt= path + 'test_consistency/optimization_flat.cal')
    atoms_flat.set_calculator(calc_f)
    
    opt_f       =   BFGS(atoms_flat)
    opt_f.run(fmax = 0.05)
    e_flat      =   atoms_flat.get_potential_energy()
    

    
    
    atoms_c     =   atoms_flat.copy()
    
    L           =   atoms_c.get_cell().diagonal()
     
    atoms_c.set_cell(L) 
    angle       =   L[1]/R
    atoms_c.rotate('y', np.pi/2)
    atoms_c.translate((-atoms_c[0].x, 0, 0) )
    
    for a in atoms_c:
        r0      =   a.position
        phi     =   r0[1]/L[1]*angle
        a.position[0]   =   R*np.cos(phi)
        a.position[1]   =   R*np.sin(phi)
    
    
    atoms_c       =   Atoms(atoms = atoms_c, container = 'Wedge')
    atoms_c.set_container(angle = angle, height = L[0], physical = False, pbcz = True)
    
    if R < 100:
        view(atoms_c.extended_copy((8,1,3)))
    
    # CALCULATOR Cyl
    calc_c      =   Hotbit(SCC=False, kpts=(nk,1, nk), physical_k = False, \
                           txt= path + 'test_consistency/optimization_cyl.cal')
    atoms_c.set_calculator(calc_c)
    
    opt_c       =   BFGS(atoms_c)
    opt_c.run(fmax = 0.05)
    
    
    e_cyl       =   atoms_c.get_potential_energy()

    print 'R = %.2f' %R
    print 'energy flat     = %.6f' %e_flat
    print 'energy cylinder = %.6f' %e_cyl
    print 'energy dif (e_cylinder - eflat)/nAtoms  = %.6f \n' %(-(e_flat - e_cyl)/len(atoms_flat))
    
    return e_flat, e_cyl, len(atoms_flat)
Exemple #33
0
def ase_minimization(indiv, Optimizer):
    """Function to use built in ASE minimizers to minimize atomic positions in structure.
    Input:
        indiv = Individual class object to be optimized
        Optimizer = Optimizer class object with needed parameters
    Output:
        indiv = Optimized Individual class object.
    """
    if 'MU' in Optimizer.debug:
        debug = True
    else:
        debug = False
    cwd1=os.getcwd()
    olammpsmin = Optimizer.lammps_min
    if Optimizer.lammps_min:
        Optimizer.lammps_min = None
    calc2 = setup_calculator(Optimizer)
#     if 'mass' in indiv[0].get_calculator():
#         mass2 = ['1 '+ str(Optimizer.atomlist[0][2])]
#         if len(Optimizer.atomlist) > 1:
#             for i in range(len(Optimizer.atomlist)-1):
#                 mass2.append(str(i+2) + ' ' + str(Optimizer.atomlist[i+1][2]))
#         calc2=LAMMPS(parameters={ 'pair_style' : Optimizer.pair_style, 'pair_coeff' : Optimizer.pair_coeff , 'mass' : mass2 },files=[ Optimizer.pot_file ])
#     else:
#         calc2=LAMMPS(parameters={ 'pair_style' : Optimizer.pair_style, 'pair_coeff' : Optimizer.pair_coeff},files=[ Optimizer.pot_file ])
    if Optimizer.structure==Defect:
        nat=indiv[0].get_number_of_atoms
        sol=Atoms()
        sol.extend(indiv[0])
        sol.extend(indiv.bulko)
        sol.set_calculator(calc2)
        sol.set_cell(indiv.bulko.get_cell())
        sol.set_pbc(True)
        dyn=BFGS(sol)
        dyn.run(fmax=0.001, steps=2500)
        positions=sol[0:nat].get_positions()
        indiv[0].set_positions(positions)
    else:
        atomsdup=indiv[0].copy()
        atomsdup.set_calculator(calc2)
        dyn=BFGS(indiv[0])
        dyn.run(fmax=0.001, steps=2500)
        positions=atomsdup.get_positions()
        indiv[0].set_positions(positions)
    os.chdir(cwd1)
    calc2.clean()
    Optimizer.lammps_min = olammpsmin
    Optimizer.output.write('ASE Minimization mutation performed on individual = '+repr(indiv.index)+'\n')
    muttype='ASEM'
    if indiv.energy==0:
        indiv.history_index=indiv.history_index+'m'+muttype
    else:
        indiv.history_index=repr(indiv.index)+'m'+muttype
    return indiv
		
		
Exemple #34
0
def test_geopt():
    calc = CP2K(label='test_geopt')
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    dyn = BFGS(h2)
    dyn.run(fmax=0.05)
    dist = h2.get_distance(0, 1)
    diff = abs((dist - 1.36733746519) / dist)
    assert(diff < 1e-10)
    print('passed test "geopt"')
Exemple #35
0
def run(sigma, atoms):
    calc = CP2K(label = 'molecules/co-relax/sigma{0}'.format(sigma),
          xc='PBE')
    atoms.set_calculator(calc)
    gopt = BFGS(atoms, logfile=None)
    gopt.run(fmax=1e-2)
    e = atoms.get_potential_energy()
    pos = atoms.get_positions()
    d = ((pos[0] - pos[1])**2).sum()**0.5
    print('{0:1.2f}  {1:1.4f}  {2:1.4f}'.format(sigma, e, d))
Exemple #36
0
 def idpp_interpolate(self, traj='idpp.traj', log='idpp.log', fmax=0.1,
                      optimizer=BFGS):
     d1 = self.images[0].get_all_distances()
     d2 = self.images[-1].get_all_distances()
     d = (d2 - d1) / (self.nimages - 1)
     old = []
     for i, image in enumerate(self.images):
         old.append(image.calc)
         image.calc = IDPP(d1 + i * d)
     opt = BFGS(self, trajectory=traj, logfile=log)
     opt.run(fmax=0.1)
     for image, calc in zip(self.images, old):
         image.calc = calc
def ase_vol_relax():
    Al = bulk('Al', 'fcc', a=4.5, cubic=True)
    calc = Vasp(xc='LDA')
    Al.set_calculator(calc)

    from ase.constraints import StrainFilter
    sf = StrainFilter(Al)
    qn = QuasiNewton(sf, logfile='relaxation.log')
    qn.run(fmax=0.1, steps=5)

    print 'Stress:\n', calc.read_stress()
    print 'Al post ASE volume relaxation\n', calc.get_atoms().get_cell()

    return Al
Exemple #38
0
def ase_vol_relax():
    Al = bulk("Al", "fcc", a=4.5, cubic=True)
    calc = Vasp(xc="LDA")
    Al.set_calculator(calc)

    from ase.constraints import StrainFilter

    sf = StrainFilter(Al)
    qn = QuasiNewton(sf, logfile="relaxation.log")
    qn.run(fmax=0.1, steps=5)

    print("Stress:\n", calc.read_stress())
    print("Al post ASE volume relaxation\n", calc.get_atoms().get_cell())

    return Al
Exemple #39
0
def run_neb_calculation(cpu):
    images = [PickleTrajectory('H.traj')[-1]]
    for i in range(nimages):
        images.append(images[0].copy())
    images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
    neb = NEB(images, parallel=True, world=cpu)
    neb.interpolate()

    images[cpu.rank + 1].set_calculator(Calculator())

    dyn = BFGS(neb)
    dyn.run(fmax=fmax)

    if cpu.rank == 1:
        results.append(images[2].get_potential_energy())
def test_pwscf_calculator():
    if not have_ase():
        skip("no ASE found, skipping test")
    elif not have_pwx():
        skip("no pw.x found, skipping test")
    else:
        pseudo_dir = pj(testdir, prefix, 'pseudo')
        print common.backtick("mkdir -pv {p}; cp files/qe_pseudos/*.gz {p}/; \
            gunzip {p}/*".format(p=pseudo_dir))
        at = get_atoms_with_calc_pwscf(pseudo_dir)

        print "scf"
        # trigger calculation here
        forces = at.get_forces()
        etot = at.get_potential_energy()
        stress = at.get_stress(voigt=False) # 3x3
        
        st = io.read_pw_scf(at.calc.label + '.out')
        assert np.allclose(forces, st.forces)
        assert np.allclose(etot, st.etot)
        assert np.allclose(st.stress, -stress * constants.eV_by_Ang3_to_GPa)
        
        # files/ase/pw.scf.out.start is a norm-conserving LDA struct,
        # calculated with pz-vbc.UPF, so the PBE vc-relax will make the cell
        # a bit bigger
        print "vc-relax"
        from ase.optimize import BFGS
        from ase.constraints import UnitCellFilter
        opt = BFGS(UnitCellFilter(at))
        cell = parse.arr2d_from_txt("""
            -1.97281509  0.          1.97281509
             0.          1.97281509  1.97281509
            -1.97281509  1.97281509  0.""")        
        assert np.allclose(cell, at.get_cell())
        opt.run(fmax=0.05) # run only 2 steps
        cell = parse.arr2d_from_txt("""
            -2.01837531  0.          2.01837531
             0.          2.01837531  2.01837531
            -2.01837531  2.01837531  0""")
        assert np.allclose(cell, at.get_cell())

        # at least 1 backup files must exist: pw.*.0 is the SCF run, backed up
        # in the first iter of the vc-relax
        assert os.path.exists(at.calc.infile + '.0')
def relaxBend(bend, left_idxs, right_idxs, edge, bond, mdrelax):
    
    constraints =   []
    constraints.append(FixAtoms(indices = left_idxs))        
    constraints.append(FixAtoms(indices = right_idxs))        
    #twist       =   twistConst_Rod(bend, 1, edge, bond ,F = 20)
    #twist.set_angle(np.pi/3 + 2./180*np.pi)
    #constraints.append(twist)
    
    add_pot =   LJ_potential_smooth(bend, bond)
    constraints.append(add_pot)
    
    calc    =   LAMMPS(parameters=get_lammps_params()) 
    bend.set_calculator(calc)
    # END CALCULATOR
    
    # RELAX
    bend.set_constraint(constraints)
    dyn     =   BFGS(bend, trajectory = mdrelax)
    dyn.run(fmax=0.05)
def test_lammps_calculator():
    if not have_ase():
        skip("no ASE found, skipping test")
    elif not have_lmp():
        skip("no lammps found, skipping test")
    else:
        at = get_atoms_with_calc_lammps()
        at.rattle(stdev=0.001, seed=int(time.time()))
        common.makedirs(at.calc.directory)
        print common.backtick("cp -v utils/lammps/AlN.tersoff {p}/".format(
            p=at.calc.directory))

        print "scf"
        forces = at.get_forces()
        etot = at.get_potential_energy()
        stress = at.get_stress(voigt=False) # 3x3
        
        st = io.read_lammps_md_txt(at.calc.label + '.out')[0]
        assert np.allclose(forces, st.forces)
        assert np.allclose(etot, st.etot)
        assert np.allclose(st.stress, -stress * constants.eV_by_Ang3_to_GPa,
                           atol=1e-10)
        
        print "relax"
        from ase.optimize import BFGS
        opt = BFGS(at, maxstep=0.04)
        opt.run(fmax=0.001, steps=10)
        coords_frac = parse.arr2d_from_txt("""
            3.3333341909920072e-01    6.6666683819841532e-01    4.4325467247779138e-03
            6.6666681184103216e-01    3.3333362368205072e-01    5.0443254824788963e-01
            3.3333341909918301e-01    6.6666683819838046e-01    3.8356759709402671e-01
            6.6666681184101539e-01    3.3333362368201563e-01    8.8356759861713752e-01
            """)
        assert np.allclose(coords_frac, at.get_scaled_positions(), atol=1e-2)

        # at least 1 backup files must exist
        assert os.path.exists(at.calc.infile + '.0')
        assert os.path.exists(at.calc.outfile + '.0')
        assert os.path.exists(at.calc.dumpfile + '.0')
        assert os.path.exists(at.calc.structfile + '.0')
Exemple #43
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(label='test_H2_GOPT')
    atoms = molecule('H2', calculator=calc)
    atoms.center(vacuum=2.0)

    # Run Geo-Opt
    gopt = BFGS(atoms, logfile=None)
    gopt.run(fmax=1e-6)

    # check distance
    dist = atoms.get_distance(0, 1)
    dist_ref = 0.7245595
    assert (dist - dist_ref) / dist_ref < 1e-7

    # check energy
    energy_ref = -30.7025616943
    energy = atoms.get_potential_energy()
    assert (energy - energy_ref) / energy_ref < 1e-10
    print('passed test "H2_GEO_OPT"')
Exemple #44
0
def run_ase_min(totalsol, fmax=0.01, mxstep=1000, fitscheme='totalenfit', STR=''):
    try:
        dyn=BFGS(totalsol)
        dyn.run(fmax=fmax, steps=mxstep)
    except OverflowError:
        STR+='--- Error: Infinite Energy Calculated - Implement Random shake---\n'
        totalsol.rattle(stdev=0.3)
        dyn=BFGS(totalsol)
        dyn.run(fmax=fmax, steps=mxstep)
    except numpy.linalg.linalg.LinAlgError:
        STR+='--- Error: Singular Matrix - Implement Random shake ---\n'
        totalsol.rattle(stdev=0.2)
        dyn=BFGS(totalsol)
        dyn.run(fmax=fmax, steps=mxstep)
    # Get Energy of Minimized Structure
    en=totalsol.get_potential_energy()
    if fitscheme == 'enthalpyfit':
        pressure=totalsol.get_isotropic_pressure(totalsol.get_stress())
    else:
        pressure=0
    volume = totalsol.get_volume()
    energy=en
    return totalsol, energy, pressure, volume, STR
Exemple #45
0
for i in range(3):

    ranks = range(i * n, (i + 1) * n)
    image = initial.copy()

    if rank in ranks:

        calc = GPAW(h=0.3,
                    kpts=(2, 2, 1),
                    txt='neb%d.txt' % j,
                    communicator=ranks)
        
        image.set_calculator(calc)
        
    image.set_constraint(constraint)
    images.append(image)
    
images.append(final)

neb = NEB(images, parallel=True)
neb.interpolate()

qn = BFGS(neb, logfile='qn.log')

traj = PickleTrajectory('neb%d.traj' % j, 'w', images[j],
                        master=(rank % n == 0))

qn.attach(traj)
qn.run(fmax=0.05)
Exemple #46
0
def eval_energy(input):
    """Function to evaluate energy of an individual
    Inputs:
        input = [Optimizer class object with parameters, Individual class structure to be evaluated]
    Outputs:
        energy, bul, individ, signal
        energy = energy of Individual evaluated
        bul = bulk structure of Individual if simulation structure is Defect
        individ = Individual class structure evaluated
        signal = string of information about evaluation
    """
    if input[0]==None:
        energy=0
        bul=0
        individ=0
        rank = MPI.COMM_WORLD.Get_rank()
        signal='Evaluated none individual on '+repr(rank)+'\n'
    else:
        [Optimizer, individ]=input
    if Optimizer.calc_method=='MAST':
        energy = individ.energy
        bul = individ.energy
        signal = 'Recieved MAST structure\n'
    else:
        if Optimizer.parallel: rank = MPI.COMM_WORLD.Get_rank()
        if not Optimizer.genealogy:
            STR='----Individual ' + str(individ.index)+ ' Optimization----\n'
        else:
            STR='----Individual ' + str(individ.history_index)+ ' Optimization----\n'
        indiv=individ[0]
        if 'EE' in Optimizer.debug:
            debug = True
        else:
            debug = False
        if debug: 
            write_xyz(Optimizer.debugfile,indiv,'Recieved by eval_energy')
            Optimizer.debugfile.flush()
        if Optimizer.structure=='Defect':
            indi=indiv.copy()
            if Optimizer.alloy==True:
                bulk=individ.bulki
            else:
                bulk=individ.bulko
            nat=indi.get_number_of_atoms()
            csize=bulk.get_cell()                                                                                                         
            totalsol=Atoms(cell=csize, pbc=True)
            totalsol.extend(indi)
            totalsol.extend(bulk)
            for sym,c,m,u in Optimizer.atomlist:
                nc=len([atm for atm in totalsol if atm.symbol==sym])
                STR+='Defect configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n'
    
        elif Optimizer.structure=='Surface':
            totalsol=Atoms()
            totalsol.extend(indiv)
            nat=indiv.get_number_of_atoms()
            totalsol.extend(individ.bulki)
            for sym,c,m,u in Optimizer.atomlist:
                nc=len([atm for atm in totalsol if atm.symbol==sym])
                STR+='Surface-Bulk configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n'
            cell=numpy.maximum.reduce(indiv.get_cell())
            totalsol.set_cell([cell[0],cell[1],500])
            totalsol.set_pbc([True,True,False])
    
        if Optimizer.constrain_position:
            ts = totalsol.copy()
            indc,indb,vacant,swap,stro = find_defects(ts,Optimizer.solidbulk,0)
            sbulk = Optimizer.solidbulk.copy()
            bcom = sbulk.get_center_of_mass()
            #totalsol.translate(-bulkcom)
            #indc.translate(-bulkcom)
            #totalsol.append(Atom(position=[0,0,0]))
    # 			for one in indc:
    # 				index = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
    # 				if totalsol.get_distance(-1,index) > Optimizer.sf:
    # 					r = random.random()
    # 					totalsol.set_distance(-1,index,Optimizer.sf*r,fix=0)
    # 			totalsol.pop()
    # 			totalsol.translate(bulkcom)
            com = indc.get_center_of_mass()
            dist = (sum((bcom[i] - com[i])**2 for i in range(3)))**0.5
            if dist > Optimizer.sf:
                STR+='Shifting structure to within region\n'
                r = random.random()*Optimizer.sf
                comv = numpy.linalg.norm(com)
                ncom = [one*r/comv for one in com]
                trans = [ncom[i]-com[i] for i in range(3)]
                indices = []
                for one in indc:
                    id = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
                    totalsol[id].position += trans
    
        # Check for atoms that are too close
        min_len=0.7
        #pdb.set_trace()
        if not Optimizer.fixed_region:
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                cutoffs=[2.0 for one in totalsol]
                nl=NeighborList(cutoffs,bothways=True,self_interaction=False)
                nl.update(totalsol)
                for one in totalsol[0:nat]:
                    nbatoms=Atoms()
                    nbatoms.append(one)
                    indices, offsets=nl.get_neighbors(one.index)
                    for index, d in zip(indices,offsets):
                        index = int(index)
                        sym=totalsol[index].symbol
                        pos=totalsol[index].position + numpy.dot(d,totalsol.get_cell())
                        at=Atom(symbol=sym,position=pos)
                        nbatoms.append(at)
                    while True:
                        dflag=False
                        for i in range(1,len(nbatoms)):
                            d=nbatoms.get_distance(0,i)
                            if d < min_len:
                                nbatoms.set_distance(0,i,min_len+.01,fix=0.5)
                                STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                                dflag=True
                        if dflag==False:
                            break
                    for i in range(len(indices)):
                        totalsol[indices[i]].position=nbatoms[i+1].position
                    totalsol[one.index].position=nbatoms[0].position
                    nl.update(totalsol)
                if debug:
                    write_xyz(Optimizer.debugfile,totalsol,'After minlength check')
                    Optimizer.debugfile.flush()
            else:
                for i in range(len(indiv)):
                    for j in range(len(indiv)):
                        if i != j:
                            d=indiv.get_distance(i,j)
                            if d < min_len:
                                indiv.set_distance(i,j,min_len,fix=0.5)
                                STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                if debug:
                    write_xyz(Optimizer.debugfile,indiv,'After minlength check')
                    Optimizer.debugfile.flush()
    
        # Set calculator to use to get forces/energies
        if Optimizer.parallel:
            calc = setup_calculator(Optimizer)
            if Optimizer.fixed_region:
                pms=copy.deepcopy(calc.parameters)
                try:
                    pms['mass'][len(pms['mass'])-1] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n'
                except KeyError:
                    pms['pair_coeff'][0] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n'
                calc = LAMMPS(parameters=pms, files=calc.files, keep_tmp_files=calc.keep_tmp_files, tmp_dir=calc.tmp_dir)
                lmin = copy.copy(Optimizer.lammps_min)
                Optimizer.lammps_min = None
                Optimizer.static_calc = setup_calculator(Optimizer)
                Optimizer.lammps_min = lmin
        else:
            calc=Optimizer.calc
        if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
            totalsol.set_calculator(calc)
            totalsol.set_pbc(True)
        else:
            indiv.set_calculator(calc)
            indiv.set_pbc(True)	#Current bug in ASE optimizer-Lammps prevents pbc=false 
            if Optimizer.structure=='Cluster':
                indiv.set_cell([500,500,500])
                indiv.translate([250,250,250])
    
        cwd=os.getcwd()
        # Perform Energy Minimization
        if not Optimizer.parallel:
            Optimizer.output.flush()
        if Optimizer.ase_min == True:
            try:
                if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                    dyn=BFGS(totalsol)
                else:
                    dyn=BFGS(indiv)
                dyn.run(fmax=Optimizer.ase_min_fmax, steps=Optimizer.ase_min_maxsteps)
            except OverflowError:
                STR+='--- Error: Infinite Energy Calculated - Implement Random ---\n'
                box=Atoms()
                indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size)
                indiv.set_calculator(calc)
                dyn=BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            except numpy.linalg.linalg.LinAlgError:
                STR+='--- Error: Singular Matrix - Implement Random ---\n'
                indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size)
                indiv.set_calculator(calc)
                dyn=BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            # Get Energy of Minimized Structure
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                en=totalsol.get_potential_energy()
                #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=totalsol.get_isotropic_pressure(totalsol.get_stress())
                    cell_max=numpy.maximum.reduce(totalsol.get_positions())
                    cell_min=numpy.minimum.reduce(totalsol.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else:
                    pressure=0
                    volume=0
                na=totalsol.get_number_of_atoms()
                ena=en/na
                energy=en
                individ[0]=totalsol[0:nat]
                bul=totalsol[(nat):len(totalsol)]
                STR+='Number of positions = '+repr(len(bul)+len(individ[0]))+'\n'
                individ[0].set_cell(csize)
                indiv=individ[0]
            else:
                en=indiv.get_potential_energy()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=indiv.get_isotropic_pressure(indiv.get_stress())
                    cell_max=numpy.maximum.reduce(indiv.get_positions())
                    cell_min=numpy.minimum.reduce(indiv.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else: 
                    pressure=0
                    volume=0
                na=indiv.get_number_of_atoms()
                ena=en/na
                energy=ena
                individ[0]=indiv
                bul=0
        else:
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                if Optimizer.calc_method=='VASP':
                    en=totalsol.get_potential_energy()
                    calcb=Vasp(restart=True)
                    totalsol=calcb.get_atoms()
                    stress=calcb.read_stress()
                else:
                    try:
                        totcop=totalsol.copy()
                        if debug: write_xyz(Optimizer.debugfile,totcop,'Individual sent to lammps')
                        OUT=totalsol.calc.calculate(totalsol)
                        totalsol=OUT['atoms']
                        totalsol.set_pbc(True)
                        if Optimizer.fixed_region:
                            if debug:
                                print 'Energy of fixed region calc = ', OUT['thermo'][-1]['pe']
                            totalsol.set_calculator(Optimizer.static_calc)
                            OUT=totalsol.calc.calculate(totalsol)
                            totalsol=OUT['atoms']
                            totalsol.set_pbc(True)
                            if debug:
                                print 'Energy of static calc = ', OUT['thermo'][-1]['pe']
                        en=OUT['thermo'][-1]['pe']
                        stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa)
                        #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                        if debug:
                            write_xyz(Optimizer.debugfile,totalsol,'After Lammps Minimization')
                            Optimizer.debugfile.flush()
                    except Exception, e:
                        os.chdir(cwd)
                        STR+='WARNING: Exception during energy eval:\n'+repr(e)+'\n'
                        f=open('problem-structures.xyz','a')
                        write_xyz(f,totcop,data='Starting structure hindex='+individ.history_index)
                        write_xyz(f,totalsol,data='Lammps Min structure')
                        en=10
                        stress=0
                        f.close()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=totalsol.get_isotropic_pressure(stress)
                    cell_max=numpy.maximum.reduce(totalsol.get_positions())
                    cell_min=numpy.minimum.reduce(totalsol.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else:
                    pressure=totalsol.get_isotropic_pressure(stress)
                    volume=0
                na=totalsol.get_number_of_atoms()
                ena=en/na
                energy=en
                if Optimizer.structure=='Defect':
                    if Optimizer.fixed_region==True or Optimizer.finddefects==False:
                        individ[0]=totalsol[0:nat]
                        bul=totalsol[(nat):len(totalsol)]
                        individ[0].set_cell(csize)
                    else:
                        if 'FI' in Optimizer.debug:
                            outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=Optimizer.debugfile)
                        else:
                            outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=False)
                        individ[0]=outt[0]
                        bul=outt[1]
                        individ.vacancies = outt[2]
                        individ.swaps = outt[3]
                        STR += outt[4]
                    indiv=individ[0]
                else:
                    top,bul=find_top_layer(totalsol,Optimizer.surftopthick)
                    indiv=top.copy()
                    individ[0]=top.copy()
            else:
Exemple #47
0
ref = np.array([[-1.26446863e-01, 4.09628186e-01, -0.00000000e+00],
                [4.27934442e-01, 2.50425467e-02, -5.14220671e-05],
                [-2.99225008e-01, -4.31533987e-01, -5.14220671e-05]])

error = np.sqrt(np.sum((forces_an - ref)**2))
print('forces_an')
print(forces_an)
print('diff from reference:')
print(error)

assert(error < tol)

# optimize geometry
dyn = BFGS(atoms)
dyn.run(fmax=0.01)

positions = atoms.get_positions()

ref = np.array([[  9.61364579e-01, 2.81689367e-02, -1.58730770e-06],
                [ -3.10444398e-01, 9.10289261e-01, -5.66399075e-06],
                [ -1.56957763e-02, -2.26044053e-02, -2.34155615e-06]])

error = np.sqrt(np.sum((positions - ref)**2))
print('positions')
print(positions)
print('diff from reference:')
print(error)

assert(error < tol)
Exemple #48
0
    F = np.array(F)

    # plt.plot(D, E)

    F1 = np.polyval(np.polyder(np.polyfit(D, E, 7)), D)
    F2 = F[:, :3, 0].sum(1)
    error = abs(F1 - F2).max()

    dimer.constraints = FixInternals(
        bonds=[(r, (0, 2)), (r, (1, 2)),
               (r, (3, 5)), (r, (4, 5))],
        angles=[(a, (0, 2, 1)), (a, (3, 5, 4))])
    opt = BFGS(dimer,
               trajectory=calc.name + '.traj', logfile=calc.name + 'd.log')
    opt.run(0.01)

    e0 = dimer.get_potential_energy()
    d0 = dimer.get_distance(2, 5)
    R = dimer.positions
    v1 = R[1] - R[5]
    v2 = R[5] - (R[3] + R[4]) / 2
    a0 = np.arccos(np.dot(v1, v2) /
                   (np.dot(v1, v1) * np.dot(v2, v2))**0.5) / np.pi * 180
    fmt = '{0:>20}: {1:.3f} {2:.3f} {3:.3f} {4:.1f}'
    print(fmt.format(calc.name, -min(E), -e0, d0, a0))
    assert abs(e0 + eexp) < 0.002
    assert abs(d0 - dexp) < 0.006
    assert abs(a0 - aexp) < 2

print(fmt.format('reference', 9.999, eexp, dexp, aexp))
Exemple #49
0
from ase.structure import molecule
from ase.optimize import BFGS
from gpaw import GPAW
from gpaw.mixer import MixerDif

for name in ['H2', 'N2', 'O2', 'NO']:
    mol = molecule(name)
    mol.center(vacuum=5.0)
    calc = GPAW(xc='PBE',
                h=0.2,
                txt=name + '.txt')
    if name == 'NO':
        mol.translate((0, 0.1, 0))
        calc.set(mixer=MixerDif(0.05,5))
    mol.set_calculator(calc)
  
    opt = BFGS(mol, logfile=name + '.log', trajectory=name + '.traj')
    opt.run(fmax=0.05)
    calc.write(name)
Exemple #50
0
    nsteps = '0',
    nstfout = '1',
    nstlog = '1',
    nstenergy = '1',
    nstlist = '1',
    ns_type = 'grid',
    pbc = 'xyz',
    rlist = '1.15',
    coulombtype = 'PME-Switch',
    rcoulomb = '0.8',
    vdwtype = 'shift',
    rvdw = '0.8',
    rvdw_switch = '0.75',
    DispCorr = 'Ener')
CALC_MM.generate_topology_and_g96file()
CALC_MM.generate_gromacs_run_file()

CALC_QMMM = AseQmmmManyqm(nqm_regions = 3, 
                          qm_calculators = [CALC_QM1, CALC_QM2, CALC_QM3], 
                          mm_calculator = CALC_MM,
                          link_info = 'byQM')
#                         link_info = 'byFILE') 

SYSTEM = read_gromos('gromacs_qm.g96')
SYSTEM.set_calculator(CALC_QMMM)
DYN = BFGS(SYSTEM)
DYN.run(fmax = 0.05)

print('exiting fine')
LOG_FILE.close()
Exemple #51
0
#constraint = FixAtoms(mask=[0,1,0,1,0]) # fix OO    #Works without patch
for image in images:
    image.set_calculator(Turbomole())  #BUG No.2: (Over-)writes coord file
    image.set_constraint(constraint)

# Write all commands for the define command in a string
define_str = '\n\na coord\n\n*\nno\nb all 3-21g hondo\n*\neht\n\n-1\nno\ns\n*\n\ndft\non\nfunc pwlda\n\n\nscf\niter\n300\n\n*'
# Run define
p = Popen('define', stdout=PIPE, stdin=PIPE, stderr=STDOUT)
stdout = p.communicate(input=define_str)

# Relax initial and final states:
if 1:
    dyn1 = QuasiNewton(images[0])
    dyn1.run(fmax=0.10)
    dyn2 = QuasiNewton(images[-1])
    dyn2.run(fmax=0.10)


# Interpolate positions between initial and final states:
neb.interpolate()
if 1:
    for image in images:
        print image.get_distance(1, 2), image.get_potential_energy()

dyn = BFGS(neb, trajectory='turbomole_h3o2m.traj')
dyn.run(fmax=0.10)

for image in images:
    print image.get_distance(1, 2), image.get_potential_energy()
def run_moldy(N, save = False):
    
    # 
    params      =   {'bond':bond, 'a':a, 'h':h}
    
    # DEFINE FILES
    mdfile, mdlogfile, mdrelax  =   get_fileName(N, 'tear_E_rebo+KC_v', taito, v, edge)  
    
    # GRAPHENE SLAB
    atoms               =   make_graphene_slab(a,h,width,length,N, \
                                               edge_type = edge, h_pass = True, \
                                               stacking = 'abc')[3]
    
    view(atoms)
    #exit()
    params['ncores']    =   ncores
    params['positions'] =   atoms.positions.copy() 
    params['pbc']       =   atoms.get_pbc()
    params['cell']      =   atoms.get_cell().diagonal()
    params['ia_dist']   =   10
    params['chemical_symbols']  \
                        =   atoms.get_chemical_symbols()
    
    # FIX
    constraints =   []
    print 'hii'
    left        =   get_ind(atoms.positions.copy(), 'left', 2, bond)
    top         =   get_ind(atoms.positions.copy(), 'top', fixtop - 1, left)
    rend_t      =   get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), 1, edge)
    rend        =   get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), fixtop, edge)
    
    print rend
    print 'hoo' 
    exit()
    
    fix_left    =   FixAtoms(indices = left)
    fix_top     =   FixAtoms(indices = top)
    
    add_kc      =   KC_potential_p(params)

    
    for ind in rend:
        fix_deform  =   FixedPlane(ind, (0., 0., 1.))
        constraints.append(fix_deform)
    
    for ind in rend_t:
        fix_deform  =   FixedPlane(ind, (0., 0., 1.))
        constraints.append(fix_deform)
    
    constraints.append(fix_left)
    constraints.append(fix_top)
    constraints.append(add_kc)
    # END FIX
    
    # CALCULATOR LAMMPS 
    parameters = {'pair_style':'rebo',
                  'pair_coeff':['* * CH.airebo C H'],
                  'mass'      :['1 12.0', '2 1.0'],
                  'units'     :'metal', 
                  'boundary'  :'f p f'}
    
    calc    =   LAMMPS(parameters=parameters) 
    atoms.set_calculator(calc)
    # END CALCULATOR
    
    #view(atoms)
    
    # TRAJECTORY
    if save:    traj    =   PickleTrajectory(mdfile, 'w', atoms)
    else:       traj    =   None
    
    #data    =   np.zeros((M/interval, 5))
    
    # RELAX
    atoms.set_constraint(add_kc)
    dyn     =   BFGS(atoms, trajectory = mdrelax)
    dyn.run(fmax=0.05)
    
    # FIX AFTER RELAXATION
    atoms.set_constraint(constraints)
    
    # DYNAMICS
    dyn     =   Langevin(atoms, dt*units.fs, T*units.kB, fric)
    n       =   0
    header  =   '#t [fs], d [Angstrom], epot_tot [eV], ekin_tot [eV], etot_tot [eV] \n'
    log_f   =   open(mdlogfile, 'w')
    log_f.write(header)            
    log_f.close()

    if T != 0:
        # put initial MaxwellBoltzmann velocity distribution
        mbd(atoms, T*units.kB)
    
    
    print 'Start the dynamics for N = %i' %N
    
    for i in range(0, M):
        
        if T == 0:
            for ind in rend:
                atoms[ind].position[2] -= dz 
        elif T != 0:
            if tau < i*dt:
                hw   =   i*dz
                for ind in rend:
                    atoms[ind].position[2] -= dz 
            
        dyn.run(1)
        
        if i%interval == 0:

            epot, ekin  =   saveAndPrint(atoms, traj, False)[:2]
            
            if T != 0:
                if tau < i*dt:  hw   =   i*dz - tau*v
                else: hw =   0
            else:   hw = i*dz
                
            data        =   [i*dt, hw, epot, ekin, epot + ekin]
            
            if save:
                log_f   =   open(mdlogfile, 'a')
                stringi =   ''
                for k,d in enumerate(data):
                    if k == 0:           
                        stringi += '%.2f ' %d
                    elif k == 1:
                        stringi += '%.6f ' %d
                    else:
                        stringi += '%.12f ' %d
                
                log_f.write(stringi +  '\n')
                log_f.close()
                  

            n += 1
        
        
        if save and T != 0 and i*dt == tau:
            log_f   =   open(mdlogfile, 'a')
            log_f.write('# Thermalization complete. ' +  '\n')
            log_f.close()
            
            
        if 1e2 <= M:    
            if i%(int(M/100)) == 0: print 'ready = %.1f' %(i/(int(M/100))) + '%' 
Exemple #53
0
# Make a mask of zeros and ones that select fixed atoms (the
# two bottom layers):
mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h
constraint = FixAtoms(mask=mask)
print mask

for image in images:
    # Let all images use an EMT calculator:
    image.set_calculator(EMT())
    image.set_constraint(constraint)

# Relax the initial and final states:
QuasiNewton(initial).run(fmax=0.05)
QuasiNewton(final).run(fmax=0.05)

# Create a Nudged Elastic Band:
neb = NEB(images)

# Make a starting guess for the minimum energy path (a straight line
# from the initial to the final state):
neb.interpolate()

# Relax the NEB path:
minimizer = BFGS(neb)
minimizer.run(fmax=0.05)

# Write the path to a trajectory:
view(images)  # 126 meV
write('jump1.traj', images)
def shearDyn(params_set, pot_key, save = False):
    
    bond    =   params_set['bond']
    T       =   params_set['T']
    taito   =   params_set['taito']
    dt, fric=   params_set['dt'], params_set['fric']
    tau     =   params_set['tau']
    vmax    =   params_set['vmax']
    vMAX    =   params_set['vMAX']
    thres_Z =   params_set['thresZ']
    width   =   params_set['width']
    ratio   =   params_set['ratio']
    edge    =   params_set['edge']
    
    
    
    atoms, L, W, length_int, b_idxs     =   \
            create_stucture(ratio, width, edge, key = 'top', a = bond)
    
    mdfile, mdlogfile, mdrelax, simulfile, folder, relaxed \
                        =   get_fileName(pot_key, edge + '_twistRod', width, \
                                        length_int, vmax * 1000, int(T), taito)
    
    
    #view(atoms)
    # FIXES
    constraints, add_pot, twist, rend_b, rend_t =   \
            get_constraints(atoms, edge, bond, b_idxs, \
                            key = 'twist_p', pot = pot_key)
    # END FIXES

    if relaxed:
        atoms   =   PickleTrajectory(mdrelax, 'r')[-1]
    else:
        trans   =   trans_atomsKC(atoms.positions[rend_b], edge, bond)
        atoms.translate(trans) 
    
    #plot_posits(atoms, edge, bond)
    
    # CALCULATOR LAMMPS 
    calc    =   LAMMPS(parameters=get_lammps_params()) 
    atoms.set_calculator(calc)
    # END CALCULATOR
    
    # TRAJECTORY
    if save:    traj    =   PickleTrajectory(mdfile, 'w', atoms)
    else:       traj    =   None
    
    #data    =   np.zeros((M/interval, 5))
    
    # RELAX
    atoms.set_constraint(add_pot)
    dyn     =   BFGS(atoms, trajectory = mdrelax)
    dyn.run(fmax=0.05)

    dist    =   np.linalg.norm(atoms.positions[rend_b] - atoms.positions[rend_t])
    twist.set_dist(dist)
    # FIX AFTER RELAXATION
    atoms.set_constraint(constraints)
    
    # DYNAMICS
    dyn     =   Langevin(atoms, dt*units.fs, T*units.kB, fric)
    header  =   '#t [fs], shift y [Angstrom], Rad, theta [rad], hmax [A], epot_tot [eV], ekin_tot [eV], etot_tot [eV], F [eV/angst] \n'
    write_line_own(mdlogfile, header, 'w')

    if T != 0:
        # put initial MaxwellBoltzmann velocity distribution
        mbd(atoms, T*units.kB)
    
    y0          =   atoms.positions[rend_b, 1]
    
    kink_formed =   False
    kink_vanished   =   False
    i           =   0
    print 'width = %i, length = %i, v=%.6f' %(width, length_int, vmax)
    
    
    M_therm     =   int(tau / dt)
    dyn.run(M_therm)
    
    M               =   int(2 * L / (np.pi * dt * vmax))
    M_min           =   int(2 * L / (np.pi * dt * vMAX))
    dtheta          =   np.pi / 2 / M
    dtheta_max      =   np.pi / 2 / M_min
    
    interval        =   int( M / 1000 ) 
    theta, time, m  =   0., 0., 0
    i_kink          =   0
    
    
    while 0. <= theta:
        
        if not kink_formed:
            if theta < np.pi/4:
                theta      +=   dtheta_max
            else:
                theta      +=   dtheta
            twist.set_angle(theta)
        else:
            if i_kink / 10 < m: 
                theta      -=   dtheta
                twist.set_angle(theta)
            
        dyn.run(1)
        
        if i % interval == 0:
            epot, ekin  =   saveAndPrint(atoms, traj, False)[:2]
            deltaY      =   atoms.positions[rend_b, 1] - y0
            
            hmax        =   np.max(atoms.positions[:,2]) #substract the height of the plane?
            R           =   get_R(L, deltaY)
            data        =   [time, deltaY, R, theta, hmax, epot, ekin, epot + ekin]
            
            if save:
                stringi =   ''
                for k,d in enumerate(data):
                    if k == 0:           
                        stringi += '%.2f ' %d
                    elif k == 1 or k == 2:
                        stringi += '%.4f ' %d
                    else:
                        stringi += '%.12f ' %d
                write_line_own(mdlogfile, stringi +  '\n', 'a')
        
            if thres_Z  <   hmax and not kink_formed:
                idxs    =   np.where(thres_Z < atoms.positions[:,2])
                write_line_own(mdlogfile, '# Kink! at idxs %s' %str(idxs) +  '\n', 'a')
                print ' kink formed! ' + str(i / interval)
                kink_formed     =   True
                i_kink  =   i
                
            if hmax < 3.6 and kink_formed and not kink_vanished:
                write_line_own(mdlogfile, '# Kink vanished! \n', 'a')
                print ' kink vanished '
                kink_vanished   =   True


            print i/interval, theta / (2*np.pi) * 360, R
        
        if kink_formed: m += 1
        
        i      +=   1
        time   +=   dt     

    
    make_simul_param_file(simulfile, W, L, width, length_int, dtheta/dt, dtheta, T, \
                          dt, fric, thres_Z, interval, deltaY, theta, i, edge)
    
    return folder
Exemple #55
0
nimages = 3

print [a.get_potential_energy() for a in PickleTrajectory('H.traj')]
images = [PickleTrajectory('H.traj')[-1]]
for i in range(nimages):
    images.append(images[0].copy())
images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
neb = NEB(images)
neb.interpolate()

for image in images[1:]:
    image.set_calculator(Calculator())

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

dyn.run(fmax=fmax)

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

results = [images[2].get_potential_energy()]

def run_neb_calculation(cpu):
    images = [PickleTrajectory('H.traj')[-1]]
    for i in range(nimages):
        images.append(images[0].copy())
    images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
    neb = NEB(images, parallel=True, world=cpu)
    neb.interpolate()

    images[cpu.rank + 1].set_calculator(Calculator())
Exemple #56
0
def find_adhesion_potential(params):
    
    bond    =   params['bond']
    a       =   np.sqrt(3)*bond # 2.462
    h       =   params['h']
    CperArea=   (a**2*np.sqrt(3)/4)**(-1)
    
    atoms   =   make_graphene_slab(a,h,width,length,N, (True, True, False))[3]
    
    # FIX
    constraints =   []
    top         =   get_mask(atoms.positions.copy(), 'top', 1, h)
    
    bottom      =   np.logical_not(top)
    fix_bot     =   FixAtoms(mask = bottom)
    constraints.append(fix_bot)
    # END FIX
    
    # DEF CALC AND RELAX
    parameters = {'pair_style':'airebo 3.0',
                  'pair_coeff':['* * CH.airebo C'],
                  'mass'      :['* 12.01'],
                  'units'     :'metal', 
                  'boundary'  :'p p f'}
    
    calc    =   LAMMPS(parameters=parameters) #, files=['lammps.data'])
    atoms.set_calculator(calc)
    
    dyn     =   BFGS(atoms)
    dyn.run(fmax=0.05)
    # SLAB IS RELAXED
    
    atoms.set_constraint(constraints)
    zmax    =   np.amax(atoms.positions[bottom][:,2])
    
    natoms  =   0
    for i in range(len(top)):
        if top[i]: natoms += 1
    
    def get_epot(z):
        
        new_pos     =   atoms.positions.copy()
        for iat in range(len(atoms)):
            if top[iat]:
                new_pos[iat][2] = z
        
        atoms.positions =   new_pos
        return atoms.get_potential_energy()/natoms  

    
    def lj(z):
        
        ecc     =   0.002843732471143
        sigmacc =   3.4
        return 2./5*np.pi*CperArea*ecc*(2*(sigmacc**6/z**5)**2 - 5*(sigmacc**3/z**2)**2), \
            8.*ecc*CperArea*np.pi*(sigmacc**12/z**11 - sigmacc**6/z**5)
    
    # Start to move the top layer in z direction
    zrange  =   np.linspace(h - .7, h + 8, 100)
    adh_pot =   np.zeros((len(zrange), 2))
    
    for i, z in enumerate(zrange):
        adh_pot[i]  =   [z, get_epot(zmax + z)]
    
    adh_pot[:,1]    =   adh_pot[:,1] - np.min(adh_pot[:,1])   
    hmin            =   adh_pot[np.where(adh_pot[:,1] == np.min(adh_pot[:,1]))[0][0], 0]
    
    np.savetxt('adh_potential.gz', adh_pot, fmt='%.12f')
        
    fig         =   plt.figure()
    ax          =   fig.add_subplot(111)
    
    ax.plot(adh_pot[:,0], adh_pot[:,1], label = 'lamps')
    ax.plot(zrange, lj(zrange)[0] - np.min(lj(zrange)[0]), label = 'lj')
    ax.plot(zrange, lj(zrange)[1], label = 'lj')
    
    ax.scatter(hmin, 0)

    ax.set_title('Adhesion energy')
    ax.set_xlabel('height, Angst')
    ax.set_ylabel('Pot. E, eV')
    plt.legend(frameon = False)
    plt.savefig('Adhesion_energy.svg')
    plt.show()
comp = InteratomicDistanceComparator(n_top=n_to_optimize, pair_cor_cum_diff=0.015, pair_cor_max=0.7, dE=0.02, mic=False)

pairing = CutAndSplicePairing(slab, n_to_optimize, blmin)
mutations = OperationSelector(
    [1.0, 1.0, 1.0],
    [MirrorMutation(blmin, n_to_optimize), RattleMutation(blmin, n_to_optimize), PermutationMutation(n_to_optimize)],
)

# Relax all unrelaxed structures (e.g. the starting population)
while da.get_number_of_unrelaxed_candidates() > 0:
    a = da.get_an_unrelaxed_candidate()
    a.set_calculator(EMT())
    print("Relaxing starting candidate {0}".format(a.info["confid"]))
    dyn = BFGS(a, trajectory=None, logfile=None)
    dyn.run(fmax=0.05, steps=100)
    a.set_raw_score(-a.get_potential_energy())
    da.add_relaxed_step(a)

# create the population
population = Population(data_connection=da, population_size=population_size, comparator=comp)

# test n_to_test new candidates
for i in xrange(n_to_test):
    print("Now starting configuration number {0}".format(i))
    a1, a2 = population.get_two_candidates()
    a3, desc = pairing.get_new_individual([a1, a2])
    if a3 == None:
        continue
    da.add_unrelaxed_candidate(a3, description=desc)
Exemple #58
0
constraint = FixAtoms(indices=[1, 3])  # fix OO
for image in images:
    image.set_calculator(EMT())
    image.set_constraint(constraint)

for image in images:  # O-H(shared) distance
    print(image.get_distance(1, 2), image.get_potential_energy())

# Relax initial and final states:
if 1:
    # XXX: Warning:
    # One would have to optimize more tightly in order to get
    # symmetric anion from both images[0] and [1], but
    # if one optimizes tightly one gets rotated(H2O) ... OH- instead
    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.get_distance(1, 2), image.get_potential_energy())

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

for image in images:
    print(image.get_distance(1, 2), image.get_potential_energy())
import os

from ase.io import read
from ase.neb import NEB
from ase.calculators.turbomole import Turbomole
from ase.optimize import BFGS

initial = read('initial.coord')
final = read('final.coord')
os.system('rm -f coord; cp initial.coord coord')

# Make a band consisting of 5 configs:
configs = [initial]
configs += [initial.copy() for i in range(3)]
configs += [final]

band = NEB(configs, climb=True)
# Interpolate linearly the positions of the not-endpoint-configs:
band.interpolate()

#Set calculators
for config in configs:
    config.set_calculator(Turbomole())

# Optimize the Path:
relax = BFGS(band, trajectory='neb.traj')
relax.run(fmax=0.05)