Exemplo n.º 1
0
def apply_constraints(mol_frm_tmp):
    constraint_list = []
    mol_indices = []
    top_layer_indices = []
    bottom_layer_indices = []

    for atm in mol_frm_tmp:
        if atm.symbol != 'Mo' and atm.symbol != 'S':
            atm.position += frmwrk_com
            mol_indices.append(atm.index)
        else:
            if atm.position[-1] > frmwrk_com[-1]:
                top_layer_indices.append(atm.index)
            else:
                bottom_layer_indices.append(atm.index)

    #Fix molecule to midpoint of bilayer
    com_constraint = FixedPlane(mol_indices, [0, 0, 1])
    top_layer = FixedPlane(top_layer_indices, [0, 0, 1])
    bottom_layer = FixAtoms(bottom_layer_indices)
    constraint_list.append(com_constraint)
    constraint_list.append(top_layer)
    constraint_list.append(bottom_layer)

    #Set constraints
    mol_frm_tmp.set_constraint(constraint_list)

    return mol_frm_tmp
Exemplo n.º 2
0
def get_atoms():
    srf = Atoms('Cu64', [(1.2763, 1.2763, 4.0000), (3.8290, 1.2763, 4.0000),
                         (6.3816, 1.2763, 4.0000), (8.9343, 1.2763, 4.0000),
                         (1.2763, 3.8290, 4.0000), (3.8290, 3.8290, 4.0000),
                         (6.3816, 3.8290, 4.0000), (8.9343, 3.8290, 4.0000),
                         (1.2763, 6.3816, 4.0000), (3.8290, 6.3816, 4.0000),
                         (6.3816, 6.3816, 4.0000), (8.9343, 6.3816, 4.0000),
                         (1.2763, 8.9343, 4.0000), (3.8290, 8.9343, 4.0000),
                         (6.3816, 8.9343, 4.0000), (8.9343, 8.9343, 4.0000),
                         (0.0000, 0.0000, 5.8050), (2.5527, 0.0000, 5.8050),
                         (5.1053, 0.0000, 5.8050), (7.6580, 0.0000, 5.8050),
                         (0.0000, 2.5527, 5.8050), (2.5527, 2.5527, 5.8050),
                         (5.1053, 2.5527, 5.8050), (7.6580, 2.5527, 5.8050),
                         (0.0000, 5.1053, 5.8050), (2.5527, 5.1053, 5.8050),
                         (5.1053, 5.1053, 5.8050), (7.6580, 5.1053, 5.8050),
                         (0.0000, 7.6580, 5.8050), (2.5527, 7.6580, 5.8050),
                         (5.1053, 7.6580, 5.8050), (7.6580, 7.6580, 5.8050),
                         (1.2409, 1.2409, 7.6081), (3.7731, 1.2803, 7.6603),
                         (6.3219, 1.3241, 7.6442), (8.8935, 1.2669, 7.6189),
                         (1.2803, 3.7731, 7.6603), (3.8188, 3.8188, 7.5870),
                         (6.3457, 3.8718, 7.6649), (8.9174, 3.8340, 7.5976),
                         (1.3241, 6.3219, 7.6442), (3.8718, 6.3457, 7.6649),
                         (6.3945, 6.3945, 7.6495), (8.9576, 6.3976, 7.6213),
                         (1.2669, 8.8935, 7.6189), (3.8340, 8.9174, 7.5976),
                         (6.3976, 8.9576, 7.6213), (8.9367, 8.9367, 7.6539),
                         (0.0582, 0.0582, 9.4227), (2.5965, -0.2051, 9.4199),
                         (5.1282, 0.0663, 9.4037), (7.6808, -0.0157, 9.4235),
                         (-0.2051, 2.5965, 9.4199), (2.1913, 2.1913, 9.6123),
                         (5.0046, 2.5955, 9.4873), (7.5409, 2.5336, 9.4126),
                         (0.0663, 5.1282, 9.4037), (2.5955, 5.0046, 9.4873),
                         (5.3381, 5.3381, 9.6106), (7.8015, 5.0682, 9.4237),
                         (-0.0157, 7.6808, 9.4235), (2.5336, 7.5409, 9.4126),
                         (5.0682, 7.8015, 9.4237), (7.6155, 7.6155, 9.4317)])
    c2 = Atoms('C2', [(3.2897, 3.2897, 10.6627), (4.2113, 4.2113, 10.6493)])
    srf.extend(c2)
    srf.pbc = (1, 1, 0)
    srf.set_cell([10.2106, 10.2106, 20.6572], scale_atoms=False)

    mask = [a.index < 32 for a in srf]
    c1 = FixedPlane(-1, (1 / np.sqrt(2), 1 / np.sqrt(2), 1))
    c2 = FixedPlane(-2, (1 / np.sqrt(2), 1 / np.sqrt(2), 1))
    constraint = FixAtoms(mask=mask)
    srf.set_constraint([constraint, c1, c2])
    return srf
