Ejemplo n.º 1
0
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
0
                    "--radius",
                    default=40.0,
                    type=float,
                    help="radius around cracktip to cutout (default 40\A)")
parser.add_argument("-i",
                    "--input",
                    default="crack_traj.xyz",
                    help="trajectory file to cut crack tip from.")
parser.add_argument("-o",
                    "--output",
                    default="cracktip_zone.xyz",
                    help="trajectory file to write cracktip region to.")

args = parser.parse_args()


def append(ats, rr, initial_crack, output_file='joined.xyz'):
    num_images = len(ats)
    for i, at in enumerate(ats):
        print i + 1, '/', num_images, initial_crack
        fixed_mask = (np.sqrt(
            map(sum, map(np.square,
                         at.positions[:, 0:3] - initial_crack[0:3]))) <= rr)
        cl = at.select(fixed_mask)
        write_xyz(output_file, cl, append=True)


ats = AtomsReader(args.input)
initial_crackpos = np.array(ats[0].params['CrackPos'])
append(ats, args.radius, initial_crackpos, output_file=args.output)
Ejemplo n.º 5
0
    #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)

    print ("\nNumber of atoms in qm region of %.1f" % qm_radius +
                                    "A : %i" % np.count_nonzero(qm_region_mask))
Ejemplo n.º 6
0

def calculate_constraint(at, tipatoms):
    f = at.get_array('force')
    cnstr = SlowGrowthBondLength(*tipatoms, bond_speed=0., direction=tipatoms)
    cnstr.adjust_forces(at, f)

    p1, p2 = at.positions[tipatoms]
    d, _ = find_mic(np.array([p2 - p1]), at._cell, pbc=False)
    d = d[0]
    d = np.dot(d, cnstr.direction)
    f_cnstr = np.dot(cnstr.get_constraint_force(), cnstr.direction)
    return np.abs(d), f_cnstr


if __name__ == "__main__":

    # MAIN
    input_file = sys.argv[1]
    atlist = AtomsReader(input_file)

    tipatoms = [int(sys.argv[2]), int(sys.argv[3])]

    name = input_file.strip('.xyz')
    fff = open('%s-constraint.csv' % name, 'wb')
    for i, at in enumerate(atlist):
        d, f_cnstr = calculate_constraint(at, tipatoms)
        print("%.5f, %.5f" % (np.abs(d), f_cnstr), file=fff)
        print("Step: %06d | %.5f, %.5f" % (i, np.abs(d), f_cnstr))
    fff.close()
Ejemplo n.º 7
0
import os
import sys
import glob
from quippy import AtomsReader, AtomsWriter, set_fortran_indexing

#Read in a collection of traj output files
#and dump them into a single traj file.
#list of properties that can be deleted
del_prop_lit = ['hybrid_vec', 'hybrid_1', 'weight_region1', 'weight_region1_1']
traj_files = sorted(glob.glob('[0-9]*.traj.xyz'))
knit_traj = AtomsWriter('full_traj.xyz')

for traj_file in traj_files:
    ats = AtomsReader(traj_file)
    print len(ats)
    for at in ats:
        mom = [3.0 for x in range(len(at))]
        at.set_initial_magnetic_moments(mom)
        at.add_property('mhm1', at.properties['modified_hybrid_mark_1'])
        at.add_property('edgex', 0.0, overwrite=True)
        at.add_property('edgey', 0.0, overwrite=True)
        at.add_property('screw', 0.0, overwrite=True)
        knit_traj.write(at)
Ejemplo n.º 8
0
                    default=1e-3)

args = parser.parse_args()

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)

#disloc_fin, disloc_ini, bulk = sd.make_barrier_configurations(calculator=lammps, cylinder_r=cylinder_r)
if not args.restart:
    gb_cell = AtomsReader('bcc_h.xyz')[-1]
else:
    gb_cell = AtomsReader('gb_traj_ini.xyz')[-1]

defect = find_h_atom(gb_cell)
h_pos = defect.position

