示例#1
0
文件: calc_gap.py 项目: obaica/imeall
def calc_gap():
    oraxis = '0,0,1'
    pot_param = PotentialParameters()
    ener_per_atom = pot_param.gs_ener_per_atom()
    selected_grains = GrainBoundary.select().where(
        GrainBoundary.orientation_axis == oraxis).where(
            GrainBoundary.boundary_plane != oraxis)

    f = open('./locenviron/gap_energies.dat', 'a')
    for gb in selected_grains.order_by(GrainBoundary.angle)[2:]:
        subgbs = (gb.subgrains.select(
            GrainBoundary,
            SubGrainBoundary).where(SubGrainBoundary.potential ==
                                    'PotBH.xml').join(GrainBoundary).dicts())
        subgbs = [
            (16.02 * (subgb['E_gb'] -
                      float(subgb['n_at'] * ener_per_atom['PotBH.xml'])) /
             (2.0 * subgb['area']), subgb) for subgb in subgbs
        ]
        subgbs.sort(key=lambda x: x[0])
        try:
            print subgbs[0][1]['path']
            continue

            target_dir = os.path.join('./grain_boundaries',
                                      subgbs[0][1]['path'])
            struct_file = os.path.join(target_dir,
                                       subgbs[0][1]['gbid']) + '_traj.xyz'
            print struct_file
            ats = AtomsReader(struct_file)[-1]
            pot = Potential('IP GAP', param_filename='gp33b.xml')
            ats.set_calculator(pot)
            print subgbs[0][1]['n_at'], subgbs[0][1]['area']
            strain_mask = [0, 0, 1, 0, 0, 0]
            ucf = UnitCellFilter(ats, strain_mask)
            opt = FIRE(ucf)
            FORCE_TOL = 0.1
            opt.run(fmax=FORCE_TOL)
            gap_en = ats.get_potential_energy()
            print gap_en
            print round(gb.angle * (180.0 / 3.14159), 3), round(
                subgbs[0][0], 3), 16.02 * (gap_en - float(
                    subgbs[0][1]['n_at'] * ener_per_atom['gp33b.xml'])) / (
                        2.0 * subgbs[0][1]['area'])
            print >> f, round(gb.angle * (180.0 / 3.14159), 3), round(
                subgbs[0][0], 3), 16.02 * (gap_en - float(
                    subgbs[0][1]['n_at'] * ener_per_atom['gp33b.xml'])) / (
                        2.0 * subgbs[0][1]['area'])
            ats.write('./locenviron/{}.xyz'.format(subgbs[0][1]['gbid']))
        except IndexError:
            print '\t', round(gb.angle * (180.0 / 3.14159), 3), subgbs
示例#2
0
def calc_chemoelast(input_file):
    """Adds the structure type using an ovitos script to the :py:class:`Atoms` object
    and calculates the breakdown of the energy contributions.

    Args:
      input_file(str):Relaxed grain boundary structure file.

    Returns:
      list(float):[(chemical_energy/total_energy)*gb_energy, (elastic_energy/total_energy)*gb_energy, gb_energy]
    """

    potparam = PotentialParameters()
    ener_bulk_dict = potparam.gs_ener_per_atom()
    r_scale_dict = potparam.eam_rscale()
    r_scale = r_scale_dict['PotBH.xml']
    E_bulk = ener_bulk_dict['PotBH.xml']
    try:
        POT_DIR = os.environ['POTDIR']
    except KeyError:
        sys.exit("PLEASE SET export POTDIR='path/to/potfiles/'")
    eam_pot = 'PotBH.xml'
    eam_pot = os.path.join(POT_DIR, eam_pot)
    pot = Potential(
        'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale),
        param_filename=eam_pot)
    ats = AtomsReader(input_file)[-1]
    ats.set_calculator(pot)
    gb_energy = potparam.calc_e_gb(ats, E_bulk)
    print gb_energy, 'J/^2m'
    ats.write('full.xyz')
    elastic_energy = strain_energy(ats)
    with open('elast.dat', 'w') as f:
        for x in elastic_energy:
            print >> f, x[0], x[1]


#generates output.xyz
    imeall_root = os.path.join(app.root_path, 'ovito_scripts/attach_cna.py')
    args_str = 'ovitos {imeall_root} -i {input_file}'.format(
        imeall_root=app.root_path, input_file='full.xyz').split()
    job = subprocess.Popen(args_str)
    job.wait()
    ats = Atoms('output.xyz')
    #print the three contributions
    x = calc_chemomechanical(ats)
    try:
        assert round(gb_energy, 2) == round(x[2], 2)
    except AssertionError:
        print "WARNING ENERGIES DON'T MATCH", gb_energy, x[2]
    return x
示例#3
0
def calc_elast_dipole_eam(input_file, force_tol, relax_cell):
    """
    Calculate elastic dipole using an Embedded Atom Potential.

    Args:
      input_file (str): Name of .xyz file contains unitcell with defect.
      force_tol (float): Force tolerance to stop relaxation.
      relax_cell (bool): Relax lattice vectors.

    Returns:
      Elastic Dipole Tensor 3x3 numpy array.
    """
    try:
        POT_DIR = os.environ['POTDIR']
    except KeyError:
        sys.exit("PLEASE SET export POTDIR='path/to/potfiles/'")

    elastic = ElasticDipole()

    eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
    pot = Potential(
        'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(1.00894848312),
        param_filename=eam_pot)

    ats = Atoms(input_file)
    ats.set_calculator(pot)

    init_vol = ats.get_volume()
    print 'Initial Vol.', init_vol
    elastic.relax_defect_cell(ats, force_tol=force_tol, relax_cell=relax_cell)
    final_vol = ats.get_volume()
    print 'Final Vol.', final_vol
    print 'Volume Diff.', final_vol - init_vol
    ats = Atoms('defect_cell_relaxed.xyz')
    defect = find_h_atom(ats)
    print 'Defect index', defect.index, 'Position', defect.position, 'Type: ', defect.number
    ats.set_calculator(pot)
    return elastic.compute_vacancy_dipole(defect, ats.copy(), pot)