Exemplo n.º 3
0
def test_siesta_zmat():
    import os
    from ase.calculators.siesta.siesta import Siesta
    from ase.constraints import FixAtoms, FixedLine, FixedPlane
    from ase import Atoms

    pseudo_path = 'pseudos'
    if not os.path.exists(pseudo_path): os.makedirs(pseudo_path)

    # Make dummy pseudopotentials.
    for symbol in 'HCO':
        with open('{0}/{1}.lda.psf'.format(pseudo_path, symbol), 'w') as fd:
            fd.close()

    atoms = Atoms('CO2', [(0.0, 0.0, 0.0), (-1.178, 0.0, 0.0),
                          (1.178, 0.0, 0.0)])

    c1 = FixAtoms(indices=[0])
    c2 = FixedLine(1, [0.0, 1.0, 0.0])
    c3 = FixedPlane(2, [1.0, 0.0, 0.0])

    atoms.set_constraint([c1, c2, c3])

    custom_dir = './dir1/'

    # Test simple fdf-argument case.
    siesta = Siesta(label=custom_dir + 'test_label',
                    symlink_pseudos=False,
                    atomic_coord_format='zmatrix',
                    fdf_arguments={
                        'MD.TypeOfRun': 'CG',
                        'MD.NumCGsteps': 1000
                    })

    atoms.set_calculator(siesta)
    siesta.write_input(atoms, properties=['energy'])

    assert os.path.isfile(os.path.join(custom_dir, 'C.lda.1.psf'))
    assert os.path.isfile(os.path.join(custom_dir, 'O.lda.2.psf'))

    with open(os.path.join(custom_dir, 'test_label.fdf'), 'r') as fd:
        lines = fd.readlines()
    lsl = [line.split() for line in lines]
    assert ['cartesian'] in lsl
    assert ['%block', 'Zmatrix'] in lsl
    assert ['%endblock', 'Zmatrix'] in lsl
    assert ['MD.TypeOfRun', 'CG'] in lsl
    assert any(
        [line.split()[4:9] == ['0', '0', '0', '1', 'C'] for line in lines])
    assert any(
        [line.split()[4:9] == ['0', '1', '0', '2', 'O'] for line in lines])
    assert any(
        [line.split()[4:9] == ['0', '1', '1', '3', 'O'] for line in lines])
Exemplo n.º 4
0
def traj(tmpdir_factory):
    slab = fcc100('Al', size=(2, 2, 3))
    add_adsorbate(slab, 'Au', 1.7, 'hollow')
    slab.center(axis=2, vacuum=4.0)
    mask = [atom.tag > 1 for atom in slab]
    fixlayers = FixAtoms(mask=mask)
    plane = FixedPlane(-1, (1, 0, 0))
    slab.set_constraint([fixlayers, plane])
    slab.set_calculator(EMT())

    fn = tmpdir_factory.mktemp("data").join("AlAu.traj")  # see /tmp/pytest-xx
    qn = QuasiNewton(slab, trajectory=str(fn))
    qn.run(fmax=0.02)
    return fn
Exemplo n.º 5
0
def traj(tmp_path_factory):
    slab = fcc100('Al', size=(2, 2, 3))
    add_adsorbate(slab, 'Au', 1.7, 'hollow')
    slab.center(axis=2, vacuum=4.0)
    mask = [atom.tag > 1 for atom in slab]
    fixlayers = FixAtoms(mask=mask)
    plane = FixedPlane(-1, (1, 0, 0))
    slab.set_constraint([fixlayers, plane])
    slab.calc = EMT()

    temp_path = tmp_path_factory.mktemp("data")
    trajectory = temp_path / 'AlAu.traj'
    qn = QuasiNewton(slab, trajectory=str(trajectory))
    qn.run(fmax=0.02)
    return str(trajectory)
Exemplo n.º 6
0
def slabCalculation():
    slab = fcc100('Al', size=(2, 2, 3))
    add_adsorbate(slab, 'Au', 1.7, 'hollow')
    slab.center(axis=2, vacuum=4.0)

    # Make sure the structure is correct:
    #from ase.visualize import view
    #view(slab)

    # Fix second and third layers:
    mask = [atom.tag > 1 for atom in slab]
    #print mask
    fixlayers = FixAtoms(mask=mask)

    # Constrain the last atom (Au atom) to move only in the yz-plane:
    plane = FixedPlane(-1, (1, 0, 0))

    slab.set_constraint([fixlayers, plane])

    print(slab.cell / Bohr)
Exemplo n.º 7
0
def test_siesta_zmat(siesta_factory):
    atoms = Atoms('CO2', [(0.0, 0.0, 0.0), (-1.178, 0.0, 0.0),
                          (1.178, 0.0, 0.0)])

    c1 = FixAtoms(indices=[0])
    c2 = FixedLine(1, [0.0, 1.0, 0.0])
    c3 = FixedPlane(2, [1.0, 0.0, 0.0])

    atoms.set_constraint([c1, c2, c3])

    custom_dir = './dir1/'

    # Test simple fdf-argument case.
    siesta = siesta_factory.calc(label=custom_dir + 'test_label',
                                 symlink_pseudos=False,
                                 atomic_coord_format='zmatrix',
                                 fdf_arguments={
                                     'MD.TypeOfRun': 'CG',
                                     'MD.NumCGsteps': 1000
                                 })

    atoms.calc = siesta
    siesta.write_input(atoms, properties=['energy'])

    with open(os.path.join(custom_dir, 'test_label.fdf'), 'r') as fd:
        lines = fd.readlines()
    lsl = [line.split() for line in lines]
    assert ['cartesian'] in lsl
    assert ['%block', 'Zmatrix'] in lsl
    assert ['%endblock', 'Zmatrix'] in lsl
    assert ['MD.TypeOfRun', 'CG'] in lsl
    assert any(
        [line.split()[4:9] == ['0', '0', '0', '1', 'C'] for line in lines])
    assert any(
        [line.split()[4:9] == ['0', '1', '0', '2', 'O'] for line in lines])
    assert any(
        [line.split()[4:9] == ['0', '1', '1', '3', 'O'] for line in lines])
