def __init__(self, atoms, indices=None, name='ir', delta=0.01, nfree=2, directions=None): assert nfree in [2, 4] self.atoms = atoms if indices is None: indices = range(len(atoms)) self.indices = np.asarray(indices) self.nfree = nfree self.name = name + '-d%.3f' % delta self.delta = delta self.H = None if directions is None: self.directions = np.asarray([0, 1, 2]) else: self.directions = np.asarray(directions) self.ir = True self.ram = False if str(type(self.atoms[0])) == "<class 'ase.atoms.Atoms'>": self.imagetype='atoms' fixed_atoms = constraints.constrained_indices(atoms[0]) allatoms = np.array(range(0,len(atoms[0]))) self.free_atoms = [i for i in allatoms if i not in fixed_atoms] self.free_list = range(0,len(self.free_atoms)) self.atom = atoms[0].copy() else: self.imagetype='pickle' if atoms.constraints: print('WARNING! \n Your Atoms object is constrained. ' 'Some forces may be unintended set to zero. \n') self.calc = atoms.get_calculator()
def test_getindices(): from ase.build import fcc111 from ase.constraints import (FixAtoms, FixBondLengths, FixLinearTriatomic, FixInternals, Hookean, constrained_indices) slab = fcc111('Pt', (4, 4, 4)) C1 = FixAtoms([0, 2, 4]) C2 = FixBondLengths([[0, 1], [0, 2]]) C3 = FixInternals(bonds=[[1, [7, 8]], [1, [8, 9]]]) C4 = Hookean(a1=30, a2=40, rt=1.79, k=5.) C5 = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)]) slab.set_constraint([C1, C2, C3, C4, C5]) assert all( constrained_indices(slab, (FixAtoms, FixBondLengths)) == [0, 1, 2, 4]) assert all( constrained_indices(slab, (FixBondLengths, FixLinearTriatomic)) == [0, 1, 2, 3, 4, 5]) assert all( constrained_indices(slab) == [0, 1, 2, 3, 4, 5, 7, 8, 9, 30, 40])
def main(): arg = sys.argv paras = readinputs(arg[1]) print paras start_atom = int(paras['start_atom']) end_atom = int(paras['end_atom']) shift_targets = numpy.array( [int(field) for field in paras['shift_targets'].split()]) dstrain = float(paras['dstrain']) fixed_direction = paras['fix_direction'] #read geometry p1 = read(filename=paras['start_structure'], index=0, format='vasp') bond_length = p1.get_distance(start_atom, end_atom) fixed_atoms = constrained_indices(p1) working_dir = os.getcwd() #move atoms based on the given strain and submit jobs drs = interpolate(p1[start_atom], p1[end_atom], dstrain, int(paras['njobs'])) #print new_atoms i = 0 log = open('stretch.dat', 'w') for dr in drs: for target in shift_targets: p1[target].position += dr job_i = working_dir + '/' + str(i) make_dir(job_i) write(filename=job_i + '/POSCAR', images=p1, format='vasp') fix_atoms(filename=job_i + '/POSCAR', fixed_atoms=[end_atom], fixed_direction=fixed_direction) log.write("%4d %8.6f\n" % (i, i * dstrain * bond_length)) i += 1 os.system('cp POTCAR ' + job_i) os.system('cp KPOINTS ' + job_i) os.system('cp INCAR ' + job_i) os.system('cp ' + paras['job_submit_script'] + ' ' + job_i) with cd(job_i): os.system(paras['job_submit_cmd'] + ' ' + paras['job_submit_script']) print os.getcwd(), 'is submitted' print 'Back to directory', os.getcwd()
def __init__(self, atoms, indices=None, name='vib', delta=0.01, nfree=2): assert nfree in [2, 4] self.atoms = atoms if indices is None: indices = range(len(atoms)) self.indices = np.asarray(indices) self.name = name self.delta = delta self.nfree = nfree self.H = None self.ir = None self.ram = None if str(type(self.atoms[0])) == "<class 'ase.atoms.Atoms'>": self.imagetype = 'atoms' fixed_atoms = constraints.constrained_indices(atoms[0]) allatoms = np.array(range(0, len(atoms[0]))) self.free_atoms = [i for i in allatoms if i not in fixed_atoms] self.free_list = range(0, len(self.free_atoms)) self.atom = atoms[0].copy() else: self.imagetype = 'pickle'
def main(): arg = sys.argv paras = readinputs(arg[1]) print paras target_atom = int(paras['target_atom']) #set strain fixed_direction = [int(field) for field in paras['fix_direction'].split()] #read geometry p1 = read(filename=paras['start_structure'], index=0, format='vasp') p2 = read(filename=paras['end_structure'], index=0, format='vasp') fixed_atoms = constrained_indices(p1) working_dir = os.getcwd() #move atoms based on the given strain and submit jobs print p1[target_atom] new_atoms = interpolate(p1[target_atom], p2[target_atom], int(paras['image_numb'])) #print new_atoms i = 0 for atom in new_atoms: p1[target_atom].position = atom job_i = working_dir + '/' + str(i) make_dir(job_i) write(filename=job_i + '/POSCAR', images=p1, format='vasp') fix_atoms(filename=job_i + '/POSCAR', fixed_atoms=[target_atom], fixed_directions=fixed_direction) i += 1 os.system('cp POTCAR ' + job_i) os.system('cp KPOINTS ' + job_i) os.system('cp INCAR ' + job_i) os.system('cp ' + paras['job_submit_script'] + ' ' + job_i) with cd(job_i): os.system(paras['job_submit_cmd'] + ' ' + paras['job_submit_script']) print os.getcwd(), 'is submitted' print 'Back to directory', os.getcwd()
from ase.build import fcc111 from ase.constraints import (FixAtoms, FixBondLengths, FixInternals, Hookean, constrained_indices) slab = fcc111('Pt', (4, 4, 4)) C1 = FixAtoms([0, 2, 4]) C2 = FixBondLengths([[0, 1], [0, 2]]) C3 = FixInternals(bonds=[[1, [7, 8]], [1, [8, 9]]]) C4 = Hookean(a1=30, a2=40, rt=1.79, k=5.) slab.set_constraint([C1, C2, C3, C4]) assert all( constrained_indices(slab, (FixAtoms, FixBondLengths)) == [0, 1, 2, 4]) assert all(constrained_indices(slab) == [0, 1, 2, 4, 7, 8, 9, 30, 40])
def pca_xyz(traj_dict, fig_title=None): """Perform a PCA analysis for the trajectories. Parameters ---------- traj_dict: dict Dictionary of calculation types and trajectories. e.g.: {'oal': oal_traj}, where oal_traj is an ASE Trajectory object or the path to the trajectory. or {'oal': [path_to_oal_traj, path_to_oal_db]}, where path_to_oal_traj is the path to the trajectory and path_to_oal_db is the path to the ase Database. or {'oal': [list_of_atoms]}, where the list of atoms serves as a trajectory to be read fig_title: str Title of the PCA plot. """ types = [] trajs = [] pos = [] energy = [] for key, value in traj_dict.items(): types.append(key) if isinstance(value, str): value = Trajectory(value) trajs.append(value) elif type(value) is list and type(value[0]) is Atoms: trajs.append(value) elif isinstance(value, list): traj = Trajectory(value[0]) db = connect(value[1]) dft_call = [i.id - 1 for i in db.select(check=True)] dft_traj = [traj[i] for i in dft_call] trajs.append(dft_traj) else: trajs.append(value) # assuming constraints (FixAtom) are applied to the same atoms constrained_id = constrained_indices(trajs[0][0]) for i in trajs: all_pos = [j.get_positions() for j in i] free_atom_pos = [np.delete(i, constrained_id, 0) for i in all_pos] pos.append([j.get_positions() for j in i]) energy.append([j.get_potential_energy() for j in i]) label = [] for i in range(len(types)): label += [types[i]] * len(pos[i]) attr = [] for i in range(1, np.shape(pos[0])[1] + 1): attr.append("%dx" % i) attr.append("%dy" % i) attr.append("%dz" % i) df = [] for i in range(len(pos)): reshape = np.array(pos[i]).reshape(np.shape(pos[i])[0], np.shape(pos[i])[1] * 3) df.append(pd.DataFrame(reshape, columns=attr)) df = pd.concat([df[i] for i in range(len(df))], ignore_index=True) df.insert(len(df.columns), "label", label) x = df.loc[:, attr].values x = StandardScaler().fit_transform(x) pca = PCA(n_components=2) principalComponents = pca.fit_transform(x) principalDf = pd.DataFrame( data=principalComponents, columns=["principal component 1", "principal component 2"], ) finalDf = pd.concat([principalDf, df[["label"]]], axis=1) fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(1, 1, 1) ax.set_xlabel("Principal Component 1", fontsize=15) ax.set_ylabel("Principal Component 2", fontsize=15) if fig_title is not None: ax.set_title(fig_title, fontsize=20) else: ax.set_title("Principal Component Analysis", fontsize=20) targets = types colors = energy mark = ["x", "s", "o", "^", "v", "<", ">", "D"] for target, color, mark in zip(targets, colors, mark): indicesToKeep = finalDf["label"] == target # if target == 'oal': ax.scatter( finalDf.loc[indicesToKeep, "principal component 1"], finalDf.loc[indicesToKeep, "principal component 2"], c=color, marker=mark, cmap="viridis", s=50, label=target, ) ax.plot( finalDf.loc[indicesToKeep, "principal component 1"], finalDf.loc[indicesToKeep, "principal component 2"], ) sm = plt.cm.ScalarMappable(cmap="viridis") colorbar = fig.colorbar(sm) colorbar.set_label("-log(abs(energy))") ax.legend() plt.savefig("pca.png")
bothways=True, skin=skin_arg) nl.update(atoms) adsorbate_atoms = [ index for index, atom in enumerate(atoms) if atom.symbol not in surface_atoms ] normals, mask = generate_normals(atoms, adsorbate_atoms=adsorbate_atoms, normalize_final=True) ### make sure to manually set the normals for 2-D materials, all atoms should have a normal pointing up, as all atoms are surface atoms #normals, mask = np.ones((len(atoms), 3)) * (0, 0, 1), list(range(len(atoms))) constrained = constrained_indices(atoms) mask = [index for index in mask if index not in constrained] #for index in mask: # atoms[index].tag = 1 atoms.set_velocities(normals / 10) all_sites = [] full_graph, envs = process_atoms(atoms, nl=nl, adsorbate_atoms=adsorbate_atoms, radius=3) ### here the default radii as well as grid are considered, these can also be added as args. for coord in [1, 2, 3]:
from ase.build import fcc111 from ase.constraints import (FixAtoms, FixBondLengths, FixInternals, Hookean, constrained_indices) slab = fcc111('Pt', (4, 4, 4)) C1 = FixAtoms([0, 2, 4]) C2 = FixBondLengths([[0, 1], [0, 2]]) C3 = FixInternals(bonds=[[1, [7, 8]], [1, [8, 9]]]) C4 = Hookean(a1=30, a2=40, rt=1.79, k=5.) slab.set_constraint([C1, C2, C3, C4]) assert all(constrained_indices(slab, (FixAtoms, FixBondLengths)) == [0, 1, 2, 4]) assert all(constrained_indices(slab) == [0, 1, 2, 4, 7, 8, 9, 30, 40])
def main(): arg = sys.argv paras = readinputs(arg[1]) print paras boundary_atoms = numpy.array( [float(field) for field in paras['boundary_atoms'].split()]) #numpy.array([0, 1, 2, 38, 39]) boundary = numpy.array( [float(field) for field in paras['boundary'].split()]) #([0, 4.407, 0]) strain = numpy.array([float(field) for field in paras['strain'].split()]) strain_direction = paras['strain_direction'] span = float(paras['span']) active_space = ([field for field in paras['active_space'].split()]) #initialize strain for each direction dx = numpy.zeros(len(strain)) dy = dx dz = dx #set strain if strain_direction == 'x': dx = strain fixed_direction = 1 if strain_direction == 'y': dy = strain fixed_direction = 2 if strain_direction == 'z': dz = strain fixed_direction = 3 #read geometry p1 = read(filename=paras['structure_file'], index=0, format='vasp') fixed_atoms = constrained_indices(p1) working_dir = os.getcwd() #move atoms based on the given strain and submit jobs stretched = open('streched.dat', 'w') for i in range(0, len(strain)): p2 = p1.copy() for atom in p2: if atom.index in fixed_atoms or atom.symbol not in active_space: continue #move atoms at the boundary. Keep the original shape of the boundary if atom.index in boundary_atoms: atom.position = atom.position + (span * dx[i], span * dy[i], span * dz[i]) continue #move other atoms. #atom.position = tuple(boundary + (numpy.array(atom.position) - boundary)*numpy.array([1+dx[i],1+dy[i],1+dz[i]])) if strain[i] < 0: job_i = working_dir + '/' + 'c_' + str(i) else: job_i = working_dir + '/' + str(i) stretched.write("%4d %12.8f \n" % (i, span * strain[i])) make_dir(job_i) write(filename=job_i + '/POSCAR', images=p2, format='vasp') fix_atoms(filename=job_i + '/POSCAR', fixed_atoms=boundary_atoms, fixed_direction=fixed_direction) os.system('cp POTCAR ' + job_i) os.system('cp KPOINTS ' + job_i) os.system('cp INCAR ' + job_i) os.system('cp ' + paras['job_submit_script'] + ' ' + job_i) with cd(job_i): os.system(paras['job_submit_cmd'] + ' ' + paras['job_submit_script']) print os.getcwd(), 'is submitted' print 'Back to directory', os.getcwd()
from ase.build import fcc111 from ase.constraints import (FixAtoms, FixBondLengths, FixLinearTriatomic, FixInternals, Hookean, constrained_indices) slab = fcc111('Pt', (4, 4, 4)) C1 = FixAtoms([0, 2, 4]) C2 = FixBondLengths([[0, 1], [0, 2]]) C3 = FixInternals(bonds=[[1, [7, 8]], [1, [8, 9]]]) C4 = Hookean(a1=30, a2=40, rt=1.79, k=5.) C5 = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)]) slab.set_constraint([C1, C2, C3, C4, C5]) assert all( constrained_indices(slab, (FixAtoms, FixBondLengths)) == [0, 1, 2, 4]) assert all( constrained_indices(slab, (FixBondLengths, FixLinearTriatomic)) == [0, 1, 2, 3, 4, 5]) assert all(constrained_indices(slab) == [0, 1, 2, 3, 4, 5, 7, 8, 9, 30, 40])