示例#4
0
    def build_h_nebpath(self, struct_path="fe_bcc.xyz", neb_path=np.array([0.25, 0.0, -0.25]), 
                        alat=2.8297, knots=5, sup_cell=5, fmax=1.e-4):
        """
        Takes a vector neb_path, and generates n intermediate images along the minimum energy path.
        the struct path should point to the relaxed structure.
        """
        POT_DIR = os.path.join(app.root_path, 'potentials')
        eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
        r_scale = 1.00894848312
        mm_pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot)

        ats_ini = AtomsReader(struct_path)[-1]
        #Pick the top tetrahedral H position in the cell [[1,0,0],[0,1,0],[0,0,1]]
        tetra_pos = alat*np.array([0.5, 0.0, 0.75])
        mid_point = 0.5*(np.diag(ats_ini.get_cell()))
        mid_point = [((sup_cell-1)/2.)*alat for sp in range(3)]
        h_pos = tetra_pos + mid_point

        disloc_ini = ats_ini.copy()
        h_tmp = h_pos
        disloc_ini.add_atoms(np.array(h_tmp), 1)

        disloc_fin = ats_ini.copy()
        h_tmp = h_pos + neb_path*alat
        disloc_fin.add_atoms(h_tmp,1)

#Relax images at the start and end of trajectory.
        disloc_ini.set_calculator(mm_pot)
        opt = FIRE(disloc_ini)
        opt.run(fmax=fmax)

        disloc_fin.set_calculator(mm_pot)
        opt = FIRE(disloc_fin)
        opt.run(fmax=fmax)

        return disloc_ini, disloc_fin
示例#5
0
        print 'Initializing crack_cell from Info File.'
        crack = CrackCell(**crack_info)
        f.close()
    except IOError:
        print 'no crack dictionary found.'
        sys.exit()

    Grain_Boundary = False

    if not Grain_Boundary:
        unit_slab = crack.build_unit_slab()

    pot_dir = os.environ['POTDIR']
    pot_file = os.path.join(pot_dir, crack_info['param_file'])
    mm_pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale=1.00894848312',
                       param_filename=pot_file,
                       cutoff_skin=2.0)

    # gb_frac.py will generate the frac_cell.xyz file which contains
    # a crack_cell:
    if Grain_Boundary:
        unit_slab = Atoms('frac_cell.xyz')
        unit_slab.set_calculator(mm_pot)

#calculate the elasticity tensor:
    crack.calculate_c(mm_pot)
    surface = crack.build_surface(mm_pot)
    E_surf = surface.get_potential_energy()
    bulk = bcc(2.82893)
    bulk.set_atoms(26)
    bulk.info['adsorbate_info'] = None
示例#6
0
            if z1 != 8:
                raise ValueError('all IN term atoms must be O')

            r_ij = (b.positions[j] + np.dot(o, b.cell) - b.positions[i])

            t = Atoms('H')
            d = r_ij / (eqm_bond_lengths[min(z1, z2), max(z1, z2)] *
                        eqm_bond_lengths[min(z1, 1), max(z1, 1)])
            t.translate(b.positions[i] + d)
            term += t

cryst = b[mask] + term

# calculator
from quippy import Potential
calc = Potential('IP TS', param_filename='ts_params.xml')

cryst.set_calculator(calc)
cryst.get_potential_energy()  # obtain reference dipole moments

cryst.set_scaled_positions(cryst.get_scaled_positions())
cryst.positions[:, 0] += cryst.cell[0, 0] / 2. - cryst.positions[:, 0].mean()
cryst.positions[:, 1] += cryst.cell[1, 1] / 2. - cryst.positions[:, 1].mean()

cryst.set_scaled_positions(cryst.get_scaled_positions())
cryst.center(vacuum, axis=0)
cryst.center(vacuum, axis=1)

# fix atoms near outer boundaries
r = cryst.get_positions()
minx = r[:, 0].min() + skin
示例#7
0
import __builtin__

orig_dir = os.getcwd()
model_dir = os.path.dirname(__file__)
if model_dir != '':
    os.chdir(model_dir)

if os.path.exists(
        'gp_iter6_sparse9k.xml.sparseX.GAP_2017_6_17_60_4_3_56_1651.bz2'):
    os.system(
        'bunzip2 gp_iter6_sparse9k.xml.sparseX.GAP_2017_6_17_60_4_3_56_1651.bz2'
    )

try:
    if hasattr(__builtin__, 'mpi_glob'):
        calculator = Potential(
            init_args='Potential xml_label="GAP_2017_6_17_60_4_3_56_165"',
            param_filename='gp_iter6_sparse9k.xml',
            mpi_obj=mpi_glob)
    else:
        calculator = Potential(
            init_args='Potential xml_label="GAP_2017_6_17_60_4_3_56_165"',
            param_filename='gp_iter6_sparse9k.xml')
    Potential.__str__ = lambda self: '<GAP Potential>'
finally:
    os.chdir(orig_dir)

no_checkpoint = True