Exemplo n.º 8
0
from ase.optimize import QuasiNewton

# 2x2-Al(001) surface with 3 layers and an
# Au atom adsorbed in a hollow site:
slab = fcc100('Al', size=(2, 2, 3))
add_adsorbate(slab, 'Au', 1.7, 'hollow')
slab.center(axis=2, vacuum=4.0)

# Make sure the structure is correct:
#from ase.visualize import view
#view(slab)

# Fix second and third layers:
mask = [atom.tag > 1 for atom in slab]
#print mask
fixlayers = FixAtoms(mask=mask)

# Constrain the last atom (Au atom) to move only in the yz-plane:
plane = FixedPlane(-1, (1, 0, 0))

slab.set_constraint([fixlayers, plane])

# Use EMT potential:
slab.set_calculator(EMT())

for i in range(5):
    qn = QuasiNewton(slab, trajectory='mep%d.traj' % i)
    qn.run(fmax=0.05)
    # Move gold atom along x-axis:
    slab[-1].x += slab.get_cell()[0, 0] / 8
Exemplo n.º 9
0
    return x_grid,y_grid,z_grid
    
c = []
# Read initial and final states:
initial = read_vasp('POSCAR')
pos = initial.get_positions()
ucell = initial.get_cell()
type = initial.get_chemical_symbols()
atoms = Atoms(positions=pos, symbols=type, cell=ucell, pbc=[True,True,True])

#c = FixAtoms(indices=[atom.index for atom in atoms if atom.symbol == 'Hf'])

#                """Constrain an atom index *a* to move in a given plane only.
#for atom in atoms:
#	c.append( FixedPlane(atom.index, ( 0, 0, 1)) )
c = [ FixedPlane( atom.index, ( 0, 0, 1) )  for atom in atoms ]
atoms.set_constraint(c)

write_vasp("OUT.vasp", atoms=atoms, vasp5=True, ignore_constraints=False)
#print (c)
fig = plt.figure()
ax = fig.add_subplot(111)
#ax.set_aspect("auto")
ax.set(xlim=(-1, 1), ylim = (-1, 1) )
a_circle = plt.Circle((23, 11.7), 2.7, alpha = 0.5,fill=False, ec='red')
a1_circle = plt.Circle((23, 11.7), 0.2,fill=False, ec='red')
ax.add_artist(a_circle)
ax.add_artist(a1_circle)
plot_atoms(atoms, ax, radii=0.5, rotation=('0x,0y,00z'))
plt.savefig("test.eps", format="eps", dpi=600)
plt.show()
benz.set_pbc(False)
tags = np.zeros_like(benz)
benz.set_tags(tags)
benz.center(vacuum=4.0)
cell = benz.get_cell()

calc = GPAW(nbands=-1,
            h=h,
            xc=xc,
            occupations=FermiDirac(0.0),
            txt=molname + '_relax.txt')
benz.set_calculator(calc)

# qn constraint
for i in range(len(benz)):
    plane = FixedPlane(i, (0, 0, 1))
    benz.set_constraint(plane)

qn = QuasiNewton(benz,
                 logfile=molname + '_relax.log',
                 trajectory=molname + '_relax.traj')
qn.run(fmax=0.01)

e_mol = benz.get_potential_energy()
del calc

#-------------------------------------
# mapping out the benzene dimer (T-shaped) intermolecular distance

e_array = np.zeros(20)
d_array = np.zeros(20)
Exemplo n.º 11
0
                     (6.3976, 8.9576, 7.6213), (8.9367, 8.9367, 7.6539),
                     (0.0582, 0.0582, 9.4227), (2.5965, -0.2051, 9.4199),
                     (5.1282, 0.0663, 9.4037), (7.6808, -0.0157, 9.4235),
                     (-0.2051, 2.5965, 9.4199), (2.1913, 2.1913, 9.6123),
                     (5.0046, 2.5955, 9.4873), (7.5409, 2.5336, 9.4126),
                     (0.0663, 5.1282, 9.4037), (2.5955, 5.0046, 9.4873),
                     (5.3381, 5.3381, 9.6106), (7.8015, 5.0682, 9.4237),
                     (-0.0157, 7.6808, 9.4235), (2.5336, 7.5409, 9.4126),
                     (5.0682, 7.8015, 9.4237), (7.6155, 7.6155, 9.4317)])
c2 = Atoms('C2', [(3.2897, 3.2897, 10.6627), (4.2113, 4.2113, 10.6493)])
srf.extend(c2)
srf.pbc = (1, 1, 0)
srf.set_cell([10.2106, 10.2106, 20.6572], scale_atoms=False)

mask = [a.index < 32 for a in srf]
c1 = FixedPlane(-1, (1 / np.sqrt(2), 1 / np.sqrt(2), 1))
c2 = FixedPlane(-2, (1 / np.sqrt(2), 1 / np.sqrt(2), 1))
constraint = FixAtoms(mask=mask)
srf.set_constraint([constraint, c1, c2])
systems.append((srf, 'C2/Cu(100)'))


def create_database():
    db = connect('systems.db', append=False)
    for atoms, description in systems:
        db.write(atoms, description=description)


if __name__ == '__main__':
    create_database()
Exemplo n.º 12
0
def do_one_interstitial(bulk_supercell,
                        bulk_supercell_pe,
                        interstitial_Z,
                        interstitial_pos,
                        label,
                        relax_radial=0.0,
                        relax_symm_break=0.0,
                        nn_cutoff=0.0,
                        tol=1.0e-2):

    interst = bulk_supercell.copy()
    interst += Atoms(numbers=[interstitial_Z], positions=[interstitial_pos])
    interstitial_i = len(interst) - 1

    if relax_radial != 0.0 or relax_symm_break != 0.0:
        nl = NeighborList([nn_cutoff / 2.0] * len(bulk_supercell),
                          self_interaction=False,
                          bothways=True)
        nl.update(bulk_supercell)
        indices, offsets = nl.get_neighbors(interstitial_i)
        offset_factor = relax_radial
        for i, offset in zip(indices, offsets):
            ri = interst.positions[interstitial_i] - (
                interst.positions[i] + np.dot(offset, interst.get_cell()))
            interst.positions[i] += offset_factor * ri
            offset_factor += relax_symm_break

    if "interstitial_constraint" in bulk_supercell.info:
        (constr_type, constr_subtype
         ) = bulk_supercell.info["interstitial_constraint"].split()[0:2]

        if constr_type == "plane":
            if constr_subtype == "atoms":
                indices = [
                    int(i) for i in
                    bulk_supercell.info["interstitial_constraint"].split()[2:]
                ]
                if len(indices) != 3:
                    raise ValueError(
                        "number of indices not 3 for plane atoms '{}'".format(
                            bulk_supercell.info["interstitial_constraint"]))
                p = interst.get_positions()
                constr_normal = np.cross(p[indices[0]] - p[indices[1]],
                                         p[indices[0]] - p[indices[2]])
            elif constr_subtype == "vector":
                constr_normal = np.array(
                    bulk_supercell.info["interstitial_constraint"].split()[2:])
            else:
                raise ValueError(
                    "unknown interstitial constraint subtype for plane '{}'".
                    format(bulk_supercell.info["interstitial_constraint"]))

            print("setting constraint FixedPlane with normal", constr_normal)
            interst.set_constraint(FixedPlane(interstitial_i, constr_normal))
        else:
            raise ValueError(
                "unknown interstitial constraint type '{}'".format(
                    bulk_supercell.info["interstitial_constraint"]))

    evaluate(interst)
    unrelaxed_interstitial_pe = interst.get_potential_energy()

    if len(set(bulk_supercell.get_atomic_numbers())) == 1:
        Ebulk = float(len(interst)) / float(
            len(bulk_supercell)) * bulk_supercell_pe
    else:
        Ebulk = bulk_supercell_pe
    Ef0 = unrelaxed_interstitial_pe - Ebulk

    unrelaxed_filename = run_root + "-%s-unrelaxed.xyz" % label
    ase.io.write(os.path.join("..", unrelaxed_filename),
                 interst,
                 format='extxyz')

    print("got unrelaxed interstitial {} cell energy".format(label),
          unrelaxed_interstitial_pe)

    try:
        interst = relax_config(interst,
                               relax_pos=True,
                               relax_cell=False,
                               tol=tol,
                               save_traj=True,
                               config_label=label,
                               from_base_model=True,
                               save_config=True,
                               try_restart=True)

        relaxed_filename = run_root + "-%s-relaxed.xyz" % label
        ase.io.write(os.path.join("..", relaxed_filename),
                     interst,
                     format='extxyz')

        interstitial_pe = interst.get_potential_energy()
        Ef = interstitial_pe - Ebulk

        print("got relaxed interstitial {} cell energy".format(label),
              interstitial_pe)
    except:
        relaxed_filename = None
        Ef = None

    print("got bulk energy", Ebulk)
    return (unrelaxed_filename, Ef0, relaxed_filename, Ef, interstitial_i)
Exemplo n.º 13
0
def get_YoungAndTau3():
    wis = range(
        4, 120)  #[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,25,28,30]
    #wYt     =   np.zeros((len(wis), 4))
    path_f = '/space/tohekorh/ShearSlide/pictures/Ytau3/%s/' % edge

    wYt = np.zeros((len(wis) - len(bad_wis), 4))
    j = 0

    for wi in wis:
        if wi not in bad_wis:
            print 'width %i' % wi
            atoms, fid = get_atoms(wi)
            constraints = []
            constraints.append(FixAtoms(indices=[0]))
            for k in range(len(atoms)):
                constraints.append(FixedPlane(k, [0, 0, 1]))

            atoms.set_constraint(constraints)

            # CALCULATOR
            calc = LAMMPS(parameters=parameters)
            atoms.set_calculator(calc)

            dyn = BFGS(
                atoms,
                logfile='/space/tohekorh/log_useless.log',
                trajectory='/space/tohekorh/ShearSlide/opm_dx=%.3f_%s.traj' %
                (dx, edge))
            dyn.run(fmax=fmax, steps=maxSteps)

            dedx = derivative(energy,
                              l0,
                              dx=dx,
                              n=1,
                              order=21,
                              args=(atoms, dyn))

            tau = dedx / 2.
            cparams.set_tau(tau)
            print 'edge stress %s eV/Angst = %.3f' % (edge, tau)

            qopm_l = (-2 * tau / (21 * cparams.get_w()) + 1) * l0

            energy(qopm_l, atoms, dyn)
            init_pos = atoms.positions.copy()

            lxs_stre = np.linspace(1. * qopm_l, (1. + perVal) * qopm_l, N)
            lxs_comp = np.linspace(1. * qopm_l, (1 - perVal) * qopm_l, N)

            lxs = np.zeros(2 * N - 1)
            energies = np.zeros(2 * N - 1)

            cparams.set_w(wi)

            n = 0
            for lx in lxs_stre:
                print lx / qopm_l
                energies[n] = energy(lx, atoms, dyn)
                lxs[n] = lx
                n += 1

            atoms.positions = init_pos
            for lx in lxs_comp[1:]:
                print lx / qopm_l
                energies[n] = energy(lx, atoms, dyn)
                lxs[n] = lx
                n += 1

            eps = (lxs - l0) / l0

            atoms.positions = init_pos
            e0 = energy(l0, atoms, dyn)
            energies -= e0

            Y_opm = curve_fit(energy_teor3, eps, energies, p0=[21])[0][:1]

            l_opm = -2 * tau / (Y_opm * cparams.get_w()) * l0 + l0
            eps0 = l_opm / l0 - 1
            print 'Youngs mod eV/Angst2 = %.3f' % (Y_opm)

            plt.scatter(eps, energies)
            plt.plot(eps, 2 * tau * l0 * eps, label='tau = %.3f' % tau)
            #plt.plot(eps, dedx*eps*l0, label = 'tau = %.3f' %tau)

            plot_eps = np.linspace(np.min(eps), np.max(eps), 200)
            plt.plot(plot_eps,
                     energy_teor3(plot_eps, Y_opm),
                     '-',
                     color='black',
                     label='fit, Y = %.3f eV/angst2' % (Y_opm))

            #        plt.plot([l_opm,l_opm], [-.1*np.max(energies), .1*np.max(energies)], '--',
            #                color = 'black', label = 'eps_opm = %.4f' %(l_opm/l0 - l0))
            plt.plot([0, 0], [-.1 * np.max(energies), .1 * np.max(energies)],
                     '--',
                     color='black')
            plt.plot([eps0, eps0],
                     [-.1 * np.max(energies), .1 * np.max(energies)],
                     '--',
                     color='black',
                     label='eps0 = %.5f' % (eps0))
            plt.legend(frameon=False)
            #plt.show()
            plt.savefig(path_f + 'w=%i_dx=%.3f.png' % (wi, dx))
            plt.clf()

            wYt[j] = [cparams.get_w(), Y_opm, tau, eps0]

            plt.scatter(wYt[:j + 1, 0],
                        wYt[:j + 1, 1],
                        label='Y',
                        color='black')
            plt.legend(loc=2, frameon=False)
            plt.twinx()
            plt.plot(wYt[:j + 1, 0], wYt[:j + 1, 2], '-o', label='tau')
            plt.xlabel('width')
            plt.title('Young s modulus and edge stress')
            plt.legend(frameon=False)
            plt.savefig(path_f + 'Ytau.png')
            plt.clf()

            np.savetxt(path_f + 'Ytau.txt',
                       wYt,
                       header='width, Y, tau, eps_opm')

            #plt.show()
            j += 1
Exemplo n.º 14
0
# User inputs
input_structure = "str.cif"
atoms = read(input_structure)
maxstep = 0.1
fmaxx = 0.01

kpoints = [6, 12, 3]
gpoints = [32, 16, 72]


index = [1,1,0]



calc = GPAW(xc='BEEF-vdW', gpts=gpoints, kpts=kpoints)  #symmetry={'point_group': False})
atoms.set_calculator(calc)

# Set constraints- Fix carbon atoms, move Li,F atoms only in plane normal to displacement direction given by index
constraints = []
constraints.append(FixAtoms(indices=[atom.index for atom in atoms if atom.symbol == 'C']))
sym = atoms.get_chemical_symbols()
for i in range(len(sym)):
    if sym[i] != 'C':
        constraints.append(FixedPlane(i,index))

atoms.set_constraint(constraints)
atoms.calc.set(txt='bfgs.txt')
dyn=BFGS(atoms=atoms, trajectory='traj.traj', logfile = 'qn.log', maxstep=maxstep)
dyn.run(fmax=fmaxx)
Exemplo n.º 15
0
atoms = bulk('NaCl', crystalstructure='rocksalt', a=5) * (2, 1, 1)
atoms.set_initial_magnetic_moments([1.1] * len(atoms))
l = SPARC(atoms=atoms,
          h=0.1,
          label='in1',
          xc='GGA',
          spin_typ=1,
          pseudo_dir='.')
l.write_input(atoms=atoms, h=0.1, spin_typ=1, pseudo_dir='.', SPIN_TYP=1)

print('input writing functional')
# check reading and writing .ion files
atoms.set_constraint(
    [FixAtoms([0]),
     FixedLine(1, [0, 1, 0]),
     FixedPlane(2, [1, 0, 0])])
write_ion(open('in1.ion', 'w'), atoms, pseudo_dir='.')
recovered_atoms = read_ion(open('in1.ion', 'r'))
assert compare_atoms(atoms, recovered_atoms) == []

calc = SPARC(atoms=atoms, pseudo_dir='.', SPIN_TYP=1)
try:  # check that `h` is required
    calc.write_input()
    raise Exception('test failed')
except CalculatorSetupError:
    pass

print('.ion reading test passed')

calc = SPARC.read('read_input')
Exemplo n.º 16
0
def get_YoungAndTau():

    wis = range(5, 120)
    wYt = np.zeros((len(wis) - len(bad_wis), 4))
    j = 0

    for wi in wis:
        if wi not in bad_wis:
            print wi, edge
            atoms, fid = get_atoms(wi)
            constraints = []
            constraints.append(FixAtoms(indices=[0]))
            for k in range(len(atoms)):
                constraints.append(FixedPlane(k, [0, 0, 1]))
            #constraints.append(FixedPlane(fid[0], [0,0,1]))
            #constraints.append(FixedPlane(fid[1], [0,0,1]))

            atoms.set_constraint(constraints)

            # CALCULATOR
            calc = LAMMPS(parameters=parameters)
            atoms.set_calculator(calc)

            dyn = BFGS(
                atoms,
                trajectory='/space/tohekorh/ShearSlide/opm_dx=%.3f_%s.traj' %
                (dx, edge),
                maxstep=.01,
                logfile='/space/tohekorh/log_useless.log')
            dyn.run(fmax=fmax, steps=10 * maxSteps)

            qopm_l = (-2 * (-.2) / (21 * cparams.get_w()) + 1) * l0

            energy(qopm_l, atoms, dyn)
            init_pos = atoms.positions.copy()

            lxs_stre = np.linspace(1. * qopm_l, (1. + perVal) * qopm_l, N)
            lxs_comp = np.linspace(1. * qopm_l, (1 - perVal) * qopm_l, N)

            lxs = np.zeros(2 * N - 1)
            energies = np.zeros(2 * N - 1)

            cparams.set_w(wi)

            n = 0
            for lx in lxs_stre:
                print lx / qopm_l
                energies[n] = energy(lx, atoms, dyn)
                lxs[n] = lx
                n += 1

            atoms.positions = init_pos
            for lx in lxs_comp[1:]:
                print lx / qopm_l
                energies[n] = energy(lx, atoms, dyn)
                lxs[n] = lx
                n += 1

            energies = energies - np.min(energies)
            eps = (lxs - l0) / l0

            Y_opm, eps0 = curve_fit(energy_teor,
                                    eps,
                                    energies,
                                    p0=[21, qopm_l / l0 - 1])[0][:2]
            tau = -Y_opm * cparams.get_w() * eps0 / 2.

            plt.scatter(eps, energies)
            plt.plot([eps0, eps0],
                     [-.1 * np.max(energies), .1 * np.max(energies)],
                     '--',
                     color='black',
                     label='eps_opm = %.4f' % eps0)

            plot_eps = np.linspace(np.min(eps), np.max(eps), 200)
            plt.plot(plot_eps,
                     energy_teor(plot_eps, Y_opm, eps0),
                     '-',
                     color='black',
                     label='fit, Y = %.3f eV/angst2, \n tau = %.3f eV/Angst' %
                     (Y_opm, tau))
            plt.legend(frameon=False)
            plt.xlabel('eps')
            plt.ylabel('energy eV')
            plt.title('Energy and sheet elasticity fit to it')

            wYt[j] = [cparams.get_w(), Y_opm, tau, eps0]
            plt.savefig(
                '/space/tohekorh/ShearSlide/pictures/Ytau/%s/w=%i.png' %
                (edge, wi))
            plt.clf()

            #plt.show()

            plt.scatter(wYt[:j + 1, 0],
                        wYt[:j + 1, 1],
                        label='Y',
                        color='black')
            plt.legend(loc=2, frameon=False)
            plt.twinx()
            plt.plot(wYt[:j + 1, 0], wYt[:j + 1, 2], '-o', label='tau')
            plt.xlabel('width')
            plt.title('Young s modulus and edge stress')
            plt.legend(frameon=False)
            plt.savefig(
                '/space/tohekorh/ShearSlide/pictures/Ytau/%s/Ytau.png' % edge)
            plt.clf()

            np.savetxt('/space/tohekorh/ShearSlide/pictures/Ytau/%s/Ytau.txt' %
                       edge,
                       wYt,
                       header='width, Y, tau, eps_opm')

            j += 1
Exemplo n.º 17
0
def get_YoungAndTau2():

    wis = range(5, 120)

    path_f = '/space/tohekorh/ShearSlide/pictures/Ytau2/%s/' % edge
    wYt = np.zeros((len(wis) - len(bad_wis), 5))
    j = 0
    fa, fb = 0.09, 0

    for wi in wis:
        if wi not in bad_wis:
            print wi, edge
            atoms, fid = get_atoms(wi)
            constraints = []
            constraints.append(FixAtoms(indices=[0]))
            for k in range(len(atoms)):
                constraints.append(FixedPlane(k, [0, 0, 1]))
            #constraints.append(FixedPlane(fid[0], [0,0,1]))
            #constraints.append(FixedPlane(fid[1], [0,0,1]))

            atoms.set_constraint(constraints)

            # CALCULATOR
            calc = LAMMPS(parameters=parameters)
            atoms.set_calculator(calc)

            dyn = BFGS(
                atoms,
                trajectory='/space/tohekorh/ShearSlide/opm_dx=%.3f_%s.traj' %
                (dx, edge),
                maxstep=.01,
                logfile='/space/tohekorh/log_useless.log')
            dyn.run(fmax=fmax, steps=10 * maxSteps)
            cparams.set_w(wi)

            #derivative(energy, l0, dx=dx, n=1, order=5)

            #opm_l   =   fmin(energy, l0, xtol = 1e-6, ftol = 1e-6, args = (atoms, dyn))[0]
            cont = True
            cont = False
            try:
                #opm_l   =   fmin_cg(energy, l0, args=(atoms, dyn), gtol=1e-03,
                #                    epsilon=1.4901161193847656e-03,
                #                    full_output=0, disp=1)
                #qopm_l  =   (-2*(-.2)/(21*cparams.get_w()) + 1)*l0
                qopm_l = oneOverR(cparams.get_w(), fa, fb) * l0 + l0
                #qopm_l  =   l0

                res = minimize(energy, [qopm_l],
                               args=(atoms, dyn),
                               method='L-BFGS-B',
                               jac=None,
                               bounds=[(l0 * .995, l0 * 1.005)],
                               tol=None,
                               callback=None,
                               options={
                                   'disp': None,
                                   'iprint': -1,
                                   'gtol': 1e-012 * wi,
                                   'eps': 1e-04,
                                   'maxiter': 15,
                                   'ftol': 2.220446049250313e-09,
                                   'maxcor': 10,
                                   'maxfun': 100
                               })  #['x'][0] 'factr': 10000
                '''                
                options={'disp': None, 'iprint': -1, 
                                              'gtol': 1e-03*wi, 'eps': 1e-04, 
                                              'maxiter': 15,
                                              'ftol': 2.220446049250313e-09, 
                                              'maxcor': 10, 
                                              'maxfun': 100})
                '''
                opm_l = res['x'][0]
                eopm = res['fun']
                print 'number of iterations = %i' % res['nit']
                init_pos = atoms.positions.copy()

                cont = True
            except Exception as e:
                print e

            if cont:
                eps0 = (opm_l - l0) / l0
                print wi, opm_l, l0, opm_l - l0, eps0
                #qopm_l  =   (-2*(-.2)/(21*cparams.get_w()) + 1)*l0

                lxs_stre = np.linspace(1. * opm_l, (1. + perVal) * opm_l, N)
                lxs_comp = np.linspace(1. * opm_l, (1 - perVal) * opm_l, N)

                lxs = np.zeros(2 * N - 1)

                energies = np.zeros(2 * N - 1)

                cparams.set_eps0(eps0)

                n = 0
                for lx in lxs_stre:
                    print lx / opm_l
                    energies[n] = energy(lx, atoms, dyn)
                    lxs[n] = lx
                    n += 1

                atoms.positions = init_pos
                for lx in lxs_comp[1:]:
                    print lx / opm_l
                    energies[n] = energy(lx, atoms, dyn)
                    lxs[n] = lx
                    n += 1

                #min_e   =   energy(opm_l, atoms, dyn)
                energies = energies - np.min(energies)  #- min_e
                eps = (lxs - l0) / l0

                Y_opm = curve_fit(energy_teor2, eps, energies, p0=[21])[0][:1]
                tau = -Y_opm * cparams.get_w() * eps0 / 2
                tau2 = (eopm - energy(l0, atoms, dyn)) / (eps0 * l0)
                plt.scatter(eps, energies)
                plt.plot([eps0, eps0],
                         [-.1 * np.max(energies), .1 * np.max(energies)],
                         '--',
                         color='black',
                         label='eps_opm = %.4f' % eps0)

                plot_eps = np.linspace(np.min(eps), np.max(eps), 200)
                plt.plot(
                    plot_eps,
                    energy_teor(plot_eps, Y_opm, eps0),
                    '-',
                    color='black',
                    label='fit, Y = %.3f eV/angst2, \n tau = %.3f eV/Angst' %
                    (Y_opm, tau))
                plt.legend(frameon=False)
                plt.xlabel('eps')
                plt.ylabel('energy eV')
                plt.title('Energy and sheet elasticity fit to it')

                wYt[j] = [cparams.get_w(), Y_opm, tau, eps0, tau2]
                plt.savefig(path_f + 'w=%i.png' % wi)
                plt.clf()

                #plt.show()
                if j > 2:
                    fa, fb = curve_fit(oneOverR,
                                       wYt[:j, 0],
                                       wYt[:j, 3],
                                       p0=[1, 0])[0][:2]
                    #if j%5 == 0:
                    #    plt.scatter(wYt[:j,0], wYt[:j,3])
                    #    plt.plot(wYt[:j,0], oneOverR(wYt[:j,0], fa, fb))
                    #    plt.show()
                    #print fa, fb

                plt.scatter(wYt[:j + 1, 0],
                            wYt[:j + 1, 1],
                            label='Y',
                            color='black')
                plt.legend(loc=2, frameon=False)
                plt.twinx()
                plt.plot(wYt[:j + 1, 0], wYt[:j + 1, 2], '-o', label='tau')
                plt.plot(wYt[:j + 1, 0], wYt[:j + 1, 4], '-o', label='tau2')
                plt.xlabel('width')
                plt.title('Young s modulus and edge stress')
                plt.legend(frameon=False)
                plt.savefig(path_f + 'Ytau.png')
                plt.clf()

                #np.savetxt(path_f  + 'Ytau.txt', wYt,
                #           header = 'width, Y, tau, eps_opm')

                j += 1
