def equilShape(element,params,size=(10,10,10),distance=25.0,corrections=0,structure='fcc'): """ this is to use the ratio of energies to calculate the equilibrium crystal shape, cycle through a bunch of (h,k,l) indices """ slab = FaceCenteredCubic(element,directions=([[1,0,0],[0,1,0],[0,0,1]]),size=(10,10,10)) energy100 = fitFunction([1,0,0],params,corrections,structure) h100 = distance orig_positions = slab.get_positions() kept_positions = list(orig_positions) center = slab.get_center_of_mass() for h in range(-12,12): for k in range(0,9): for l in range(0,9): nvector=list([h,k,l]/numpy.sqrt(h**2+k**2+l**2)) energyhkl = fitFunction(nvector,params,corrections,structure) distancehkl = energyhkl/energy100*h100 for i in range(0,len(kept_positions)): list_to_pop = [] if numpy.dot(kept_positions[i],nvector) > distancehkl: list_to_pop.append(i) for i in list_to_pop: kept_positions.pop(i) # set up new slab with new positions number_of_atoms = len(kept_positions) elstring = str(number_of_atoms)+'Pt' new_slab = Atoms(elstring,positions=kept_positions) return new_slab
def makePerturbedLattice(self, shape=(2,2,2)): """ to make perturbed bulk structure lattice positions """ a = self.getFCCLattice() slab = FaceCenteredCubic(size = shape, symbol=self.element, latticeconstant=a) positions=slab.get_positions() perturbations = numpy.random.standard_normal(scipy.shape(positions))*a*0.05 positions += perturbations return positions
def test_antisymmetry(): size = 2 atoms = FaceCenteredCubic(size=[size, size, size], symbol='Cu', latticeconstant=2, pbc=(1, 1, 1)) vmin, vlen = get_distances(atoms.get_positions(), cell=atoms.cell, pbc=True) assert (vlen == vlen.T).all() for i, j in itertools.combinations(range(len(atoms)), 2): assert (vmin[i, j] == -vmin[j, i]).all()
def myfcc(symbol, pbc): "Make an fcc lattice with standard lattice constant" if ismaster: a = FaceCenteredCubic(symbol=symbol, size=(10,10,10), pbc=pbc) dx = 0.01 * np.sin(0.1 * np.arange(len(a) * 3)) dx.shape = (len(a),3) a.set_positions(a.get_positions() + dx) a.set_momenta(np.zeros((len(a),3))) #view(a) else: a = None if isparallel: a = MakeParallelAtoms(a, cpulayout) return a
def test_minimum_image_convention(dim): size = 2 if dim == 2: pbc = [True, True, False] else: pbc = [True, True, True] atoms = FaceCenteredCubic(size=[size, size, size], symbol='Cu', latticeconstant=2, pbc=pbc) if dim == 2: cell = atoms.cell.uncomplete(atoms.pbc) atoms.set_cell(cell, scale_atoms=False) d0 = atoms.get_distances(0, np.arange(len(atoms)), mic=True) if dim == 2: U = np.array([[1, 2, 0], [0, 1, 0], [0, 0, 1]]) else: U = np.array([[1, 2, 2], [0, 1, 2], [0, 0, 1]]) assert np.linalg.det(U) == 1 atoms.set_cell(U.T @ atoms.cell, scale_atoms=False) atoms.wrap() d1 = atoms.get_distances(0, np.arange(len(atoms)), mic=True) assert_allclose(d0, d1) vnbrlist = NeighborListMic(atoms.get_positions(), atoms.cell, atoms.pbc) d2 = np.linalg.norm(vnbrlist, axis=1) assert_allclose(d0, d2) nl = NeighborList(np.ones(len(atoms)) * 2 * size * np.sqrt(3), bothways=True, primitive=PrimitiveNeighborList) nl.update(atoms) indices, offsets = nl.get_neighbors(0) d3 = float("inf") * np.ones(len(atoms)) for i, offset in zip(indices, offsets): p = atoms.positions[i] + offset @ atoms.get_cell() d = np.linalg.norm(p - atoms.positions[0]) d3[i] = min(d3[i], d) assert_allclose(d0, d3)
def test_minimum_image_convention(): import numpy as np from numpy.testing import assert_allclose from ase.lattice.cubic import FaceCenteredCubic from ase.neighborlist import mic as NeighborListMic from ase.neighborlist import NeighborList, PrimitiveNeighborList size = 2 atoms = FaceCenteredCubic(size=[size, size, size], symbol='Cu', latticeconstant=2, pbc=(1, 1, 1)) d0 = atoms.get_distances(0, np.arange(len(atoms)), mic=True) U = np.array([[1, 2, 2], [0, 1, 2], [0, 0, 1]]) assert np.linalg.det(U) == 1 atoms.set_cell(U.T @ atoms.cell, scale_atoms=False) atoms.wrap() d1 = atoms.get_distances(0, np.arange(len(atoms)), mic=True) assert_allclose(d0, d1) vnbrlist = NeighborListMic(atoms.get_positions(), atoms.cell, atoms.pbc) d2 = np.linalg.norm(vnbrlist, axis=1) assert_allclose(d0, d2) nl = NeighborList(np.ones(len(atoms)) * 2 * size * np.sqrt(3), bothways=True, primitive=PrimitiveNeighborList) nl.update(atoms) indices, offsets = nl.get_neighbors(0) d3 = float("inf") * np.ones(len(atoms)) for i, offset in zip(indices, offsets): p = atoms.positions[i] + offset @ atoms.get_cell() d = np.linalg.norm(p - atoms.positions[0]) d3[i] = min(d3[i], d) assert_allclose(d0, d3)
def MakeAtoms(elem1, elem2=None): if elem2 is None: elem2 = elem1 a1 = reference_states[elem1]['a'] a2 = reference_states[elem2]['a'] a0 = (0.5 * a1**3 + 0.5 * a2**3)**(1.0 / 3.0) * 1.03 if ismaster: print "Z1 = %i, Z2 = %i, a0 = %.5f" % (elem1, elem2, a0) # 50*50*50 would be big enough, but some vacancies are nice. atoms = FaceCenteredCubic(symbol='Cu', size=(51, 51, 51)) nremove = len(atoms) - 500000 assert nremove > 0 remove = np.random.choice(len(atoms), nremove, replace=False) del atoms[remove] if elem1 != elem2: z = atoms.get_atomic_numbers() z[np.random.choice(len(atoms), len(atoms) / 2, replace=False)] = elem2 atoms.set_atomic_numbers(z) if isparallel: # Move this contribution into position uc = atoms.get_cell() x = mpi.world.rank % cpuLayout[0] y = (mpi.world.rank // cpuLayout[0]) % cpuLayout[1] z = mpi.world.rank // (cpuLayout[0] * cpuLayout[1]) assert (0 <= x < cpuLayout[0]) assert (0 <= y < cpuLayout[1]) assert (0 <= z < cpuLayout[2]) offset = x * uc[0] + y * uc[1] + z * uc[2] new_uc = cpuLayout[0] * uc[0] + cpuLayout[1] * uc[1] + cpuLayout[ 2] * uc[2] atoms.set_cell(new_uc, scale_atoms=False) atoms.set_positions(atoms.get_positions() + offset) # Distribute atoms. Maybe they are all on the wrong cpu, but that will # be taken care of. atoms = MakeParallelAtoms(atoms, cpuLayout) MaxwellBoltzmannDistribution(atoms, T * units.kB) return atoms
def MakeAtoms(elem1, elem2=None): if elem2 is None: elem2 = elem1 a1 = reference_states[elem1]['a'] a2 = reference_states[elem2]['a'] a0 = (0.5 * a1**3 + 0.5 * a2**3)**(1.0/3.0) * 1.03 if ismaster: print "Z1 = %i, Z2 = %i, a0 = %.5f" % (elem1, elem2, a0) # 50*50*50 would be big enough, but some vacancies are nice. atoms = FaceCenteredCubic(symbol='Cu', size=(51,51,51)) nremove = len(atoms) - 500000 assert nremove > 0 remove = np.random.choice(len(atoms), nremove, replace=False) del atoms[remove] if elem1 != elem2: z = atoms.get_atomic_numbers() z[np.random.choice(len(atoms), len(atoms)/2, replace=False)] = elem2 atoms.set_atomic_numbers(z) if isparallel: # Move this contribution into position uc = atoms.get_cell() x = mpi.world.rank % cpuLayout[0] y = (mpi.world.rank // cpuLayout[0]) % cpuLayout[1] z = mpi.world.rank // (cpuLayout[0] * cpuLayout[1]) assert(0 <= x < cpuLayout[0]) assert(0 <= y < cpuLayout[1]) assert(0 <= z < cpuLayout[2]) offset = x * uc[0] + y * uc[1] + z * uc[2] new_uc = cpuLayout[0] * uc[0] + cpuLayout[1] * uc[1] + cpuLayout[2] * uc[2] atoms.set_cell(new_uc, scale_atoms=False) atoms.set_positions(atoms.get_positions() + offset) # Distribute atoms. Maybe they are all on the wrong cpu, but that will # be taken care of. atoms = MakeParallelAtoms(atoms, cpuLayout) MaxwellBoltzmannDistribution(atoms, T * units.kB) return atoms
print sum(a), "near old position and", sum(b), "near new position." print nr2, "atoms should be affected" ReportTest("Number of affected atoms", nr, nr2, 0) del np_atoms, np_nblist if 1: print print "Testing perturbations of all the atoms" magnarr = array((0.0, 0.01, 0.1, 1.0, 3.0, 10.0)) pick = argsort(random.random((len(magnarr),))) for magn in take(magnarr, pick): dx = magn * random.uniform(-1, 1, (len(atoms), 3)) print " Perturbation:", magn atoms.set_positions(dx + atoms.get_positions()) nblist.check_and_update(atoms) checklist(nblist, atoms, listcutoff) print print "Testing perturbations of single atoms" magnarr = array((0.0, 0.01, 0.1, 1.0, 3.0, 10.0)) pick1 = argsort(random.random((len(magnarr),))) for magn in take(magnarr, pick1): numarr = array((1, 3, 10, len(atoms)/2, -3)) pick2 = argsort(random.random((len(numarr),))) for number in take(numarr, pick2): # Pick number random atoms.
latticeconstant=2, pbc=(1, 1, 1)) d0 = atoms.get_distances(0, np.arange(len(atoms)), mic=True) U = np.array([[1, 2, 2], [0, 1, 2], [0, 0, 1]]) assert np.linalg.det(U) == 1 atoms.set_cell(U.T @ atoms.cell, scale_atoms=False) atoms.wrap() d1 = atoms.get_distances(0, np.arange(len(atoms)), mic=True) assert_allclose(d0, d1) vnbrlist = NeighborListMic(atoms.get_positions(), atoms.cell, atoms.pbc) d2 = np.linalg.norm(vnbrlist, axis=1) assert_allclose(d0, d2) nl = NeighborList(np.ones(len(atoms)) * 2 * size * np.sqrt(3), bothways=True, primitive=PrimitiveNeighborList) nl.update(atoms) indices, offsets = nl.get_neighbors(0) d3 = float("inf") * np.ones(len(atoms)) for i, offset in zip(indices, offsets): p = atoms.positions[i] + offset @ atoms.get_cell() d = np.linalg.norm(p - atoms.positions[0]) d3[i] = min(d3[i], d)
host = "niflheim-d512" elif re.match("^[stu]\d\d\d.dcsc.fysik.dtu.dk$", host): print " This is an s50 node on Niflheim." fullhost = "niflheim-s50/%s" % (host.split(".")[0]) host = "niflheim-s50" else: fullhost = host print "Current time is "+when print "" print "Preparing system" initial = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(30, 30, 30), symbol="Cu") ReportTest("Number of atoms", len(initial), 108000, 0) r = initial.get_positions() r.flat[:] += 0.14 * sin(arange(3*len(initial))) initial.set_positions(r) print "Running self-test." atoms = Atoms(initial) #atoms.set_calculator(EMT()) atoms.set_calculator(OpenKIMcalculator('EMT_Asap_Standard_AlAgAuCuNiPdPt__MO_118428466217_000')) e = atoms.get_potential_energies() f = atoms.get_forces() if os.access(selfcheckfilename, os.F_OK): olde, oldf = cPickle.load(open(selfcheckfilename)) de = max(fabs(e - olde)) df = max(fabs(f.flat[:] - oldf.flat[:])) print "Maximal deviation: Energy", de, " Force", df ReportTest("Max force error", df, 0.0, 1e-11)
boundaries = ((1,1,1),) elif nbltype == "CLUSTER": boundaries = ((0,0,0),) else: boundaries = ((1,1,1), (0,0,0), (0,0,1)) for pbc in boundaries: txt = nbltype + (" PBC=%1i%1i%1i " % pbc) # Test that EMT reimported through OpenKIM gives the right results. atoms_kim = FaceCenteredCubic(size=(10,10,10), symbol='Cu') #atoms_kim = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], # size=(30, 30, 30), # symbol="Cu") natoms = len(atoms_kim) atoms_kim.set_pbc(pbc) r = atoms_kim.get_positions() r.flat[:] += 0.1 * np.sin(np.arange(3*natoms)) atoms_kim.set_positions(r) atoms_emt = atoms_kim.copy() kim = OpenKIMcalculator(openkimmodel, allowed=nbltype) emt = EMT() emt.set_subtractE0(False) atoms_kim.set_calculator(kim) atoms_emt.set_calculator(emt) ek = atoms_kim.get_potential_energy() ee = atoms_emt.get_potential_energy() ReportTest(txt+"Total energy", ek, ee, 1e-8) ek = atoms_kim.get_potential_energies() ee = atoms_emt.get_potential_energies() for i in range(0, natoms, step): ReportTest(txt+"Energy of atom %i" % (i,), ek[i], ee[i], 1e-8)
#AsapThreads() cpulayout = (1,1,2) element = 'Pt' size = (20,20,100) master = world.rank == 0 if master: atoms = FaceCenteredCubic(symbol=element, size=size, pbc=(True, True, False)) atoms.center(vacuum=10.0, axis=2) atoms.set_momenta(np.zeros((len(atoms),3))) # Select an atom to get a kick r = atoms.get_positions() uc = atoms.get_cell() x = r[:,0] - 0.5 * uc[0,0] y = r[:,1] - 0.5 * uc[1,1] z = r[:,2] zprime = z - 0.01 * (x * x + y * y) n = np.argmax(zprime) #a = atoms[n] #dp = np.sqrt(2 * a.mass * 1000.0) #a.momentum = np.array([0, 0, dp]) t = np.zeros(len(atoms), int) t[n] = 1 atoms.set_tags(t) else: atoms = None atoms = MakeParallelAtoms(atoms, cpulayout)
host = "niflheim-d512" elif re.match("^[stu]\d\d\d.dcsc.fysik.dtu.dk$", host): print " This is an s50 node on Niflheim." fullhost = "niflheim-s50/%s" % (host.split(".")[0]) host = "niflheim-s50" else: fullhost = host print "Current time is "+when print "" print "Preparing system" initial = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(30, 30, 30), symbol="Pt") ReportTest("Number of atoms", len(initial), 108000, 0) r = initial.get_positions() r.flat[:] += 0.14 * sin(arange(3*len(initial))) initial.set_positions(r) print "Running self-test." atoms = Atoms(initial) atoms.set_calculator(EMT2013(PtY_parameters)) e = atoms.get_potential_energies() f = atoms.get_forces() if os.access(selfcheckfilename, os.F_OK): olde, oldf = cPickle.load(open(selfcheckfilename)) de = max(fabs(e - olde)) df = max(fabs(f.flat[:] - oldf.flat[:])) print "Maximal deviation: Energy", de, " Force", df ReportTest("Max force error", df, 0.0, 1e-11) ReportTest("Max energy error", de, 0.0, 1e-11)
numbers = count.keys() numbers.sort() sum = 0 for i in numbers: #print i, count[i] sum += i*count[i] ReportTest("Number of neighbors (EMT's NB list)", sum, 21*len(atoms), 0) nblist = NeighborList(latconst * 0.5 * (1/sqrt(2) + 1), atoms, 0.0) #nblist = NeighborCellLocator(latconst * 0.5 * (1/sqrt(2) + 1), atoms, 0.0) fnb = FullNeighborList(latconst * 0.5 * (1/sqrt(2) + 1), Atoms(atoms)) TestLists(nblist, fnb, "nearest-neigbor lists (periodic)", 6) ReportTest("Energy unperturbed 1", atoms.get_potential_energy(), epot, 1e-11) atoms.set_positions(atoms.get_positions()) ReportTest("Energy unperturbed 2", atoms.get_potential_energy(), epot, 1e-11) nblist = NeighborList(4.98409, atoms, 0.0) fnb = FullNeighborList(4.98409, Atoms(atoms)) TestLists(nblist, fnb, "long neigbor lists (periodic)", 21) ReportTest("Energy unperturbed 3", atoms.get_potential_energy(), epot, 1e-11) atoms.set_positions(atoms.get_positions()) ReportTest("Energy unperturbed 4", atoms.get_potential_energy(), epot, 1e-11) atoms = Atoms(atoms, pbc=(0,0,0)) nblist = NeighborList(latconst * 0.5 * (1/sqrt(2) + 1), atoms, 0.0) fnb = FullNeighborList(latconst * 0.5 * (1/sqrt(2) + 1), Atoms(atoms)) TestLists(nblist, fnb, "nearest-neigbor lists (non-periodic)")
1, 0) ReportTest("Forces required", pot.calculation_required(atoms, ["forces"]), 1, 0) ReportTest("Stress required", pot.calculation_required(atoms, ["stress"]), 1, 0) ReportTest("Magmom required", pot.calculation_required(atoms, ["magmoms"]), 1, 0) e = atoms.get_potential_energy() ReportTest("Energy not required", pot.calculation_required(atoms, ["energy"]), 0, 0) ReportTest("Forces required (II)", pot.calculation_required(atoms, ["forces"]), 1, 0) f = atoms.get_forces() ReportTest("Energy not required (II)", pot.calculation_required(atoms, ["energy"]), 0, 0) ReportTest("Forces not required", pot.calculation_required(atoms, ["forces"]), 0, 0) ReportTest("Energy or forces not required", pot.calculation_required(atoms, ["energy", "forces"]), 0, 0) ReportTest("Energy or stress required", pot.calculation_required(atoms, ["energy", "stress"]), 1, 0) s = atoms.get_stress() ReportTest("Stress not required", pot.calculation_required(atoms, ["stress"]), 0, 0) r = atoms.get_positions() r[0, 0] += 0.1 atoms.set_positions(r) ReportTest.Summary()
# Make a small perturbation of the momenta atoms.set_momenta(1e-6 * random.random([len(atoms), 3])) print "Initializing ..." predyn = VelocityVerlet(atoms, 0.5) try: predyn.run(2500) except: print atoms.arrays['positions'] print atoms.arrays['momenta'] print atoms.arrays['momenta'].shape print atoms.get_masses() print atoms.get_masses().shape raise initr = atoms.get_positions() initp = atoms.get_momenta() def targetfunc(params, x): return params[0] * exp(-params[1] * x) + params[2] output = file("Langevin.dat", "w") for temp, frict in ((0.01, 0.001),): dyn = Langevin(atoms, timestep, temp, frict) print "" print "Testing Langevin dynamics with T = %f eV and lambda = %f" % (temp, frict) ekin = atoms.get_kinetic_energy()/natoms print ekin output.write("%.8f\n" % ekin)
directed (bool): whether the old one was directed or not """ nbr_list_reverse = torch.stack( [nbr_list[:, 0], nbr_list[:, 2], nbr_list[:, 1]], dim=-1) new_nbrs = torch.cat([nbr_list, nbr_list_reverse], dim=0) return new_nbrs if __name__ == "__main__": from ase.lattice.cubic import FaceCenteredCubic atoms = FaceCenteredCubic(symbol='H', size=(3, 3, 3), latticeconstant=1.679, pbc=True) from ase.neighborlist import neighbor_list i, j, d = neighbor_list("ijD", atoms, cutoff=2.5, self_interaction=False) print("ASE calculated {} pairs".format(i.shape[0])) xyz = torch.Tensor(atoms.get_positions()) cell = torch.Tensor(atoms.get_cell()) cutoff = 2.5 nbr_list, offsets = generate_nbr_list(xyz, cutoff, cell) print("torchmd calculated {} pairs".format(nbr_list.shape[0] * 2))
boundaries = ((1, 1, 1), ) elif nbltype == "CLUSTER": boundaries = ((0, 0, 0), ) else: boundaries = ((1, 1, 1), (0, 0, 0), (0, 0, 1)) for pbc in boundaries: txt = nbltype + (" PBC=%1i%1i%1i " % pbc) # Test that EMT reimported through OpenKIM gives the right results. atoms_kim = FaceCenteredCubic(size=(10, 10, 10), symbol='Cu') #atoms_kim = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], # size=(30, 30, 30), # symbol="Cu") natoms = len(atoms_kim) atoms_kim.set_pbc(pbc) r = atoms_kim.get_positions() r.flat[:] += 0.1 * np.sin(np.arange(3 * natoms)) atoms_kim.set_positions(r) atoms_emt = atoms_kim.copy() kim = OpenKIMcalculator(openkimmodel, allowed=nbltype) emt = EMT() emt.set_subtractE0(False) atoms_kim.set_calculator(kim) atoms_emt.set_calculator(emt) ek = atoms_kim.get_potential_energy() ee = atoms_emt.get_potential_energy() ReportTest(txt + "Total energy", ek, ee, 1e-8) ek = atoms_kim.get_potential_energies() ee = atoms_emt.get_potential_energies() for i in range(0, natoms, step): ReportTest(txt + "Energy of atom %i" % (i, ), ek[i], ee[i], 1e-8)
#set_verbose(1) master = world.rank == 0 if master: atoms0 = FaceCenteredCubic(symbol='Pt', size=(15, 15, 30)) else: atoms0 = None atoms0 = MakeParallelAtoms(atoms0, (1, 1, 2)) atoms0.set_calculator(pot()) print >> sys.stderr, "*********** FIRST FORCE CALCULATION ************" print >> sys.stderr, "len(atoms) =", len( atoms0), " no. atoms =", atoms0.get_number_of_atoms() f0 = atoms0.get_forces() perturbation = 0.01 * np.random.standard_normal(atoms0.get_positions().shape) r = atoms0.get_positions() + perturbation atoms0.set_positions(r) print >> sys.stderr, "*********** SECOND FORCE CALCULATION ************" f1 = atoms0.get_forces() print >> sys.stderr, "*********** COPYING ATOMS **************" atoms2 = ParallelAtoms((1, 1, 2), atoms0.comm, atoms0, distribute=False) atoms2.set_calculator(pot()) print >> sys.stderr, "*********** THIRD FORCE CALCULATION ************" f2 = atoms2.get_forces() #maxdev = abs(f2 - f1).max() #print maxdev #ReportTest("Max error 1:", maxdev, 0.0, 1e-6)
# Checks for Ticket #11 from asap3 import * from ase.lattice.cubic import FaceCenteredCubic from asap3.testtools import ReportTest print "Test for Ticket #11: https://trac.fysik.dtu.dk/projects/Asap/ticket/11" atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], size=(6, 6, 6), symbol="Cu") atoms.set_calculator(EMT()) r = atoms.get_positions() print "Orig position", r[-1] uc = atoms.get_cell() print uc r[-1] = 1.51 * uc[2] atoms.set_positions(r) print atoms.get_potential_energy() p1 = atoms.get_positions()[-1] print "p1:", p1 atoms.set_cell(uc, scale_atoms=True) print atoms.get_potential_energy() p2 = atoms.get_positions()[-1] print "p2:", p2 atoms.set_cell(uc, scale_atoms=False) print atoms.get_potential_energy()
print sum(a), "near old position and", sum(b), "near new position." print nr2, "atoms should be affected" ReportTest("Number of affected atoms", nr, nr2, 0) del np_atoms, np_nblist if 1: print print "Testing perturbations of all the atoms" magnarr = array((0.0, 0.01, 0.1, 1.0, 3.0, 10.0)) pick = argsort(random.random((len(magnarr), ))) for magn in take(magnarr, pick): dx = magn * random.uniform(-1, 1, (len(atoms), 3)) print " Perturbation:", magn atoms.set_positions(dx + atoms.get_positions()) nblist.check_and_update(atoms) checklist(nblist, atoms, listcutoff) print print "Testing perturbations of single atoms" magnarr = array((0.0, 0.01, 0.1, 1.0, 3.0, 10.0)) pick1 = argsort(random.random((len(magnarr), ))) for magn in take(magnarr, pick1): numarr = array((1, 3, 10, len(atoms) / 2, -3)) pick2 = argsort(random.random((len(numarr), ))) for number in take(numarr, pick2): # Pick number random atoms. if number < 0: # Find N neighboring atoms and perturb them
#set_verbose(1) ismaster = world.rank == 0 isparallel = world.size != 1 if world.size == 1: cpulayout = None elif world.size == 2: cpulayout = [2,1,1] elif world.size == 3: cpulayout = [1,3,1] elif world.size == 4: cpulayout = [2,1,2] if ismaster: init = FaceCenteredCubic(size=(10,10,10), symbol='Cu', pbc=False) z = init.get_positions()[:,2] fixedatoms = np.less(z, 0.501*z.max()) print len(init), sum(fixedatoms) MaxwellBoltzmannDistribution(init, 6000*units.kB) init.set_tags(fixedatoms) else: init = None print print "Running simulation with Filter" atoms1 = MakeParallelAtoms(init, cpulayout) atoms1.arrays['r_init'] = atoms1.get_positions() atoms1.set_calculator(EMT()) atoms1a = Filter(atoms1, mask=np.logical_not(atoms1.get_tags())) dyn = VelocityVerlet(atoms1a, 3*units.fs)
from ase.lattice.cubic import FaceCenteredCubic from ase.io import * from ase.visualize import view import math a = float(input("Ingrese parametro de red : ")) arc = open("fcc_108000.txt","w") atomos = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(30,30,30),symbol='Cu',pbc=(1,1,1),latticeconstant=a) posi = atomos.get_positions() simbol = atomos.get_chemical_symbols() arc.write(str(len(simbol))+"\n") for i in range(len(simbol)): arc.write(str(posi[i,0])+" ") arc.write(str(posi[i,1])+" ") arc.write(str(posi[i,2])+"\n") #----Luego borrar----# #write('fcc_108000.txt',atomos,format='xyz') pos = atomos.get_positions() c_m = atomos.get_center_of_mass() coor_x = pos[:,0] coor_y = pos[:,1] coor_z = pos[:,2] print "posicion de cero",pos[0] print "centro de masa", c_m print "x_max y x_min:",coor_x.max(),coor_x.min()
def get_structure(self, name, elements, a=None, c=None, l=None): # Check number of elements if name[:3] in ['fcc', 'hcp']: if len(elements) != 1: raise ValueError("Tuple of elements must be of length one") if name[:3] in ['l12', 'l10'] or name[:2] == 'B2': if len(elements) != 2: raise ValueError("Tuple of elements must be of length two") # Get lattice constants if a is None: if name[:2] == 'B2': a = self.get_lattice_constant_a(name[:2], elements) elif name[:3] in ['fcc', 'hcp', 'bcc', 'l12', 'l10']: a = self.get_lattice_constant_a(name[:3], elements) if c is None: if name[:3] in ['hcp', 'l10']: c = self.get_lattice_constant_c(name[:3], elements) # Get size if name in ['fcc', 'hcp', 'bcc', 'l12', 'l10', 'B2']: size = self.properties[name + '_size'] elif name in ['fcc100', 'fcc111', 'hcp0001']: size = self.properties[name + '_size'][:2] + (l, ) # Make structure if name == 'fcc': atoms = FaceCenteredCubic(symbol=elements[0], size=size, latticeconstant=a) elif name == 'hcp': atoms = HexagonalClosedPacked(symbol=elements[0], size=size, directions=[[2, -1, -1, 0], [0, 1, -1, 0], [0, 0, 0, 1]], latticeconstant=(a, c)) elif name == 'bcc': atoms = BodyCenteredCubic(symbol=elements[0], size=size, latticeconstant=a) elif name == 'B2': atoms = B2(symbol=elements, size=size, latticeconstant=a) elif name == 'l12': atoms = L1_2(symbol=elements, size=size, latticeconstant=a) elif name == 'l10': atoms = L1_0(symbol=elements, size=size, latticeconstant=(a, c)) elif name == 'fcc100': atoms = fcc100(symbol=elements[0], size=size, a=a, vacuum=10.0) elif name == 'fcc111': atoms = fcc111(symbol=elements[0], size=size, a=a, vacuum=10.0, orthogonal=True) elif name == 'hcp0001': atoms = hcp0001(symbol=elements[0], size=size, a=a, c=c, vacuum=10.0, orthogonal=True) elif name == 'hcp1010A': raise ValueError("Structure '%s' not supported" % (name, )) atoms = None elif name == 'hcp1010B': raise ValueError("Structure '%s' not supported" % (name, )) atoms = None elif name == 'l12100': n = (l + 1) / 2 atoms = L1_2(symbol=elements, size=(8, 8, n), latticeconstant=a) atoms.set_pbc([True, True, False]) # Remove layers atoms = atoms[atoms.get_positions()[:, 2] > 0.1 * a] # Set vacuum atoms.center(axis=2, vacuum=10.0) elif name == 'l12111': if l % 3 == 0: n = l / 3 c = 0 else: n = l / 3 + 1 c = 3 - l % 3 atoms = L1_2( symbol=elements, size=(8, 4, n), #directions=[[1,-1,0],[1,0,-1],[1,1,1]], latticeconstant=a) directions=[[1, -1, 0], [1, 1, -2], [1, 1, 1]], latticeconstant=a) atoms.set_pbc([True, True, False]) # Wrap positions scpos = atoms.get_scaled_positions() scpos[scpos > (1.0 - 1e-12)] = 0.0 atoms.set_scaled_positions(scpos) # Remove layers if c > 0: atoms = atoms[atoms.get_positions()[:, 2] > (c - 0.5) * a / np.sqrt(3.0)] # Set vacuum atoms.center(axis=2, vacuum=10.0) else: raise ValueError("Structure '%s' not supported" % (name, )) return atoms
radius = 15 size = [14, 10, 100] # radius = 30 # size = [28, 20, 100] # 51500 atoms a = FaceCenteredCubic('Au', directions=[[1, 0, -1], [0, 1, 0], [1, 0, 1]], size=size) c = a.cell.diagonal() / 2 dir1 = [sqrt(2), 1, 0] dir2 = [sqrt(2), -1, 0] dir3 = [0, 1, 0] dir1 = np.array(dir1) / np.linalg.norm(dir1) dir2 = np.array(dir2) / np.linalg.norm(dir2) dir3 = np.array(dir3) / np.linalg.norm(dir3) r = a.get_positions() - c m = np.abs(r.dot(dir1)) > radius m = np.logical_or(m, np.abs(r.dot(dir2)) > radius) m = np.logical_or(m, np.abs(r.dot(dir3)) > radius) del a[m] a.center() a.set_pbc([False, False, True]) io.write('whisker.xyz', a) io.write('whisker.data', a, format='lammps-data')
def __init__(self, symbol=None, layers=None, positions=None, latticeconstant=None, symmetry=None, cell=None, center=None, multiplicity=1, filename=None, debug=0): self.debug = debug self.multiplicity = multiplicity if filename is not None: # We skip MonteCarloAtoms.__init__, do it manually. self.mc_optim = np.zeros(101, np.intc) self.mc_optim[0] = 10000 # MC optim invalid self.read(filename) return #Find the atomic number if symbol is not None: if isinstance(symbol, str): self.atomic_number = atomic_numbers[symbol] else: self.atomic_number = symbol else: raise Warning('You must specify a atomic symbol or number!') #Find the crystal structure if symmetry is not None: if symmetry.lower() in ['bcc', 'fcc', 'hcp']: self.symmetry = symmetry.lower() else: raise Warning('The %s symmetry does not exist!' % symmetry.lower()) else: self.symmetry = reference_states[ self.atomic_number]['symmetry'].lower() if self.debug: print 'Crystal structure:', self.symmetry #Find the lattice constant if latticeconstant is None: if self.symmetry == 'fcc': self.lattice_constant = reference_states[ self.atomic_number]['a'] else: raise Warning(('Cannot find the lattice constant ' + 'for a %s structure!' % self.symmetry)) else: self.lattice_constant = latticeconstant if self.debug: print 'Lattice constant(s):', self.lattice_constant #Make the cluster of atoms if layers is not None and positions is None: layers = list(layers) #Make base crystal based on the found symmetry if self.symmetry == 'fcc': if len(layers) != data.lattice[self.symmetry]['surface_count']: raise Warning( 'Something is wrong with the defined number of layers!' ) xc = int(np.ceil(layers[1] / 2.0)) + 1 yc = int(np.ceil(layers[3] / 2.0)) + 1 zc = int(np.ceil(layers[5] / 2.0)) + 1 xs = xc + int(np.ceil(layers[0] / 2.0)) + 1 ys = yc + int(np.ceil(layers[2] / 2.0)) + 1 zs = zc + int(np.ceil(layers[4] / 2.0)) + 1 center = np.array((xc, yc, zc)) * self.lattice_constant size = (xs, ys, zs) if self.debug: print 'Base crystal size:', size print 'Center cell position:', center atoms = FaceCenteredCubic( symbol=symbol, size=size, latticeconstant=self.lattice_constant, align=False) else: raise Warning( ('The %s crystal structure is not' + ' supported yet.') % self.symmetry) positions = atoms.get_positions() numbers = atoms.get_atomic_numbers() cell = atoms.get_cell() elif positions is not None: numbers = [self.atomic_number] * len(positions) else: numbers = None #Load the constructed atoms object into this object self.set_center(center) MonteCarloAtoms.__init__(self, numbers=numbers, positions=positions, cell=cell, pbc=False) #Construct the particle with the assigned surfasces if layers is not None: self.set_layers(layers)
def __init__(self, symbol=None, layers=None, positions=None, latticeconstant=None, symmetry=None, cell=None, center=None, multiplicity=1, filename=None, debug=0): self.debug = debug self.multiplicity = multiplicity if filename is not None: # We skip MonteCarloAtoms.__init__, do it manually. self.mc_optim = np.zeros(101, np.intc) self.mc_optim[0] = 10000 # MC optim invalid self.read(filename) return #Find the atomic number if symbol is not None: if isinstance(symbol, str): self.atomic_number = atomic_numbers[symbol] else: self.atomic_number = symbol else: raise Warning('You must specify a atomic symbol or number!') #Find the crystal structure if symmetry is not None: if symmetry.lower() in ['bcc', 'fcc', 'hcp']: self.symmetry = symmetry.lower() else: raise Warning('The %s symmetry does not exist!' % symmetry.lower()) else: self.symmetry = reference_states[self.atomic_number]['symmetry'].lower() if self.debug: print 'Crystal structure:', self.symmetry #Find the lattice constant if latticeconstant is None: if self.symmetry == 'fcc': self.lattice_constant = reference_states[self.atomic_number]['a'] else: raise Warning(('Cannot find the lattice constant ' + 'for a %s structure!' % self.symmetry)) else: self.lattice_constant = latticeconstant if self.debug: print 'Lattice constant(s):', self.lattice_constant #Make the cluster of atoms if layers is not None and positions is None: layers = list(layers) #Make base crystal based on the found symmetry if self.symmetry == 'fcc': if len(layers) != data.lattice[self.symmetry]['surface_count']: raise Warning('Something is wrong with the defined number of layers!') xc = int(np.ceil(layers[1] / 2.0)) + 1 yc = int(np.ceil(layers[3] / 2.0)) + 1 zc = int(np.ceil(layers[5] / 2.0)) + 1 xs = xc + int(np.ceil(layers[0] / 2.0)) + 1 ys = yc + int(np.ceil(layers[2] / 2.0)) + 1 zs = zc + int(np.ceil(layers[4] / 2.0)) + 1 center = np.array((xc, yc, zc)) * self.lattice_constant size = (xs, ys, zs) if self.debug: print 'Base crystal size:', size print 'Center cell position:', center atoms = FaceCenteredCubic(symbol=symbol, size=size, latticeconstant=self.lattice_constant, align=False) else: raise Warning(('The %s crystal structure is not' + ' supported yet.') % self.symmetry) positions = atoms.get_positions() numbers = atoms.get_atomic_numbers() cell = atoms.get_cell() elif positions is not None: numbers = [self.atomic_number] * len(positions) else: numbers = None #Load the constructed atoms object into this object self.set_center(center) MonteCarloAtoms.__init__(self, numbers=numbers, positions=positions, cell=cell, pbc=False) #Construct the particle with the assigned surfasces if layers is not None: self.set_layers(layers)
print " Periodic boundary conditions: %s" % (str(v),) elif k == 'natoms': print " Number of atoms: %i" % (v,) elif hasattr(v, 'shape'): print " %s: shape = %s, type = %s" % (k, str(v.shape), str(v.dtype)) else: print " %s: %s" % (k, str(v)) # Read info from separate files. for k, v in metadata['datatypes'].items(): if v and not k in small: info = backend.read_info(frame, k) if info and isinstance(info[0], tuple): shape, dtype = info else: shape = info dtype = 'unknown' print " %s: shape = %s, type = %s" % (k, str(shape), dtype) if __name__ == '__main__': from ase.lattice.cubic import FaceCenteredCubic from ase.io import read, write atoms = FaceCenteredCubic(size=(5, 5, 5), symbol='Au') write('test.bundle', atoms) atoms2 = read('test.bundle') assert (atoms.get_positions() == atoms2.get_positions()).all() assert (atoms.get_atomic_numbers() == atoms2.get_atomic_numbers()).all()
# Checks for Ticket #11 from asap3 import * from ase.lattice.cubic import FaceCenteredCubic from asap3.testtools import ReportTest print "Test for Ticket #11: https://trac.fysik.dtu.dk/projects/Asap/ticket/11" atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(6,6,6), symbol="Cu") atoms.set_calculator(EMT()) r = atoms.get_positions() print "Orig position", r[-1] uc = atoms.get_cell() print uc r[-1] = 1.51*uc[2] atoms.set_positions(r) print atoms.get_potential_energy() p1 = atoms.get_positions()[-1] print "p1:", p1 atoms.set_cell(uc, scale_atoms=True) print atoms.get_potential_energy() p2 = atoms.get_positions()[-1] print "p2:", p2 atoms.set_cell(uc, scale_atoms=False) print atoms.get_potential_energy() p3 = atoms.get_positions()[-1]