x, y, z = gb_cell.positions.T
radius1 = np.sqrt((x - h_pos[0])**2 + (y - h_pos[1])**2 + (z - h_pos[2])**2)
qm_region_mask = (radius1 < qm_radius)
qm_buffer_mask = (radius1 < qm_radius + buff)

print("\nNumber of atoms in qm region of %.1f" % qm_radius +
      "A : %i" % np.count_nonzero(qm_region_mask))

print("together with the buffer of %.1f" % (qm_radius + buff) +
Ejemplo n.º 9
0
def build_neb_configurations():
    at_ini = AtomsReader('gb_traj.xyz')[-1]
Ejemplo n.º 10
0
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)
#r_scale = 1.0089
#mm_pot_mod = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot)



with open('subgb.json','r') as f:
    subgb_dict = json.load(f)
#[11.79728921, 4.61819134, 34.51540462]
h_pos = subgb_dict['site']
print (h_pos)
#disloc_fin, disloc_ini, bulk = sd.make_barrier_configurations(calculator=lammps, cylinder_r=cylinder_r)
gb_cell = AtomsReader('interstitial_traj.xyz')[-1]
x, y, z = gb_cell.positions.T
radius1 = np.sqrt((x - h_pos[0])**2 + (y-h_pos[1])**2 + (z-h_pos[2])**2)

qm_region_mask = (radius1 < qm_radius)
qm_buffer_mask = (radius1 < qm_radius + buff)

print ("\nNumber of atoms in qm region of %.1f" % qm_radius +
                                "A : %i" % np.count_nonzero(qm_region_mask))

print ("together with the buffer of %.1f" % (qm_radius + buff ) +
                                "A %i" % np.count_nonzero(qm_buffer_mask))