name = 'GAP'
示例#8
0
  sim_T       = sim_T*units.kB
  calc_elastic_constants = False
  dyn_type = 'eam'

  print '\tDislocation Type: ',   dis_type, ' dislocation.'
  print '\tCalculate Dynamics: ', run_dyn
  print '\tCalculate Nye Tensor: ', calc_nye
  print '\tInput File: ', input_file
  print '\tPotential: ',  pot_type

  if pot_type == 'EAM':
    global potdir
    potdir   = os.environ['POTDIR']
    eam_pot  = os.path.join(potdir, 'PotBH.xml')
    r_scale  = 1.00894848312
    pot      = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot)
  elif pot_type == 'TB':
    tb = TightBindingPot(alat= 1.00, nk=12)
    screw_slab_unit = Atoms(screw_slab_unit)
    center_cell = np.diag(screw_slab_unit.get_cell())/2.
    screw_slab_unit.add_atoms(center_cell,1)
    #screw_slab_unit.add_atoms(center_cell*0.76, 6)

    screw_slab_unit.set_atoms(screw_slab_unit.Z)
    print len(screw_slab_unit)
    tb.write_control_file('ctrl.fe', screw_slab_unit)
    pot = Potential('IP LMTO_TBE', param_str="""
    <params>
      <LMTO_TBE_params n_types="2" control_file="ctrl.fe">
        <per_type_data type="1" atomic_num="26"/>
        <per_type_data type="2" atomic_num="1"/>
示例#9
0
def calc_bulk_dissolution(args):
    """Calculate the bulk dissolution energy for hydrogen
    in a tetrahedral position in bcc iron.
    Args:
      args(list): determine applied strain to unit cell.
    """
    POT_DIR = os.path.join(app.root_path, 'potentials')
    eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
    r_scale = 1.00894848312
    pot = Potential(
        'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale),
        param_filename=eam_pot)
    alat = 2.83

    gb = BodyCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                           size=(6, 6, 6),
                           symbol='Fe',
                           pbc=(1, 1, 1),
                           latticeconstant=alat)
    cell = gb.get_cell()
    print 'Fe Cell', cell

    e1 = np.array([1, 0, 0])
    e2 = np.array([0, 1, 0])
    e3 = np.array([0, 0, 1])

    if args.hydrostatic != 0.0:
        strain_tensor = np.eye(3) + args.hydrostatic * np.eye(3)
        cell = cell * strain_tensor
        gb.set_cell(cell, scale_atoms=True)
        print 'Hydrostatic strain', args.hydrostatic
        print 'strain tensor', strain_tensor
        print gb.get_cell()
    elif args.stretch != 0.0:
        strain_tensor = np.tensordot(e2, e2, axes=0)
        strain_tensor = np.eye(3) + args.stretch * strain_tensor
        cell = strain_tensor * cell
        print 'Stretch strain'
        print 'Cell:', cell
        gb.set_cell(cell, scale_atoms=True)
    elif args.shear != 0.0:
        strain_tensor = np.tensordot(e1, e2, axes=0)
        strain_tensor = np.eye(3) + args.shear * strain_tensor
        cell = strain_tensor.dot(cell)
        print 'Shear Strain', strain_tensor
        print 'Cell:', cell
        gb.set_cell(cell, scale_atoms=True)
        gb.write('sheared.xyz')
    else:
        print 'No strain applied.'

    tetra_pos = alat * np.array([0.25, 0.0, 0.5])
    h2 = aseAtoms('H2', positions=[[0, 0, 0], [0, 0, 0.7]])
    h2 = Atoms(h2)

    gb = Atoms(gb)
    gb_h = gb.copy()
    gb_h.add_atoms(tetra_pos, 1)

    #caclulators
    gb.set_calculator(pot)
    h2.set_calculator(pot)
    gb_h.set_calculator(pot)
    gb_h.write('hydrogen_bcc.xyz')

    #Calc Hydrogen molecule energy
    opt = BFGS(h2)
    opt.run(fmax=0.0001)
    E_h2 = h2.get_potential_energy()
    h2.write('h2mol.xyz')

    #strain_mask  = [1,1,1,0,0,0]
    strain_mask = [0, 0, 0, 0, 0, 0]
    ucf = UnitCellFilter(gb_h, strain_mask)

    #opt = BFGS(gb_h)
    opt = FIRE(ucf)
    opt.run(fmax=0.0001)
    E_gb = gb.get_potential_energy()
    E_gbh = gb_h.get_potential_energy()
    E_dis = E_gbh - E_gb - 0.5 * E_h2

    print 'E_gb', E_gb
    print 'E_gbh', E_gbh
    print 'H2 Formation Energy', E_h2
    print 'Dissolution Energy', E_dis
示例#10
0
import os

from quippy import Potential
import __builtin__

orig_dir = os.getcwd()
model_dir = os.path.dirname(__file__)
os.chdir(model_dir)
try:
    if hasattr(__builtin__, 'mpi_glob'):
        calculator = Potential(init_args='TB DFTB use_k_density k_density=4.0 Fermi_T=0.05',
                                               param_filename='tightbind.parms.DFTB.pbc-0-1.xml', mpi_obj=mpi_glob)
    else:
        calculator = Potential(init_args='TB DFTB use_k_density k_density=4.0 Fermi_T=0.05',
                                               param_filename='tightbind.parms.DFTB.pbc-0-1.xml')
finally:
    os.chdir(orig_dir)

no_checkpoint = True

name = 'DFTB.1'
示例#11
0
def gamma_surf(h_pos=np.array([1.41, 1.500, 22.48])):
    """
    :method:`gamma_surf` generates a set of directories with the upper
    half unit cell displaced along a certain distance
    along a particular lattice vector. Hydrogens can be added by
    setting vector in h_pos.

    TODO:
      h_pos should be a list of vectors and atom type for this to be more general.
    """

    vasp_exe = '/projects/SiO2_Fracture/iron/vasp.bgq'
    crack_geom = {
        'cleavage_plane': (1, 1, 0),
        'crack_front': (1, -1, 0),
        'crack_direction': (0, 0, 1)
    }

    crack_direction = crack_geom['crack_direction']
    crack_front = crack_geom['crack_front']
    cleavage_plane = crack_geom['cleavage_plane']
    fe_unit = BodyCenteredCubic(
        directions=[crack_direction, crack_front, cleavage_plane],
        size=(1, 1, 1),
        symbol='Fe',
        pbc=(1, 1, 1),
        latticeconstant=2.83)
    nunits = 8
    fe_bulk = BodyCenteredCubic(
        directions=[crack_direction, crack_front, cleavage_plane],
        size=(2, 2, nunits),
        symbol='Fe',
        pbc=(1, 1, 1),
        latticeconstant=2.83)
    fe_unit = Atoms(fe_unit)
    fe_bulk = Atoms(fe_bulk)

    ycut = 5.0 + float(nunits) / 2.0 * fe_unit.lattice[2, 2]
    fe_bulk.center(vacuum=5.0, axis=2)
    print 'lattice', fe_bulk.lattice[1, 1]
    print 'ycut', ycut

    a1 = fe_unit.lattice[0, 0]
    a2 = fe_unit.lattice[1, 1]

    POT_DIR = os.environ['POTDIR']
    eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
    r_scale = 1.00894848312
    #eam_pot = os.path.join(POT_DIR, 'iron_mish.xml')
    #r_scale = 1.0129007626
    pot = Potential(
        'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale),
        param_filename=eam_pot)
    fe_bulk.set_calculator(pot)
    print 'Bulk Energy', fe_bulk.get_potential_energy()
    refen = fe_bulk.get_potential_energy()
    A = fe_bulk.get_volume() / fe_bulk.lattice[2, 2]

    vasp_args = dict(
        xc='PBE',
        amix=0.01,
        amin=0.001,
        bmix=0.001,
        amix_mag=0.01,
        bmix_mag=0.001,
        kpts=[8, 8, 1],
        kpar=32,
        lreal='auto',
        ibrion=2,
        nsw=40,
        nelmdl=-15,
        ispin=2,
        nelm=100,
        algo='VeryFast',
        npar=8,
        lplane=False,
        lwave=False,
        lcharg=False,
        istart=0,
        voskown=1,
        ismear=1,
        sigma=0.1,
        isym=2)  # possibly try iwavpr=12, should be faster if it works

    dir_name = 'b111shiftsym'
    #dir_name  = 'b001shiftsym'
    f = open('_patdon123{0}H1.dat'.format(dir_name), 'w')
    WRITEVASP = True
    a0 = 2.83
    for inum, ashift in enumerate(np.arange(0, 1.10, 0.10)):
        try:
            os.mkdir('{0}{1}'.format(dir_name, ashift))
        except:
            pass
        print 'Directory already exists'

        os.chdir('{0}{1}'.format(dir_name, ashift))
        fe_shift = fe_bulk.copy()
        fe_shift.set_calculator(pot)
        for at in fe_shift:
            if at.position[2] > ycut:
                #[00-1](110)
                #  at.position += ashift*np.array([-a1,0,0])
                #[1-11](110)
                at.position += 0.5 * ashift * np.array([a1, a2, 0])
    #  print >> fil1, ashift, (units.m**2/units.J)*(fe_shift.get_potential_energy()-refen)/A
        line = []
        for at in fe_shift:
            line.append(FixedLine(at.index, (0, 0, 1)))
    #Now add Hydrogen
    # fe_shift.add_atoms(np.array([0.53*a0, 0.53*a0, 21.0+a0/2]),1)
    # at relaxed position:
        fe_shift.add_atoms(h_pos, 1)
        fix_atoms_mask = [at.number == 1 for at in fe_shift]
        fixedatoms = FixAtoms(mask=fix_atoms_mask)
        fe_shift.set_constraint(line + [fixedatoms])
        opt = LBFGS(fe_shift)
        opt.run(fmax=0.1, steps=1000)
        if inum == 0:
            print 'Setting Reference Energy'
            refen = fe_shift.get_potential_energy()
        print >> f, ashift, (units.m**2 / units.J) * (
            fe_shift.get_potential_energy() - refen) / A
        fe_shift.write('feb{0}.xyz'.format(ashift))
        if WRITEVASP:
            vasp = Vasp(**vasp_args)
            vasp.initialize(fe_shift)
            write_vasp('POSCAR',
                       vasp.atoms_sorted,
                       symbol_count=vasp.symbol_count,
                       vasp5=True)
            vasp.write_incar(fe_shift)
            vasp.write_potcar()
            vasp.write_kpoints()
        os.chdir('../')
    f.close()
示例#12
0
relax_slab = True                     # If True, relax notched slab with calculator
relax_fmax = 0.025*units.eV/units.Ang # Maximum force criteria for relaxation

# ******* Molecular dynamics parameters ***********

sim_T = 300.0*units.kB           # Simulation temperature
nsteps = 10000                   # Total number of timesteps to run for
timestep = 1.0*units.fs          # Timestep (NB: time base units are not fs!)
cutoff_skin = 2.0*units.Ang      # Amount by which potential cutoff is increased
                                 # for neighbour calculations
tip_move_tol = 10.0              # Distance tip has to move before crack 
                                 # is taken to be running
strain_rate = 1e-5*(1/units.fs)  # Strain rate
traj_file = 'traj.nc'            # Trajectory output file (NetCDF format)
traj_interval = 10               # Number of time steps between
                                 # writing output frames

# ********** Setup calculator ************

# Stillinger-Weber (SW) classical interatomic potential, from QUIP
from quippy import Potential
calc = Potential('IP SW', 'params.xml')

# Screened Kumagai potential, from Atomistica
#import atomistica
#calc = atomistica.KumagaiScr()



示例#13
0
potparam = PotentialParameters()
ener_bulk = potparam.gs_ener_per_atom()

POT_DIR = '/Users/lambert/pymodules/imeall/imeall/potentials'

at = AtomsReader(sys.argv[1])
at = at[-1]

pot_string = 'iron_mish.xml'
print ''
print '\t POTENTIAL: ', pot_string
print ''
eam_pot = os.path.join(POT_DIR, pot_string)
pot_1 = Potential(
    'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(1.0129007626),
    param_filename=eam_pot)
at.set_calculator(pot_1)
calc_e_gb(at, ener_bulk[pot_string])

pot_string = 'Fe_Mendelev.xml'
print ''
print 'POTENTIAL: ', pot_string
print ''
eam_pot = os.path.join(POT_DIR, pot_string)
pot_2 = Potential(
    'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(1.00894848312),
    param_filename=eam_pot)
at.set_calculator(pot_2)
calc_e_gb(at, ener_bulk[pot_string])
示例#14
0
from quippy import Potential
import os

model_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(
    model_dir,
    '16x16x16k_mesh_param_file_tightbind.parms.NRL_TB.Ti_spline.xml')

calculator = Potential('TB NRL-TB', param_filename=filename, Fermi_T=0.1)

no_checkpoint = True
name = 'DFTB'
示例#15
0
        sc = SumCalculator(pot, cc)

        atoms.set_constraint(FixAtoms(mask=fix_line_mask))
        atoms.set_calculator(sc)
        LBFGS(atoms, use_armijo=False).run(fmax=0.2)

        fix_line = [FixedLine(i, np.array([0, 1, 0])) for i in fix_line_idx]
        atoms.set_array('fix_line_mask', fix_line_mask)

        atoms.set_constraint(fix_line + springs)
        atoms.set_calculator(pot)
        opt = vanillaLBFGS(atoms)

    else:
        print("Method not understood")
        return

    opt.attach(trajectory_write, interval=5)
    opt.run(fmax=fmax)
    return


if __name__ == '__main__':

    pot = Potential('IP TS', param_filename="../ts_params.xml")
    in_file = sys.argv[1]
    out_file = os.path.splitext(in_file)[0] + '_relaxed.xyz'
    atoms = Atoms(in_file)
    minim_precon(atoms)
    atoms.write(out_file)
示例#16
0
# A module defining a module needs to define only one variable,
# named `calculator`, which should be an instance of the ase.calculator.Calculator,
# a subclass of this, or a compatible class implementing the calculator interface.

calculator = Potential('IP Tersoff',
                       param_str="""
<Tersoff_params n_types="3" label="PRB_39">
<comment> Tersoff, Phys. Rev. B v 39, p 5566 (1989) </comment>
<per_type_data type="1" atomic_num="6" 
  A="1393.6" B="346.7" lambda="3.4879" mu="2.2119" beta="0.00000015724" 
  n="0.72751" c="38049" d="4.384" h="-0.57058" R="1.8" S="2.1" />
<per_type_data type="2" atomic_num="14"
 A="1830.8" B="471.18" lambda="2.4799" mu="1.7322" beta="0.0000011"
 n="0.78734" c="100390" d="16.217" h="-0.59825" R="2.7" S="3.0" />
<per_type_data type="3" atomic_num="32"
  A="1769" B="419.23" lambda="2.4451" mu="1.7047" beta="0.00000090166"
  n="0.75627" c="106430" d="15.652" h="-0.43884" R="2.8" S="3.1" />
<per_pair_data type1="1" type2="1" chi="1.0" />
<per_pair_data type1="2" type2="1" chi="0.9776" />
<per_pair_data type1="2" type2="2" chi="1.0" />
<per_pair_data type1="3" type2="1" chi="1.0" />
<per_pair_data type1="3" type2="2" chi="1.00061" />
<per_pair_data type1="3" type2="3" chi="1.0" />
</Tersoff_params>
""")

no_checkpoint = True

name = 'Tersoff'
示例#17
0
import os

import numpy as np

from ase.units import GPa, J, m, kB, fs, Ang
import quippy
from matscipy.neighbours import neighbour_list
from quippy import Potential

k_spring = 1.00
initial_strain = 0.10
crack_seed_length = 1. / 3  # fraction of total length
strain_ramp_length = 15
vacuum = 20
relax_fmax = 0.01
pre_optim = True
relax_slab = True

calc = Potential("IP TS", param_filename='ts_params.xml')
示例#18
0
import os

from quippy import Potential
import __builtin__

orig_dir = os.getcwd()
model_dir = os.path.dirname(__file__)
if model_dir != '':
    os.chdir(model_dir)

if os.path.exists('gp_iter5_with111adatom_with3x3das_sparse2x.xml.sparseX.GAP_2017_5_20_60_4_23_20_5121.bz2'):
    os.system('bunzip2 gp_iter5_with111adatom_with3x3das_sparse2x.xml.sparseX.GAP_2017_5_20_60_4_23_20_5121.bz2')

try:
    if hasattr(__builtin__, 'mpi_glob'):
        calculator = Potential(init_args='Potential xml_label="GAP_2017_5_20_60_4_23_20_512"',
                                               param_filename='gp_iter5_with111adatom_with3x3das_sparse2x.xml', mpi_obj=mpi_glob)
    else:
        calculator = Potential(init_args='Potential xml_label="GAP_2017_5_20_60_4_23_20_512"',
                                               param_filename='gp_iter5_with111adatom_with3x3das_sparse2x.xml')
    Potential.__str__ = lambda self: '<GAP Potential>'
finally:
    os.chdir(orig_dir)

no_checkpoint = True

name = 'GAP-ScienceAdvances'
示例#19
0
# Model for Stillinger-Weber with original parameters for Si (Z=14)

from quippy import Potential

# A module defining a module needs to define only one variable,
# named `calculator`, which should be an instance of the ase.calculator.Calculator,
# a subclass of this, or a compatible class implementing the calculator interface.

calculator = Potential('IP SW',
                       param_str="""
<SW_params n_types="1">
<per_type_data type="1" atomic_num="14" />
<per_pair_data atnum_i="14" atnum_j="14" AA="7.049556277" BB="0.6022245584"
      p="4" q="0" a="1.80" sigma="2.0951" eps="2.1675" />
<per_triplet_data atnum_c="14" atnum_j="14" atnum_k="14"
      lambda="21.0" gamma="1.20" eps="2.1675" />
</SW_params>
""")

no_checkpoint = True
name = 'SW'
示例#20
0
    calc_elastic_constants = False
    dyn_type = 'eam'

    print '\tDislocation Type: ', dis_type, ' dislocation.'
    print '\tCalculate Dynamics: ', run_dyn
    print '\tCalculate Nye Tensor: ', calc_nye
    print '\tInput File: ', input_file
    print '\tPotential: ', pot_type

    if pot_type == 'EAM':
        global potdir
        potdir = os.environ['POTDIR']
        eam_pot = os.path.join(potdir, 'PotBH.xml')
        r_scale = 1.00894848312
        pot = Potential(
            'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale),
            param_filename=eam_pot)
    elif pot_type == 'TB':
        tb = TightBindingPot(alat=1.00, nk=12)
        screw_slab_unit = Atoms(screw_slab_unit)
        center_cell = np.diag(screw_slab_unit.get_cell()) / 2.
        screw_slab_unit.add_atoms(center_cell, 1)
        #screw_slab_unit.add_atoms(center_cell*0.76, 6)

        screw_slab_unit.set_atoms(screw_slab_unit.Z)
        print len(screw_slab_unit)
        tb.write_control_file('ctrl.fe', screw_slab_unit)
        pot = Potential('IP LMTO_TBE',
                        param_str="""
    <params>
      <LMTO_TBE_params n_types="2" control_file="ctrl.fe">
示例#21
0
    try:
        pot_dir  = os.environ['POTDIR']
    except:
        print 'POTDIR not defined in os environment.'
        raise

    nqx = 24
    nqy = 24
    nqz = 24

    n_sup_x = 8
    n_sup_y = 8
    n_sup_z = 8

    pot_file  = os.path.join(pot_dir, 'PotBH.xml')
    pot       = Potential('IP EAM_ErcolAd', param_filename=pot_file)
    #Set paths for phonon band structures:
    #paths = [np.array([0,0,-0.5]), np.array([0,0,0]), np.array([0,0,0.5]), np.array([0,0.5,0.5])]
    b1        = 1.0
    #Nice plot for phonon:
    paths     = [np.array([0,0,0.0]), np.array([b1/2.0, b1/2.0, 0.0]), np.array([b1/2.0,b1/2.0,b1])]
    paths     = calc_band_paths(paths)
    unit_cell = BodyCenteredCubic(directions = [[1,0,0], [0,1,0],[0,0,1]],
                                  size = (1,1,1), symbol='Fe', pbc=(1,1,1),
                                  latticeconstant = 2.83)

    symbols          = unit_cell.get_chemical_symbols()
    cell             = unit_cell.get_cell()
    scaled_positions = unit_cell.get_scaled_positions()

    THZ_to_mev = 4.135665538536
示例#22
0
文件: relax.py 项目: obaica/imeall
def relax_gb(gb_file='file_name',
             traj_steps=120,
             total_steps=1200,
             force_tol=0.05):
    """Method to relax a grain_boundary bicrystal structure. Requires a .json
    file with at a minimum the 'param_file' variable specified.

    Args:
      gb_file(str): gbid.
      traj_steps(int): number of steps between print trajectories.
      total_steps(int): total number of force relaxation steps.
      force_tol(float): Force relaxation criterion in ev/A.

    Returns:
      :class:`ase.Atoms` Object
    """
    def converged(grain, smax, fmax):
        maxstress = max(grain.get_stress().ravel())
        rmsforces = np.sum(grain.get_forces()**2, axis=1)**0.5
        maxforce = max(rmsforces)
        if maxforce < fmax and maxstress < smax:
            return True
        return False

    with open('subgb.json', 'r') as outfile:
        j_dict = json.load(outfile)
    try:
        POT_DIR = os.path.join(app.root_path, 'potentials')
    except KeyError:
        sys.exit(
            "Please set POTDIR in os environment. `export POTDIR='path/to/potfiles/`"
        )
    try:
        param_file = j_dict['param_file']
        if param_file == 'iron_mish.xml':
            eam_pot = os.path.join(POT_DIR, 'iron_mish.xml')
            r_scale = 1.0129007626
        elif param_file == 'Fe_Mendelev.xml':
            eam_pot = os.path.join(POT_DIR, 'Fe_Mendelev.xml')
            r_scale = 1.00894848312
        elif param_file == 'PotBH.xml':
            eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
            r_scale = 1.00894848312
        elif param_file == 'Fe_Ackland.xml':
            eam_pot = os.path.join(POT_DIR, 'Fe_Ackland.xml')
            r_scale = 1.00894185389
        elif param_file == 'Fe_Dudarev.xml':
            eam_pot = os.path.join(POT_DIR, 'Fe_Dudarev.xml')
            r_scale = 1.01279093417
        elif param_file == 'gp33b.xml':
            eam_pot = os.path.join(POT_DIR, 'gp33b.xml')
            sparse_file = 'gp33b.xml.sparseX.GAP_2016_10_3_60_19_29_10_8911'
            eam_pot_sparse = os.path.join(POT_DIR, sparse_file)
            shutil.copy(eam_pot, './')
            shutil.copy(eam_pot_sparse, './')
        else:
            print 'No paramfile found!'
            sys.exit()
    except KeyError:
        print 'No EAM potential file with that name. Relax failed.'
        sys.exit()

    print 'Using: ', eam_pot
    pot_file = eam_pot.split('/')[-1]
    print '{0}.xyz'.format(gb_file)
    print os.getcwd()
    grain = io.read('{0}.xyz'.format(gb_file), index='-1')
    if param_file != 'gp33b.xml':
        pot = Potential(
            'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale),
            param_filename=eam_pot)
    else:
        pot = Potential('IP GAP', param_filename=eam_pot)

    grain.set_calculator(pot)
    grain.info['adsorbate_info'] = None
    E_gb_init = grain.get_potential_energy()
    traj_file = gb_file
    if 'traj' in traj_file:
        out = AtomsWriter('{0}'.format('{0}.xyz'.format(traj_file)))
    else:
        out = AtomsWriter('{0}'.format('{0}_traj.xyz'.format(traj_file)))
    strain_mask = [0, 0, 1, 0, 0, 0]
    ucf = UnitCellFilter(grain, strain_mask)
    opt = FIRE(ucf)
    cell = grain.get_cell()
    A = cell[0][0] * cell[1][1]
    H = cell[2][2]
    #Calculation dumps total energyenergy and grainboundary area data to json file.
    with open('subgb.json', 'r') as f:
        gb_dict = json.load(f)

    #Write an initial dict so we know if the system has been initialized but the calculation is not finished.
    with open('subgb.json', 'w') as outfile:
        for key, value in gb_dict.items():
            j_dict[key] = value
        json.dump(j_dict, outfile, indent=2)

    CONVERGED = False
    FORCE_TOL = force_tol

    #default to 5 if traj_steps = 120, otherwise increases
    num_iters = int(float(total_steps) / float(traj_steps))
    logging.debug('num_iters: {}'.format(num_iters))
    for i in range(num_iters):
        opt.run(fmax=FORCE_TOL, steps=traj_steps)
        out.write(grain)
        force_array = grain.get_forces()
        max_force_II = max([max(f) for f in force_array])
        max_forces = [
            np.sqrt(fx**2 + fy**2 + fz**2) for fx, fy, fz in zip(
                grain.properties['force'][0], grain.properties['force'][1],
                grain.properties['force'][2])
        ]
        if max(max_forces) <= FORCE_TOL:
            CONVERGED = True
            break
    out.close()

    gb_dict['converged'] = CONVERGED
    E_gb = grain.get_potential_energy()
    gb_dict['E_gb'] = E_gb
    gb_dict['E_gb_init'] = E_gb_init
    gb_dict['area'] = A
    with open('subgb.json', 'w') as outfile:
        for key, value in gb_dict.items():
            j_dict[key] = value
        json.dump(j_dict, outfile, indent=2)

    if param_file == 'gp33b.xml':
        os.remove(param_file)
        os.remove(sparse_file)
    else:
        pass
    return grain
示例#23
0
  sym_tilt_110 = [[np.pi*(93.37/180.), np.array([-3., 3., 4.])]]
  gbid = '1109337334'
  or_axis = [1,1,0]
  bp      = [-1,1,12]

##########################################
##First calculate surface energetics:   ##
##########################################
  bulk = BodyCenteredCubic(directions = [[1,0,0],[0,1,0], [0,0,1]],
                           size = (1,1,1), symbol='Fe', pbc=(1,1,1),
                           latticeconstant = 2.85)

  eam_pot = './Fe_Mendelev.xml'
  gb_frac = GBFracture()
  surf_cell = gb_frac.build_surface(bp = sym_tilt_110[0][1])
  pot     = Potential('IP EAM_ErcolAd', param_filename=eam_pot)
  bulk.set_calculator(pot)
  ener_per_atom = bulk.get_potential_energy()/len(bulk)
  surf_cell.set_calculator(pot)
  surf_ener = surf_cell.get_potential_energy()
  cell  = surf_cell.get_cell()
  A     = cell[0][0]*cell[1][1]
  gamma = (surf_ener- len(surf_cell)*ener_per_atom)/A

  print '2*gamma ev/A2', gamma
  print '2*gamma J/m2',  gamma/(units.J/units.m**2)
  j_dict = {'or_axis':or_axis, 'bp':bp, 'gamma':gamma}
  with open('gbfrac.json','w') as f:
    json.dump(j_dict, f)
  out = AtomsWriter('{0}'.format('{0}_surf.xyz'.format(gbid)))
  out.write(Atoms(surf_cell))
示例#24
0
at.calc_connect()

print 'Delete atoms'
at = gbr.delete_atoms(grain=at, rcut=1.5)
at.info['OrigHeight'] = at.positions[:, 1].max() - at.positions[:, 1].min()
r_scale = 1.00894848312
rem = []
for atom in at:
    if atom.position[0] <= 0.00 and atom.position[1] <= 100.0:
        rem.append(atom.index + 1)
print 'Removing ', len(rem), ' atoms.'
if len(rem) > 0:
    at.remove_atoms(rem)
else:
    print 'No atoms displaced from unitcell'
pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale),
                param_filename=eam_pot)
at.set_calculator(pot)
at.write('unrelaxed.xyz')
print 'Running Relaxation'
opt = FIRE(at)
opt.run(fmax=0.1)

print 'Calculating connectivity and Nye Tensor'

ref_slab = Atoms('ref_slab.xyz')
ref_slab.set_cutoff(3.0)
ref_slab.calc_connect()

at.set_cutoff(3.0)
at.calc_connect()
alpha = calc_nye_tensor(at, ref_slab, 3, 3, at.n)
示例#25
0
文件: run-tb.py 项目: obaica/imeall
        MOL=mol GAMMA=F PAIR=pair SCALE={scale}
        UL={ul} IODEL={io} OVLP={ovlp} TBU={tbu} NOUAVG={nav} U1={u1}
EWALD   TOL=ewtol NKDMX=1999 NKRMX=1999
OPTIONS ASA[ADNF[0] NSPH[0] TWOC[0] CCOR[1]]"""

# generate a control file from template for this atomic config
write_control_file('ctrl.fe', ctrl_template, atoms, alat, nk=nk)

# setup QUIP Potential interfacing to LMTO TBE library
# control file is the one written above from template
# NB: order of types must match order in control file
tb_pot = Potential('IP LMTO_TBE',
                   param_str="""
    <params>
      <LMTO_TBE_params n_types="3" control_file="ctrl.fe">
        <per_type_data type="1" atomic_num="26"/>
        <per_type_data type="2" atomic_num="6"/>
        <per_type_data type="3" atomic_num="1"/>
      </LMTO_TBE_params>
    </params>""")

print tb_pot

# compute energies and forces for a range of lattice constants
if True:
    a = np.linspace(2.5, 3.0, 5)
    e = []
    f = []
    configs = []
    for aa in a:
        atoms = BodyCenteredCubic(symbol='Fe', latticeconstant=aa)
示例#26
0
    parser.add_argument("--use_gap", "-g", action="store_true")
    parser.add_argument("--relax", "-r", action="store_true", help='If true relaxes initial and final positions of the NEB calculation.')
    args = parser.parse_args()

    #only one qmpot specifed at command line
    use_eampot = not(args.use_gap or args.use_socket) 
    #assert sum(args.use_gap + args.use_socket + use_mmpot) == 1 
    print (args, file=(open('output.txt','w')))

    buff = args.buff
    qm_radius = args.qm_radius

    POT_DIR = os.path.join(app.root_path, 'potentials')
    eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
    r_scale = 1.00894848312
    mm_pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot)

    if args.auto_gen:
        gb_cell = AtomsReader(args.input_file)[-1]
    else:
        gb_cell = AtomsReader("disloc_0.xyz")[-1]

   # defect = find_h_atom(gb_cell)
   # h_pos = defect.position
    qm_center = gb_cell.info['CrackPos']
    x, y, z = gb_cell.positions.T
    radius1 = np.sqrt((x -qm_center[0])**2 + (y-qm_center[1])**2 + (z-qm_center[2])**2)

    qm_region_mask = (radius1 < qm_radius)
    qm_buffer_mask = (radius1 < qm_radius + buff)
示例#27
0
        distances.append(v['distance'])

        if j % npoints == 0:
            special_points.append(v['distance'])

    special_points.append(data['phonon'][-1]['distance'])
    return special_points, distances, frequencies


write_yaml = 1  # save results to band.yaml file
read_yaml = 0  # set to 1 to add a plot loaded from YAML file

# Define unit cell and potential to be used for calculating forces
a = 5.44
bulk = diamond(a, 14)
pot = Potential('IP SW')
bulk.set_calculator(pot)

# Phonopy pre-process
print "------"
print "Phonon"
print "------"
# 1st arg. is the input unit cell.
# 2nd arg. is the supercell lattice relative to the unit cell.
# 'distance' is the distance of displacements.
# Default symmetry tolerance is 1e-5 in fractional coordinates.
phonon = Phonopy(bulk, [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                 distance=0.01,
                 factor=VaspToTHz)
phonon.print_displacements()
supercells = phonon.get_supercells_with_displacements()
示例#28
0
                         env=os.environ)

sock_calc = SocketCalculator(quip_client)

el = 'Si'
a0 = 5.43
n = [6, 4, 1]
crack_surface = [1, 1, 1]
crack_front = [1, -1, 0]

cryst = diamond(el, a0, n, crack_surface, crack_front)
cryst.pbc = [True, True, True]  # QUIP doesn't handle open BCs
cryst.rattle(0.01)

cryst.set_calculator(sock_calc)
sock_e = cryst.get_potential_energy()
sock_f = cryst.get_forces()
sock_s = cryst.get_stress()
sock_calc.shutdown()

# compare to results from quippy
quippy_calc = Potential('IP SW', param_filename='params.xml')
cryst.set_calculator(quippy_calc)
quippy_e = cryst.get_potential_energy()
quippy_f = cryst.get_forces()
quippy_s = cryst.get_stress()

print 'energy difference', sock_e - quippy_e
print 'force difference', abs((sock_f - quippy_f).max())
print 'stress difference', abs((sock_s - quippy_s).max())
示例#29
0
calculator = Potential('IP Si_MEAM',
                       param_str="""
<Si_MEAM_params n_types="1" label="">
<!-- Thomas J Lenosky, Babak Sadigh, Eduardo Alonso, Vasily V Bulatov, Tomas Diaz de la Rubia -->
<!-- Jeongnim Kim, Arthur F Voter and Joel D Kress -->
<!-- Highly optimized empirical potential model of silicon -->
<!-- Modelling Simul. Mater. Sci. Eng. 8 (2000) 825-841 -->
  <per_type_data atomic_num="14" type="1">
    <spline spline_function="U" n_spline="8" yp1="0.73514" ypn="0.61652">
      <point x="-1.7709300000" y="-1.0749300000" />
      <point x="-0.3881514286" y="-0.2004500000" />
      <point x=" 0.9946271429" y=" 0.4142200000" />
      <point x=" 2.3774057143" y=" 0.8793900000" />
      <point x=" 3.7601842857" y=" 1.2668900000" />
      <point x=" 5.1429628571" y=" 1.6299800000" />
      <point x=" 6.5257414286" y=" 1.9773800000" />
      <point x=" 7.9085200000" y=" 2.3961800000" />
    </spline>
  </per_type_data>
  <per_pair_data atomic_num_i="14" atomic_num_j="14" r_cut_phi="4.5" r_cut_rho="3.5" r_cut_f="3.5">
    <spline spline_function="phi" n_spline="10" yp1="-42.66967" ypn="0.00000">
      <point x="1.5000000000" y=" 6.9299400000" />
      <point x="1.8333333333" y="-0.4399500000" />
      <point x="2.1666666667" y="-1.7012300000" />
      <point x="2.5000000000" y="-1.6247300000" />
      <point x="2.8333333333" y="-0.9969600000" />
      <point x="3.1666666667" y="-0.2739100000" />
      <point x="3.5000000000" y="-0.0249900000" />
      <point x="3.8333333333" y="-0.0178400000" />
      <point x="4.1666666667" y="-0.0096100000" />
      <point x="4.5000000000" y=" 0.0000000000" />
    </spline>
    <spline spline_function="rho" n_spline="11" yp1="-1.00000" ypn="0.00000">
      <point x="1.5000000000" y=" 0.1374700000" />
      <point x="1.7000000000" y="-0.1483100000" />
      <point x="1.9000000000" y="-0.5597200000" />
      <point x="2.1000000000" y="-0.7311000000" />
      <point x="2.3000000000" y="-0.7628300000" />
      <point x="2.5000000000" y="-0.7291800000" />
      <point x="2.7000000000" y="-0.6662000000" />
      <point x="2.9000000000" y="-0.5732800000" />
      <point x="3.1000000000" y="-0.4069000000" />
      <point x="3.3000000000" y="-0.1666200000" />
      <point x="3.5000000000" y=" 0.0000000000" />
    </spline>
    <spline spline_function="f" n_spline="10" yp1="-3.61894" ypn="0.00000">
      <point x="1.5000000000" y="1.2503100000" />
      <point x="1.7222222222" y="0.8682100000" />
      <point x="1.9444444444" y="0.6084600000" />
      <point x="2.1666666667" y="0.4875600000" />
      <point x="2.3888888889" y="0.4416300000" />
      <point x="2.6111111111" y="0.3761000000" />
      <point x="2.8333333333" y="0.2714500000" />
      <point x="3.0555555556" y="0.1481400000" />
      <point x="3.2777777778" y="0.0485500000" />
      <point x="3.5000000000" y="0.0000000000" />
    </spline>
  </per_pair_data>
  <per_triplet_data atomic_num_i="14" atomic_num_j="14" atomic_num_k="14">
    <spline spline_function="g" n_spline="8" yp1="-13.95042" ypn="1.13462">
      <point x="-1.0000000000" y="5.2541600000" />
      <point x="-0.7428371429" y="2.3591500000" />
      <point x="-0.4856742857" y="1.1959500000" />
      <point x="-0.2285114286" y="1.2299500000" />
      <point x=" 0.0286514286" y="2.0356500000" />
      <point x=" 0.2858142857" y="3.4247400000" />
      <point x=" 0.5429771429" y="4.9485900000" />
      <point x=" 0.8001400000" y="5.6179900000" />
    </spline>
  </per_triplet_data>
</Si_MEAM_params>
""")