Exemplo n.º 18
0
from ase.constraints import FixAtoms, FixedLine, FixedPlane
from ase import Atoms

pseudo_path = 'pseudos'
if not os.path.exists(pseudo_path): os.makedirs(pseudo_path)

# Make dummy pseudopotentials.
for symbol in 'HCO':
    with open('{0}/{1}.lda.psf'.format(pseudo_path, symbol), 'w') as fd:
        fd.close()

atoms = Atoms('CO2', [(0.0, 0.0, 0.0), (-1.178, 0.0, 0.0), (1.178, 0.0, 0.0)])

c1 = FixAtoms(indices=[0])
c2 = FixedLine(1, [0.0, 1.0, 0.0])
c3 = FixedPlane(2, [1.0, 0.0, 0.0])

atoms.set_constraint([c1, c2, c3])

custom_dir = './dir1/'

# Test simple fdf-argument case.
siesta = Siesta(label=custom_dir + 'test_label',
                symlink_pseudos=False,
                atomic_coord_format='zmatrix',
                fdf_arguments={
                    'MD.TypeOfRun': 'CG',
                    'MD.NumCGsteps': 1000
                })

atoms.set_calculator(siesta)
Exemplo n.º 19
0
def get_constraints(atoms, edge, bond, idxs, key='shear_p', pot='LJ'):

    if key == 'shear':
        # FIXES
        constraints = []
        if edge == 'zz': fixL = np.sqrt(3) * bond * .51  #1.05
        if edge == 'ac': fixL = 1.01 * bond

        rend_b, rend_t = get_posInds(atoms, 'redge')[1:]
        lend_s, lend_h = get_posInds(atoms, 'ledge', fixL)

        #view(atoms)
        if idxs == None:
            for i in lend_s:
                constraints.append(FixedLine(i, (0, 0, 1)))
            constraints.append(FixAtoms(indices=lend_h))
        else:
            for i in idxs:
                constraints.append(FixedLine(i, (0, 0, 1)))

        for i in rend_b:
            constraints.append(FixedPlane(i, (0, 1, 0)))

        # KC
        add_LJ = LJ_potential_smooth(bond)
        constraints.append(add_LJ)
        # END FIXES

        return constraints, add_LJ, rend_b, rend_t

    elif key == 'twist_F':

        # FIXES
        constraints = []
        if edge == 'zz': fixL = np.sqrt(3) * bond * 2.05
        if edge == 'ac': fixL = 5 * bond

        rend_b, rend_t = get_posInds(atoms, 'redge')[1:]
        lend_s, lend_h = get_posInds(atoms, 'ledge', fixL)

        #view(atoms)
        if idxs == None:
            for i in lend_s:
                constraints.append(FixedLine(i, (0, 0, 1)))
            constraints.append(FixAtoms(indices=lend_h))
        else:
            for i in idxs:
                constraints.append(FixedLine(i, (0, 0, 1)))

        # KC
        add_LJ = LJ_potential_smooth(bond)
        if len(rend_b) != len(rend_t) != 1: raise
        twist = twist_const_F(rend_b[0], rend_t[0], np.zeros(3))

        constraints.append(FixedPlane(rend_b[0], (0, 0, 1)))
        constraints.append(FixedPlane(rend_t[0], (0, 0, 1)))

        constraints.append(add_LJ)
        constraints.append(twist)
        # END FIXES

        return constraints, add_LJ, twist, rend_b, rend_t

    elif key == 'twist_p':

        # FIXES
        constraints = []
        if edge == 'zz': fixL = np.sqrt(3) * bond * .51
        if edge == 'ac': fixL = 1.1 * bond

        rend_b, rend_t = get_posInds(atoms, 'redge')[1:]
        lend_s, lend_h = get_posInds(atoms, 'ledge', fixL)

        #view(atoms)
        if idxs == None:
            for i in lend_s:
                constraints.append(FixedLine(i, (0, 0, 1)))
            constraints.append(FixAtoms(indices=lend_h))
        else:
            for i in idxs:
                constraints.append(FixedLine(i, (0, 0, 1)))

        # KC
        if pot == 'KC':
            params = {}
            params['positions'] = atoms.positions
            params['chemical_symbols'] = atoms.get_chemical_symbols()
            params['ia_dist'] = 10
            params['edge'] = edge
            params['bond'] = bond
            params['ncores'] = 1
            add_pot = KC_potential_p(params)

        elif pot == 'LJ':
            add_pot = LJ_potential_smooth(atoms, bond)

        if len(rend_b) != len(rend_t) != 1: raise

        #dist            =   np.linalg.norm(atoms.positions[rend_b[0]] - atoms.positions[rend_t[0]])
        #twist           =   twistConst_Rod(rend_b[0], rend_t[0], dist)
        twist = twistConst_Rod(atoms, 4, edge, bond)

        constraints.append(FixedPlane(rend_b[0], (0, 0, 1)))

        constraints.append(add_pot)
        constraints.append(twist)
        # END FIXES

        return constraints, add_pot, twist, rend_b[0], rend_t[0]