magmoms=[2.6 for _ in range(np.count_nonzero(qm_buffer_mask))]
vasp_args = dict(xc='PBE', amix=0.01, amin=0.001, bmix=0.001, amix_mag=0.01, bmix_mag=0.001,
                 kpts=[1, 1, 1], kpar=1, lreal='auto', nelmdl=-15, ispin=2, prec='High', encut=320,
Ejemplo n.º 11
0
    A = cell[0, 0] * cell[1, 1]
    E_gb = (at.get_potential_energy() - (at.n * (E_bulk))) / (2. * A)
    print A
    print at.get_potential_energy()
    print E_gb, 'eV/A^2'
    E_gb = 16.02 * (at.get_potential_energy() - (at.n * (E_bulk))) / (2. * A)
    print E_gb, 'J/m^2'
    return E_gb


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 ''
Ejemplo n.º 12
0
def gb_check_force(material='alphaFe', or_axis='001', force_tol=0.05, modify_db=False, gb_start=0, sub_start=0):
    """Recurse through directory tree, loading the structure file, json dict
    and the model for each subgrain. Check that the force tolerance in the structure
    file has actually been met for convergence.

    Args:
      material(str): material string.
      or_axis(str): orientation axis.
      force_tol(float): Max force magnitude on the relaxed structures.
      modify_db(bool): If True :py:class:`SubGrainBoundary` will be updated.
      gb_start(int): Start from this grain boundary in list.
      sub_start(int): Start from this subgrainboundary in list.
    """

    analyze  = GBAnalysis()
    gb_files = []
    analyze.find_gb_json('{0}'.format(os.path.join(GRAIN_DATABASE, os.path.join(material, or_axis))),
                                                   gb_files, 'gb.json')
    no_struct_file = open('no_struct.txt','a')
    for gb_num, gb in enumerate(gb_files[gb_start:]):
        with open(gb[1], 'r') as f:
            gb_json = json.load(f)
        GB_model = GrainBoundary.select().where(GrainBoundary.gbid==gb_json['gbid']).get()
        for subgb_num, subgb_model in enumerate(GB_model.subgrains[sub_start:]):
            subgb_dict_path = os.path.join(subgb_model.path,'subgb.json')
            subgb_dict_path = os.path.join(GRAIN_DATABASE, subgb_dict_path)
            with open(subgb_dict_path,'r') as f:
                subgb_dict = json.load(f)
            struct_path = os.path.join(subgb_model.path, subgb_model.gbid+'_traj.xyz')
            struct_path = os.path.join(GRAIN_DATABASE, struct_path)
            try:
                ats = AtomsReader(struct_path)[-1]
            except RuntimeError:
                print 'No Struct File'
            except EOFError:
                print 'Struct File corrupted'
            except IOError:
                print 'No Traj File'
            else:
                print gb_num+gb_start, subgb_num+sub_start, struct_path
                try:
                    forces = [np.sqrt(x**2+y**2+z**2) for x,y,z, in zip(ats.properties['force'][0],
                                                                        ats.properties['force'][1],
                                                                        ats.properties['force'][2])]
                except KeyError:
                    print gb_num+gb_start, struct_path
                    print 'No Force in atoms object'
                    conv_check = False
                else:
                    if max(forces) <= force_tol:
                        conv_check = True
                    else:
                        conv_check = False
                        subgb_dict['E_gb'] = 0.0

            if modify_db:
                if conv_check != subgb_dict['converged']:
                    print struct_path
                    print 'Force from .xyz: ', conv_check, 'json: ', subgb_dict['converged']
                    print 'Model: ', subgb_model.converged
                    subgb_dict['converged'] = conv_check
                    with open(subgb_dict_path, 'w') as f:
                        json.dump(subgb_dict, f, indent=2)
                else:
                    pass
            else:
                try:
                    if conv_check != subgb_dict['converged']:
                        print struct_path
                        print 'Force from .xyz: ', conv_check, 'json: ', subgb_dict['converged']
                        print 'Model: ', subgb_model.converged
                    else:
                        pass
                except KeyError:
                    print 'no convergence key'
                    subgb_dict['converged']=conv_check
                    with open(subgb_dict_path, 'w') as f:
                        json.dump(subgb_dict, f, indent=2)
Ejemplo n.º 13
0
if opt.offset is not None:
    if len(opt.offset) != len(args):
        p.error(
            'Number of -O/--offset options must match number of input files')
else:
    opt.offset = [0] * len(args)

if len(opt.bond) == 0 and len(opt.angle) == 0:
    p.error('One or more -b/--bond pairs or -a/--angle triplets needed')

atoms = set([idx for bond in opt.bond
             for idx in bond] + [idx for angle in opt.angle for idx in angle])
atoms_start = min(atoms)
atoms_stop = max(atoms)
sources = [
    AtomsReader(arg, start=offset, range=[atoms_start, atoms_stop])
    for arg, offset in zip(args, opt.offset)
]

bonds = [(i - atoms_start + 1, j - atoms_start + 1) for (i, j) in opt.bond]
angles = [(i - atoms_start + 1, j - atoms_start + 1, k - atoms_start + 1)
          for (i, j, k) in opt.angle]

fmt_string = '%18.6f' * (1 + len(sources) * (len(bonds) + len(angles)))
for configs in itertools.izip(*sources):
    times = []
    bondlengths = []
    angles = []
    for at in configs:
        times.append(at.time)
        for i, j in bonds:
Ejemplo n.º 14
0
    args = parser.parse_args()

    #only one qmpot specifed at command line
    use_eampot = not (args.use_gap or args.use_socket)
    if use_eampot:
        print ('USING EAMPOT')

    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)

    crack_slab = AtomsReader('crack_sim.xyz')[-1]

    crack_pos = crack_slab.info['CrackPos']
    x, y, z = crack_slab.positions.T
    radius1 = np.sqrt((x - crack_pos[0])**2 + (y-crack_pos[1])**2 + (z-crack_pos[2])**2)

    qm_region_mask = (radius1 < qm_radius)
    qm_buffer_mask = (radius1 < qm_radius + buff)

    print ("\nNumber of atoms in qm region of %.1f" % qm_radius +
                                    "A : %i" % np.count_nonzero(qm_region_mask))

    print ("together with the buffer of %.1f" % (qm_radius + buff ) +
                                    "A %i" % np.count_nonzero(qm_buffer_mask))

    if args.use_socket: