def breed(particles,objects,gen): sortedIndices = numpy.argsort(numpy.asarray(objects)) particlestobreed = [] explambda = numpy.log(10) / (NPsPerGen - 1) for i in range(len(particles)): trialvar = numpy.random.random() if (trialvar <= numpy.exp(-1 * explambda * i)): particlestobreed.append(particles[sortedIndices[i]]) NewGen = [] for i in range(NPsPerGen): first = numpy.random.randint(len(particlestobreed)) second = numpy.random.randint(len(particlestobreed)) gene1 = numpy.random.randint(2) gene2 = numpy.random.randint(2) if (gene1 == 0): type1 = particlestobreed[first].gene[0] else: type1 = particlestobreed[second].gene[0] if (gene2 == 0): type2 = particlestobreed[first].gene[1] else: type2 = particlestobreed[second].gene[1] if (particlestobreed[first].gene[2] < particlestobreed[second].gene[2]): minval = particlestobreed[first].gene[2] maxval = particlestobreed[second].gene[2] else: minval = particlestobreed[second].gene[2] maxval = particlestobreed[first].gene[2] numbertype1 = numpy.random.randint(minval, maxval + 1) NewGen.append(createparticle(type1,type2,numbertype1)) traj = PickleTrajectory('generation'+str(gen)+ '_' + str(i) + '.traj','w') NewGen[i].gene = (type1,type2,numbertype1) traj.write(ParticleList[i]) traj.close() return NewGen
def fit_volume(self, name, atoms, data=None): N, x = self.fit cell0 = atoms.get_cell() v = atoms.get_volume() if x > 0: strains = np.linspace(1 - x, 1 + x, N) else: strains = np.linspace(1 + x / v, 1 - x / v, N)**(1./3) energies = [] traj = PickleTrajectory(self.get_filename(name, 'fit.traj'), 'w') for s in strains: atoms.set_cell(cell0 * s, scale_atoms=True) energies.append(atoms.get_potential_energy()) traj.write(atoms) traj.close() if data is not None: data['strains'] = strains data['energies'] = energies else: assert N % 2 == 1 data = {'energy': energies[N // 2], 'strains': strains, 'energies': energies} return data
def __init__(self, atoms, temperature=100 * kB, optimizer=FIRE, fmax=0.1, dr=0.1, logfile='-', trajectory='lowest.traj', optimizer_logfile='-', local_minima_trajectory='local_minima.traj', adjust_cm=True): Dynamics.__init__(self, atoms, logfile, trajectory) self.kT = temperature self.optimizer = optimizer self.fmax = fmax self.dr = dr if adjust_cm: self.cm = atoms.get_center_of_mass() else: self.cm = None self.optimizer_logfile = optimizer_logfile self.lm_trajectory = local_minima_trajectory if isinstance(local_minima_trajectory, str): self.lm_trajectory = PickleTrajectory(local_minima_trajectory, 'w', atoms) self.initialize()
def accept_move(self): e = self.atoms.get_potential_energy() self.lists['energy'].append(e) self.lists['counts'].append(1) self.lists['coordinations'].append(self.sumcoordinations(self.surfmove.coordinations)) self.lists['types'].append(self.sumcoordinations(self.surfmove.types)) #See sumcoordinations self.lists['vac_coordinations'].append(self.sumcoordinations(self.surfmove.vacant_coordinations)) self.lists['vac_types'].append(self.sumcoordinations(self.surfmove.vacant_types)) if self.mc_step>=self.total_steps/2: if self.id_relax == None: self.id_relax = self.n_accept unrelax_energy, relax_energy = self.relax() self.lists['unrelaxed_energies'].append(unrelax_energy) self.lists['relaxed_energies'].append(relax_energy) e += relax_energy - unrelax_energy if e < self.ground_state_energy: #now store .amc in tmpfn[1] and 0000* in tmpfn[0] tmpfn = self.filename.split(".") traj = PickleTrajectory(tmpfn[0]+".traj", 'w', self.atoms, master=True, backup=False) traj.write() traj.close() #write(filename=tmpfn[0]+".traj",images=self.atoms) self.ground_state_energy = e else: self.lists['unrelaxed_energies'].append(np.nan) self.lists['relaxed_energies'].append(np.nan) self.mc_step += 1 self.n_accept += 1
def vasp2xyz(): try: from lxml import etree except ImportError: print "You need to install python-lxml." print "start parse" xml = etree.parse("vasprun.xml") calculations = xml.xpath('//calculation') print 'len(calculations)=', len(calculations) from ase.io.trajectory import PickleTrajectory atoms = io.read('POSCAR') traj = PickleTrajectory('a.traj', 'w', atoms) print "start find forces and positions" allforce = [] allpos = [] def toarr(v): x = v.text.split() return map(float, x) for i, u in enumerate(calculations): print "step : ", i forces = map(toarr, u.xpath('./varray[@name="forces"]/v')) positions = map(toarr, u.xpath( './structure/varray[@name="positions"]/v')) atoms.set_scaled_positions(positions) allforce.append(forces) allpos.append(positions) traj.write() np.save('allforce.npy', allforce) np.save('allpos.npy', allpos) passthru("ase-gui a.traj -o a.xyz ")
def __init__(self, filename, mode='r', atoms=None, master=None, backup=True): if master is not None: if atoms.get_comm().rank != 0: raise NotImplementedError("It is required that the cpu with rank 0 is the master") _PickleTrajectory.__init__(self, filename, mode, atoms, master, backup=backup)
def vasp2xyz(): try: from lxml import etree except ImportError: print "You need to install python-lxml." print "start parse" xml = etree.parse("vasprun.xml") calculations = xml.xpath('//calculation') print 'len(calculations)=', len(calculations) from ase.io.trajectory import PickleTrajectory atoms = io.read('POSCAR') traj = PickleTrajectory('a.traj', 'w', atoms) print "start find forces and positions" allforce = [] allpos = [] def toarr(v): x = v.text.split() return map(float, x) for i, u in enumerate(calculations): print "step : ", i forces = map(toarr, u.xpath('./varray[@name="forces"]/v')) positions = map(toarr, u.xpath('./structure/varray[@name="positions"]/v')) atoms.set_scaled_positions(positions) allforce.append(forces) allpos.append(positions) traj.write() np.save('allforce.npy', allforce) np.save('allpos.npy', allpos) passthru("ase-gui a.traj -o a.xyz ")
def _test_timestepping(self, t): #XXX DEBUG START if debug and os.path.isfile('%s_%d.gpw' % (self.tdname, t)): return #XXX DEBUG END timestep = self.timesteps[t] self.assertAlmostEqual(self.duration % timestep, 0.0, 12) niter = int(self.duration / timestep) ndiv = 1 #XXX traj = PickleTrajectory('%s_%d.traj' % (self.tdname, t), 'w', self.tdcalc.get_atoms()) t0 = time.time() f = paropen('%s_%d.log' % (self.tdname, t), 'w') print >>f, 'propagator: %s, duration: %6.1f as, timestep: %5.2f as, ' \ 'niter: %d' % (self.propagator, self.duration, timestep, niter) for i in range(1, niter+1): # XXX bare bones propagation without all the nonsense self.tdcalc.propagator.propagate(self.tdcalc.time, timestep * attosec_to_autime) self.tdcalc.time += timestep * attosec_to_autime self.tdcalc.niter += 1 if i % ndiv == 0: rate = 60 * ndiv / (time.time()-t0) ekin = self.tdcalc.atoms.get_kinetic_energy() epot = self.tdcalc.get_td_energy() * Hartree F_av = np.zeros((len(self.tdcalc.atoms), 3)) print >>f, 'i=%06d, time=%6.1f as, rate=%6.2f min^-1, ' \ 'ekin=%13.9f eV, epot=%13.9f eV, etot=%13.9f eV' \ % (i, timestep * i, rate, ekin, epot, ekin + epot) t0 = time.time() # Hack to prevent calls to GPAW::get_potential_energy when saving spa = self.tdcalc.get_atoms() spc = SinglePointCalculator(epot, F_av, None, None, spa) spa.set_calculator(spc) traj.write(spa) f.close() traj.close() self.tdcalc.write('%s_%d.gpw' % (self.tdname, t), mode='all') # Save density and wavefunctions to binary gd, finegd = self.tdcalc.wfs.gd, self.tdcalc.density.finegd if world.rank == 0: big_nt_g = finegd.collect(self.tdcalc.density.nt_g) np.save('%s_%d_nt.npy' % (self.tdname, t), big_nt_g) del big_nt_g big_psit_nG = gd.collect(self.tdcalc.wfs.kpt_u[0].psit_nG) np.save('%s_%d_psit.npy' % (self.tdname, t), big_psit_nG) del big_psit_nG else: finegd.collect(self.tdcalc.density.nt_g) gd.collect(self.tdcalc.wfs.kpt_u[0].psit_nG) world.barrier()
def do_calculations(self, formulas): """Perform calculation on molecules, write results to .gpw files.""" atoms = {} for formula in formulas: for symbol in string2symbols(formula.split('_')[0]): atoms[symbol] = None formulas = formulas + atoms.keys() for formula in formulas: if path.isfile(formula + '.gpw'): continue barrier() open(formula + '.gpw', 'w') s = molecule(formula) s.center(vacuum=self.vacuum) cell = s.get_cell() h = self.h s.set_cell((cell / (4 * h)).round() * 4 * h) s.center() calc = GPAW(h=h, xc=self.xc, eigensolver=self.eigensolver, setups=self.setups, basis=self.basis, fixmom=True, txt=formula + '.txt') if len(s) == 1: calc.set(hund=True) s.set_calculator(calc) if formula == 'BeH': calc.initialize(s) calc.nuclei[0].f_si = [(1, 0, 0.5, 0, 0), (0.5, 0, 0, 0, 0)] if formula in ['NO', 'ClO', 'CH']: s.positions[:, 1] += h * 1.5 try: energy = s.get_potential_energy() except (RuntimeError, ConvergenceError): if rank == 0: print >> sys.stderr, 'Error in', formula traceback.print_exc(file=sys.stderr) else: print >> self.txt, formula, repr(energy) self.txt.flush() calc.write(formula) if formula in diatomic and self.calculate_dimer_bond_lengths: traj = PickleTrajectory(formula + '.traj', 'w') d = diatomic[formula][1] for x in range(-2, 3): s.set_distance(0, 1, d * (1.0 + x * 0.02)) traj.write(s)
def hyster_study(edge, folder=None): if folder == None: folder = os.getcwd() print folder for fileC in os.listdir(folder): if fileC[-6:] == '.simul': fileC = folder + fileC _, length, _, _, v, T, dt, fric, dtheta, \ thresZ, interval, deltaY, theta, M, edge = read_simul_params_file(fileC) mdfile = fileC[:-6] + '.traj' traj = PickleTrajectory(mdfile, 'r') atoms_init = traj[0] constraints, _, twist, rend_b, rend_t = get_constraints(atoms_init, edge, \ bond, None, key = 'twist_p') #constraints, _, rend_b, rend_t = get_constraints(atoms_init, edge, \ # bond, None, key = 'twist_p') atoms = traj[-1] atoms.set_constraint(constraints) vels = (traj[-2].positions - traj[-1].positions) / (interval * dt) atoms.set_velocities(vels) calc = LAMMPS(parameters=get_lammps_params()) atoms.set_calculator(calc) view(atoms) dyn = Langevin(atoms, dt * units.fs, T * units.kB, fric) twist.set_angle(theta) dyn.run(10 * interval) view(atoms) traj_new = PickleTrajectory(fileC[:-6] + '_hyst.traj', 'w', atoms) mdlogf = fileC[:-6] + '_hyst.log' do_dynamics(mdlogf, atoms, dyn, rend_b, rend_t, v, dt, deltaY, \ theta, dtheta, length, thresZ, \ interval, traj_new, M, twist) mdhystf = fileC[:-6] + '_hyst.traj' logfile = fileC[:-6] + '.log' append_files(logfile, mdlogf, logfile[:-4] + '_comp.log') call([ 'ase-gui', mdfile, mdhystf, '-o', logfile[:-4] + '_comp.traj' ])
def write_cp2k_traj_file(self, wrkdir): pos_path = wrkdir + "/" + self.directory + "/" + "cp2k-pos-1.xyz" if os.path.exists(pos_path): traj_path = wrkdir + "/" + self.directory + "/" + self.filename + ".traj" start_atoms = self.get_initial_structure() index = 0 if not os.path.exists(traj_path): result_atoms = ase.io.read(pos_path, index) result_atoms.set_cell(start_atoms.get_cell()) result_atoms.set_pbc(start_atoms.get_pbc()) if start_atoms.constraints is not None: for constraint in start_atoms.constraints: result_atoms.set_constraint(constraint) traj = PickleTrajectory(traj_path, mode="w", atoms=result_atoms) traj.write() index = 1 traj = PickleTrajectory(traj_path, mode="a") while True: try: result_atoms = ase.io.read(pos_path, index) result_atoms.set_cell(start_atoms.get_cell()) result_atoms.set_pbc(start_atoms.get_pbc()) if start_atoms.constraints is not None: for constraint in start_atoms.constraints: result_atoms.set_constraint(constraint) traj.write(result_atoms) index += 1 except: break os.remove(pos_path) else: if self.debug: print "%s does not exist. Not writing anything." % pos_path
def write_mode(self, n, kT=units.kB * 300, nimages=30): """Write mode to trajectory file.""" mode = self.get_mode(n) * sqrt(kT / self.hnu[n]) p = self.atoms.positions.copy() n %= 3 * len(self.indices) traj = PickleTrajectory('%s.%d.traj' % (self.name, n), 'w') calc = self.atoms.get_calculator() self.atoms.set_calculator() for x in np.linspace(0, 2 * pi, nimages, endpoint=False): self.atoms.set_positions(p + sin(x) * mode) traj.write(self.atoms) self.atoms.set_positions(p) self.atoms.set_calculator(calc) traj.close()
def get_log_data(ia, T, key, Wis=range(1, 20)): path = '/space/tohekorh/ShearSlide/files/%s_%i/%s/' % (ia, T, key) data = [] print path for x in os.walk(path): folder = x[0] if folder != path: print folder if query_yes_no('Take this folder?', default="yes"): W = int(folder.split('=')[1]) if W in Wis: for filen in os.listdir(folder): if filen[-6:] == '.simul': print filen if query_yes_no('Take this file?', default="yes"): fPath = folder + '/' + filen Wval, L, wi, li, v = read_simul_params_file( fPath)[:5] if wi != W: raise logpath = fPath[:-6] + '.log' trajpath = fPath[:-6] + '.traj' atoms = PickleTrajectory(trajpath, 'r')[-1] natoms = len(atoms) data.append([ wi, li, Wval, L, natoms, v, np.loadtxt(logpath) ]) return data
def compare_trajectory(self, i_traj, calc, tables, i_par): """ Calculate the energies for the frames in the trajectory and plot them. """ frames = [] energies = [] trajectory = PickleTrajectory(self.trajectories[i_traj]) for i, image in enumerate(trajectory): e_tb = None try: atoms = Atoms(image) c = copy(calc) c.tables = tables atoms.set_calculator(c) e_tb = atoms.get_potential_energy() except Exception as ex: print(ex, file=self.txt) if e_tb != None: energies.append(e_tb) frames.append(i) delta_E = self.norm_to_isolated_atoms(trajectory[0]) for i in range(len(energies)): energies[i] += delta_E self.plot(frames, energies, i_traj, tables, i_par)
def __init__(self, atoms, timestep, integrator='verlet', trajectory=None, traj_interval=1000, logfile=None, loginterval=100): Dynamics.__init__(self, atoms, None, None) self.dt = timestep if integrator == 'verlet': self.run_style = 'verlet' else: raise RuntimeError('Unknown integrator: %s' % thermostat) if trajectory: if isinstance(trajectory, str): trajectory = PickleTrajectory(trajectory, 'w', atoms) self.attach(trajectory, interval=traj_interval) if logfile: self.attach(MDLogger(dyn=self, atoms=atoms, logfile=logfile), interval=loginterval) self.fix = None self.cell_relaxed = False
def __init__(self, filename, mode='r', atoms=None, master=None, backup=True): if master is not None: if atoms.get_comm().rank != 0: raise NotImplementedError( "It is required that the cpu with rank 0 is the master") _PickleTrajectory.__init__(self, filename, mode, atoms, master, backup=backup)
def optimizeMolecule(molecule,NMoves,creationString): bestEnergy = 0. totalMinimaFound = 0 sinceLastFind = 0 calc = QSC() molecule.set_calculator(calc) for i in range(NMoves): molecule = newMove(molecule) molecule = preventExplosions(molecule) molecule.center() sinceLastFind += 1 # do a last optimization of the structure dyn = FIRE(molecule) dyn.run(steps = 2000) newEnergy = molecule.get_potential_energy() if (newEnergy < bestEnergy): optimizedMolecule = molecule bestEnergy = newEnergy line = str(totalMinimaFound) + " " + str(molecule.get_potential_energy()) + " " + str(i) +"\n" print line f = open('EnergyList.txt','a') f.write(line) f.close() minimaList = PickleTrajectory(str(creationString),mode='a') minimaList.write(optimizedMolecule) totalMinimaFound += 1 minimaList.close() sinceLastFind = 0 elif (sinceLastFind < 200): break minimaList.close() minimaList = PickleTrajectory(str(creationString),mode='r') atomslist = [atom for atom in minimaList] ase.io.write('movie.xyz',atomslist,format='xyz') # write a movie file of our dynamics minimaList.close() return optimizedMolecule
def fit_bond_length(self, name, atoms, data): N, x = self.fit assert N % 2 == 1 d0 = atoms.get_distance(0, 1) distances = np.linspace(d0 * (1 - x), d0 * (1 + x), N) energies = [] traj = PickleTrajectory(self.get_filename(name, 'fit.traj'), 'w') for d in distances: atoms.set_distance(0, 1, d) energies.append(atoms.get_potential_energy()) self.check_occupation_numbers(atoms) traj.write(atoms) traj.close() data['distances'] = distances data['energies'] = energies
def MD(self): """Molecular Dynamic""" from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase import units from ase.md import MDLogger from ase.io.trajectory import PickleTrajectory from ase.md.langevin import Langevin from ase.md.verlet import VelocityVerlet dyndrivers = { 'Langevin': Langevin, 'None': VelocityVerlet, } useAsap = False mol = self.mol temperature = self.definedParams['temperature'] init_temperature = self.definedParams['init_temperature'] time_step = self.definedParams['time_step'] nstep = self.definedParams['nstep'] nprint = self.definedParams['nprint'] thermostat = self.definedParams['thermostat'] prop_file = os.path.join(self.definedParams['workdir'], self.definedParams['output_prefix'] + '.out') traj_file = os.path.join(self.definedParams['workdir'], self.definedParams['output_prefix'] + '.traj') MaxwellBoltzmannDistribution(mol, init_temperature * units.kB) if thermostat == 'None': dyn = VelocityVerlet(mol, time_step * units.fs) elif thermostat == 'Langevin': dyn = Langevin(mol, time_step * units.fs, temperature * units.kB, 0.01) else: raise ImplementationError( method, 'Thermostat is not implemented in the MD function') #Function to print the potential, kinetic and total energy traj = PickleTrajectory(traj_file, "a", mol) dyn.attach(MDLogger(dyn, mol, prop_file), interval=nprint) dyn.attach(traj.write, interval=nprint) dyn.run(nstep) traj.close()
def MD(self): """Molecular Dynamic""" from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase import units from ase.md import MDLogger from ase.io.trajectory import PickleTrajectory from ase.md.langevin import Langevin from ase.md.verlet import VelocityVerlet dyndrivers = { 'Langevin': Langevin, 'None': VelocityVerlet, } useAsap = False mol = self.mol temperature = self.definedParams['temperature'] init_temperature = self.definedParams['init_temperature'] time_step = self.definedParams['time_step'] nstep = self.definedParams['nstep'] nprint = self.definedParams['nprint'] thermostat = self.definedParams['thermostat'] prop_file = os.path.join(self.definedParams['workdir'], self.definedParams['output_prefix']+'.out') traj_file = os.path.join(self.definedParams['workdir'], self.definedParams['output_prefix']+'.traj') MaxwellBoltzmannDistribution(mol,init_temperature*units.kB) if thermostat == 'None': dyn = VelocityVerlet(mol, time_step*units.fs) elif thermostat == 'Langevin': dyn = Langevin(mol, time_step*units.fs, temperature*units.kB, 0.01 ) else: raise ImplementationError(method,'Thermostat is not implemented in the MD function') #Function to print the potential, kinetic and total energy traj = PickleTrajectory(traj_file,"a",mol) dyn.attach(MDLogger(dyn,mol,prop_file),interval=nprint) dyn.attach(traj.write, interval = nprint) dyn.run(nstep) traj.close()
def fit_volume(self, name, atoms): N, x = self.fit cell0 = atoms.get_cell() strains = np.linspace(1 - x, 1 + x, N) energies = [] traj = PickleTrajectory(self.get_filename(name, 'fit.traj'), 'w') for s in strains: atoms.set_cell(cell0 * s, scale_atoms=True) energies.append(atoms.get_potential_energy()) traj.write(atoms) traj.close() assert N % 2 == 1 data = {'energy': energies[N // 2], 'strains': strains, 'energies': energies} return data
def calculate(self, filename): """Run calculation and write results to file.""" self.log('Calculating', self.name, '...') config = self.atoms.copy() self.set_calculator(config, filename) traj = PickleTrajectory(filename, 'w', backup=False) cell = config.get_cell() self.energies = [] if self.fmax is not None: if (not config.constraints and not config.positions.any(axis=1).all()): # one atom is at (0,0,0) - fix it: mask = np.logical_not(config.positions.any(axis=1)) config.constraints = FixAtoms(mask=mask) dyn = LBFGS(config) dyn.attach(traj, 1, config) dyn.run(fmax=self.fmax) e = config.get_potential_energy() self.post_process(config) self.energies.append(e) elif not config.pbc.any() and len(config) == 2: # This is a dimer. self.bondlengths = [] d0 = config.get_distance(0, 1) for strain in self.strains: d = d0 * strain config.set_distance(0, 1, d) self.bondlengths.append(d) e = config.get_potential_energy() self.energies.append(e) self.post_process(config) traj.write(config) else: self.volumes = [] for strain in self.strains: config.set_cell(strain * cell, scale_atoms=True) self.volumes.append(config.get_volume()) e = config.get_potential_energy() self.energies.append(e) self.post_process(config) traj.write(config) return config
def get_corrugation_energy(atoms, constraints, bond, bottom, top, indent, m): if 'zz' in indent: xset = np.linspace(0., np.sqrt(3)*bond, m) elif 'arm' in indent: xset = np.linspace(0., 3*bond, m) atoms_init = atoms.copy() natoms = 0 for i in range(len(top)): if top[i]: natoms += 1 fix_l = FixedLine(i, [0., 0., 1.]) constraints.append(fix_l) atoms.set_constraint(constraints) def get_epot(x): new_pos = atoms_init.positions.copy() for iat in range(len(atoms)): if top[iat]: new_pos[iat][0] += x atoms.positions = new_pos e, hmin = get_optimal_h(atoms, bottom, top, natoms, False) #print x, e return e, hmin # Start to move the top layer in x direction corr_pot = np.zeros((len(xset), 3)) traj = PickleTrajectory(path + \ 'trajectories/corrugation_trajectory_%s.traj' %(indent), "w", atoms) for i, x in enumerate(xset): traj.write(get_save_atoms(atoms)) e, hmin = get_epot(x) corr_pot[i] = [x, hmin, e] np.savetxt(path + 'datas/corrugation_data_%s.data' %(indent), corr_pot) return corr_pot
def write_mode(self, n=None, kT=units.kB * 300, nimages=30): """Write mode number n to trajectory file. If n is not specified, writes all non-zero modes.""" if n == None: for index, energy in enumerate(self.get_energies()): if abs(energy) > 1e-5: self.write_mode(n=index, kT=kT, nimages=nimages) return mode = self.get_mode(n) * sqrt(kT / abs(self.hnu[n])) p = self.atoms.positions.copy() n %= 3 * len(self.indices) traj = PickleTrajectory('%s.%d.traj' % (self.name, n), 'w') calc = self.atoms.get_calculator() self.atoms.set_calculator() for x in np.linspace(0, 2 * pi, nimages, endpoint=False): self.atoms.set_positions(p + sin(x) * mode) traj.write(self.atoms) self.atoms.set_positions(p) self.atoms.set_calculator(calc) traj.close()
def calculate(self, name, atoms): #???? if self.sfmax is not None and self.fmax is not None: # this performs first relaxation of internal degrees of freedom data = OptimizeTask.calculate(self, name, atoms) # writing traj from optimizer does not work for StrainFilter! traj = PickleTrajectory(self.get_filename(name, 'traj'), 'a', atoms) sf = StrainFilter(atoms) while not self.converged(atoms, sfmax=self.sfmax, fmax=self.fmax): # take a step on the cell self.soptimize(name, sf, data, trajectory=traj) # relax internal degrees of freedom OptimizeTask.optimize(self, name, atoms, data, trajectory=traj) data['relaxed energy'] = atoms.get_potential_energy() data['relaxed volume'] = atoms.get_volume() elif self.sfmax is not None: # this performs single-point energy calculation data = OptimizeTask.calculate(self, name, atoms) sf = StrainFilter(atoms) # writing traj from optimizer does not work for StrainFilter! traj = PickleTrajectory(self.get_filename(name, 'traj'), 'w', atoms) self.soptimize(name, sf, data, trajectory=traj) data['relaxed energy'] = atoms.get_potential_energy() data['relaxed volume'] = atoms.get_volume() elif self.fmax is not None: data = OptimizeTask.calculate(self, name, atoms) else: # no optimization if self.fit is None: # only calculate single-point energy if no fit follows data = OptimizeTask.calculate(self, name, atoms) if self.fit is not None: if self.sfmax is not None or self.fmax is not None: # fit after optimization self.fit_volume(name, atoms, data) else: # fit is the only task performed data = self.fit_volume(name, atoms) return data
def fit_volume(self, name, atoms, data=None): N, x = self.fit cell0 = atoms.get_cell() v = atoms.get_volume() if x > 0: strains = np.linspace(1 - x, 1 + x, N) else: strains = np.linspace(1 + x / v, 1 - x / v, N)**(1. / 3) energies = [] traj = PickleTrajectory(self.get_filename(name, 'fit.traj'), 'w') for s in strains: atoms.set_cell(cell0 * s, scale_atoms=True) energies.append(atoms.get_potential_energy()) traj.write(atoms) traj.close() if data is not None: data['strains'] = strains data['energies'] = energies else: assert N % 2 == 1 data = { 'energy': energies[N // 2], 'strains': strains, 'energies': energies } return data
def fit_bond_length(self, name, atoms, data=None): N, x = self.fit d0 = atoms.get_distance(0, 1) distances = np.linspace(d0 * (1 - x), d0 * (1 + x), N) energies = [] traj = PickleTrajectory(self.get_filename(name, 'fit.traj'), 'w') for d in distances: atoms.set_distance(0, 1, d) energies.append(atoms.get_potential_energy()) self.check_occupation_numbers(atoms) traj.write(atoms) traj.close() if data is not None: data['distances'] = distances data['energies'] = energies else: assert N % 2 == 1 data = { 'energy': energies[N // 2], 'distances': distances, 'energies': energies } return data
def __init__(self, atoms, temperature=100 * kB, optimizer=FIRE, fmax=0.1, dr=0.1, logfile='-', trajectory='lowest.traj', optimizer_logfile='-', local_minima_trajectory='local_minima.traj', adjust_cm=True): """Parameters: atoms: Atoms object The Atoms object to operate on. trajectory: string Pickle file used to store trajectory of atomic movement. logfile: file object or str If *logfile* is a string, a file with that name will be opened. Use '-' for stdout. """ Dynamics.__init__(self, atoms, logfile, trajectory) self.kT = temperature self.optimizer = optimizer self.fmax = fmax self.dr = dr if adjust_cm: self.cm = atoms.get_center_of_mass() else: self.cm = None self.optimizer_logfile = optimizer_logfile self.lm_trajectory = local_minima_trajectory if isinstance(local_minima_trajectory, str): self.lm_trajectory = PickleTrajectory(local_minima_trajectory, 'w', atoms) self.initialize()
def eos(self, atoms, name): opts = self.opts traj = PickleTrajectory(self.get_filename(name, 'traj'), 'w', atoms) eps = 0.01 strains = np.linspace(1 - eps, 1 + eps, 5) v1 = atoms.get_volume() volumes = strains**3 * v1 energies = [] cell1 = atoms.cell for s in strains: atoms.set_cell(cell1 * s, scale_atoms=True) energies.append(atoms.get_potential_energy()) traj.write(atoms) traj.close() eos = EquationOfState(volumes, energies, opts.eos_type) v0, e0, B = eos.fit() atoms.set_cell(cell1 * (v0 / v1)**(1 / 3), scale_atoms=True) data = {'volumes': volumes, 'energies': energies, 'fitted_energy': e0, 'fitted_volume': v0, 'bulk_modulus': B, 'eos_type': opts.eos_type} return data
def _test_timestepping(self, t): #XXX DEBUG START if debug and os.path.isfile('%s_%d.gpw' % (self.tdname, t)): return #XXX DEBUG END timestep = self.timesteps[t] self.assertAlmostEqual(self.duration % timestep, 0.0, 12) niter = int(self.duration / timestep) ndiv = 1 #XXX traj = PickleTrajectory('%s_%d.traj' % (self.tdname, t), 'w', self.tdcalc.get_atoms()) t0 = time.time() f = paropen('%s_%d.log' % (self.tdname, t), 'w') print('propagator: %s, duration: %6.1f as, timestep: %5.2f as, ' \ 'niter: %d' % (self.propagator, self.duration, timestep, niter), file=f) for i in range(1, niter + 1): # XXX bare bones propagation without all the nonsense self.tdcalc.propagator.propagate(self.tdcalc.time, timestep * attosec_to_autime) self.tdcalc.time += timestep * attosec_to_autime self.tdcalc.niter += 1 if i % ndiv == 0: rate = 60 * ndiv / (time.time() - t0) ekin = self.tdcalc.atoms.get_kinetic_energy() epot = self.tdcalc.get_td_energy() * Hartree F_av = np.zeros((len(self.tdcalc.atoms), 3)) print('i=%06d, time=%6.1f as, rate=%6.2f min^-1, ' \ 'ekin=%13.9f eV, epot=%13.9f eV, etot=%13.9f eV' \ % (i, timestep * i, rate, ekin, epot, ekin + epot), file=f) t0 = time.time() # Hack to prevent calls to GPAW::get_potential_energy when saving spa = self.tdcalc.get_atoms() spc = SinglePointCalculator(epot, F_av, None, None, spa) spa.set_calculator(spc) traj.write(spa) f.close() traj.close() self.tdcalc.write('%s_%d.gpw' % (self.tdname, t), mode='all') # Save density and wavefunctions to binary gd, finegd = self.tdcalc.wfs.gd, self.tdcalc.density.finegd if world.rank == 0: big_nt_g = finegd.collect(self.tdcalc.density.nt_g) np.save('%s_%d_nt.npy' % (self.tdname, t), big_nt_g) del big_nt_g big_psit_nG = gd.collect(self.tdcalc.wfs.kpt_u[0].psit_nG) np.save('%s_%d_psit.npy' % (self.tdname, t), big_psit_nG) del big_psit_nG else: finegd.collect(self.tdcalc.density.nt_g) gd.collect(self.tdcalc.wfs.kpt_u[0].psit_nG) world.barrier()
def append_equilibrium_trajectory(self,weight,calc,traj,comment=None,label=None,color=None): """ Calculates the V'rep(r) from a given equilibrium trajectory. The trajectory is set of three (or more, albeit not necessary) frames where atoms move near their equilibrium structure. To first approximation, the energies of these frames ARE THE SAME. This method is then equivalent to append_energy_curve method for given trajectory, with a flat energy curve. * Atoms should move as parallel to the fitted bonds as possible. * Amplitude should be small enough (say, 0.01 Angstroms) parameters: =========== weight: fitting weight calc: Hotbit calculator (remember charge and k-points) traj: filename for ASE trajectory (energies need not be defined) comment: fitting comment for par-file (replaced by comment if None) label: plotting label (replaced by comment if None) color: plotting color """ traj1 = PickleTrajectory(traj) atoms2 = traj1[0].copy() calc2 = NullCalculator() atoms2.set_calculator(calc2) tmpfile = '_tmp.traj' traj2 = PickleTrajectory(tmpfile,'w',atoms2) for atoms1 in traj1: atoms2.set_positions(atoms1.get_positions()) atoms2.set_cell( atoms1.get_cell() ) atoms2.get_potential_energy() traj2.write() traj2.close() self.append_energy_curve(weight,calc,tmpfile,comment,label,color) os.remove(tmpfile) if os.path.isfile(tmpfile+'.bak'): os.remove(tmpfile+'.bak')
def plot_ref(self, i_traj): """ Plot the energies of a given trajectory as a function of the frame number. """ import pylab as pl e_dft = [] traj = PickleTrajectory(self.trajectories[i_traj]) for image in traj: e_dft.append(image.get_total_energy()) pl.plot(e_dft, c='blue', label='DFT-energies')
def plot_energies(path,md_type,title,t0_histo,bin_histo,write=False): traj = PickleTrajectory(path+md_type+'.traj') ref_e = traj[0].get_total_energy() ref_epot = traj[0].get_potential_energy() e = [ atoms.get_total_energy() - ref_e for atoms in traj] ekin = [ atoms.get_kinetic_energy() for atoms in traj] epot = [ atoms.get_potential_energy() - ref_epot for atoms in traj] temp = [ atoms.get_temperature() for atoms in traj] plt.figure(1) plt.title(title) plt.ylabel('Energy [eV]') plt.xlabel('Time [fs]') plt.plot( e, 'g-' , label=r'Etot[t]-Etot[0]') plt.legend(loc='upper right') if write: plt.savefig(md_type+'_etot.eps', format='eps') plt.savefig(pp, format='pdf') plt.figure(2) plt.subplot(211) plt.title(title) plt.ylabel('Energy [eV]') plt.xlabel('Time [fs]') plt.plot( epot, 'g-' , label=r'Epot[t]-Epot[0]') plt.legend(loc='upper right') plt.subplot(212) plt.ylabel('Energy [eV]') plt.xlabel('Time [fs]') plt.plot( ekin, 'b-' ,label=r'Ekin') plt.legend(loc='upper right') if write: plt.savefig(md_type+'_e.eps', format='eps') plt.savefig(pp, format='pdf') plt.figure(3) plt.title(title) plt.subplot(211) plt.xlabel('Temperature [K]') plt.annotate("using t0 = {0} fs".format(t0_histo), xy=(0.75, 0.75), xycoords="axes fraction") plt.hist(temp[t0_histo:], bin_histo) plt.subplot(212) plt.ylabel('Temperature [K]') plt.xlabel('Time [fs]') plt.plot(temp, 'b-' ) if write: plt.savefig(md_type+'_T.eps', format='eps') plt.savefig(pp, format='pdf') return
def plot_fig1(): mdfile = '/space/tohekorh/ShearSlide/files/LJ_10/ac_twistTaito/w=7/md_L=24_v=0.20_00.traj' #mdfile = '/space/tohekorh/ShearSlide/files/KC_10/ac_stickTaito/w=7/r=20/md_L=145_stL=27_00.traj' traj = PickleTrajectory(mdfile) z_init = np.average(traj[0].positions[:, 2]) xrange = [np.min(traj[0].positions[:, 0]), np.max(traj[0].positions[:, 0])] yrange = [np.min(traj[0].positions[:, 1]), np.max(traj[0].positions[:, 1])] from ase.structure import graphene_nanoribbon from ase.visualize import view from ase import Atoms base = graphene_nanoribbon(70, 50, type='armchair', saturated=False, C_C=bond, main_element='N') base.rotate([1, 0, 0], np.pi / 2) base.positions[:, 2] = z_init - 3.8 atoms_v = Atoms() n = int(len(traj) / 1.3) #n = nsnap = 3 atoms_use = [traj[i] for i in np.array(range(nsnap)) * n / nsnap] for i, atoms in enumerate(atoms_use): atoms.positions[:, 1] = -atoms.positions[:, 1] - i * 20 #atoms.positions[:,0] = -atoms.positions[:,0] atoms_v += atoms cent_atoms = np.array([ np.average(atoms_v.positions[:, 0]), np.average(atoms_v.positions[:, 1]), 0 ]) cent_base = np.array([ np.average(base.positions[:, 0]), np.average(base.positions[:, 1]), 0 ]) base.translate(cent_atoms - cent_base) #atoms_v += base view(atoms_v, viewer='vmd')
def writeBestEnergyIntoFile(trajectoryFile, molecule): bookkeepingFile = open('BestEnergies.txt', mode='a') candidates = PickleTrajectory(str(trajectoryFile), mode='r') molecules = [molecule for molecule in candidates] potentialEnergyList = [ molecule.get_potential_energy() for molecule in molecules ] minimumPotenialEnergy = min(potentialEnergyList) indexOfMinimumPotentialEnergy = potentialEnergyList.index( minimumPotenialEnergy) line = str(trajectoryFile) + str( molecule.get_potential_energy()) + str(indexOfMinimumPotentialEnergy) bookkeepingFile.write(line) bookkeepingFile.close()
def mainBasinLoop(symbol1, symbol2, elementN1, elementN2, numberOfType1, numberOfType2, radius, percentType1): """symbol1 and symbol2 should be STRINGS. elementN1 and elementN2 should be ATOMIC NUMBERS of those elements. numberOfType1 and numberOfType2 are the actual # of those atoms in the molecule radius can be a decimal percent should be expressed as a number between 0 and 1. After that, it will create five new sets of 400 molecules, each set being the result of that first set having one of our small perturbations performed on it, which are also then minimized, perturbed, etc., until 50,000 total original orientations have been minimized.""" bigKickResults, round1PE = [], [] global finalList creationString = symbol1 + str(numberOfType1) + symbol2 + str(numberOfType2) creationString2 = creationString + '.traj' baseAtom = nearlySphericalAtom(str(creationString),radius,numberOfType1+numberOfType2) baseAtom.set_pbc((1,1,1)) baseAtom.set_cell((100,100,100)) calc = QSC() baseAtom.set_calculator(calc) baseAtom = makeBimetallic(baseAtom,numberOfType1+numberOfType2,elementN1,elementN2,percentType1) baseAtom = preventExplosions(baseAtom) baseAtom = preventExplosions(baseAtom) for x in range(listLength): bigKickResults.append(baseAtom.copy()) for x in range(listLength/2): bigKickResults[x] = shake(bigKickResults[x]) for x in range(listLength/2, listLength): bigKickResults[x] = switchAtoms(bigKickResults[x]) for x in range(len(bigKickResults)): bigKickResults[x] = optimizeMolecule(bigKickResults[x],FIREMoves,creationString2) round1PE.append(bigKickResults[x].get_potential_energy()) minimumPE = min(round1PE) minimumIndex = round1PE.index(minimumPE) bestAtom = bigKickResults[minimumIndex] minimaList = PickleTrajectory(str(creationString2),mode='a') minimaList.write(bestAtom) minimaList.close() finalList.append(bestAtom.copy()) smallKicks(bigKickResults,0,creationString2) veryBestAtom = returnFinalBestAtom(str(creationString2), str(creationString)) return veryBestAtom
def get_adhesion_energy(atoms, hmax, bottom, top, indent, m): zmax = np.amax(atoms.positions[bottom][:,2]) natoms = 0 for i in range(len(top)): if top[i]: natoms += 1 def get_epot(z): new_pos = atoms.positions.copy() for iat in range(len(atoms)): if top[iat]: new_pos[iat][2] = z atoms.positions = new_pos e = atoms.get_potential_energy()/natoms print z - zmax, e return e # Start to move the top layer in z direction zrange = np.linspace(h - .7, h + hmax, m) adh_pot = np.zeros((len(zrange), 2)) traj = PickleTrajectory(path + \ 'trajectories/adhesion_trajectory_%s.traj' %(indent), "w", atoms) # Here we lift the top layer: for i, z in enumerate(zrange): traj.write(get_save_atoms(atoms)) adh_pot[i] = [z, get_epot(zmax + z)] np.savetxt(path + 'datas/adhesion_data_%s.data' %(indent), adh_pot) return adh_pot
def fit_bond_length(self, name, atoms, data=None): N, x = self.fit d0 = atoms.get_distance(0, 1) distances = np.linspace(d0 * (1 - x), d0 * (1 + x), N) energies = [] traj = PickleTrajectory(self.get_filename(name, 'fit.traj'), 'w') for d in distances: atoms.set_distance(0, 1, d) energies.append(atoms.get_potential_energy()) self.check_occupation_numbers(atoms) traj.write(atoms) traj.close() if data is not None: data['distances'] = distances data['energies'] = energies else: assert N % 2 == 1 data = {'energy': energies[N // 2], 'distances': distances, 'energies': energies} return data
def write_optimized(self, atoms, energy): magmoms = None # XXX we could do better ... forces = np.zeros((len(atoms), 3)) calc = SinglePointCalculator(energy, forces, np.zeros((3, 3)), magmoms, atoms) atoms.set_calculator(calc) filename = '%s%s-optimized.traj' % (self.name, self.tag) traj = PickleTrajectory(filename, 'w', backup=False) traj.write(atoms) traj.close()
def plot_md(path, md_type, title, t0_histo, bin_histo, nf=1, nc=1, write=False): """ nc=1 by default caculates a_l for every carbon, an integer every l carbons""" traj = PickleTrajectory(path + md_type + '.traj') #Get the C-C backbone position array. c_index = [a.index for a in traj[0] if a.symbol == 'C'] c_traj = [atoms[c_index] for atoms in traj] c_pos = np.array([atoms.get_array('positions') for atoms in c_traj]) #define the junction points and get junction vectors print 'Number of C in system', len(c_traj[0]) l = range(0, len(c_traj[0]), nc) a_l = get_junction_vectors(c_pos, l) #calculate end-to-end vector r_ee sum over junctions r_ee = a_l.sum(axis=1) # temp = [ atoms.get_temperature() for atoms in traj] r2 = (r_ee * r_ee).sum(axis=1) r2_mean = r2.mean() r = np.sqrt(r2) plt.figure(nf) plt.subplot(211) plt.title(title) plt.ylabel('R [Ang]') plt.xlabel('Time [fs]') plt.plot(r, 'g-', label=r'R[t]') plt.legend(loc='upper right') plt.subplot(212) plt.xlabel('R [Ang]') plt.annotate("using t0 = {0} fs".format(t0_histo), xy=(0.75, 0.75), xycoords="axes fraction") plt.hist(r[t0_histo:], bin_histo) if write: #plt.savefig(md_type+'_R.eps', format='eps') plt.savefig(pp, format='pdf') return
def plot_oh(path,md_type,title,t0_histo,bin_histo,write=False): traj = PickleTrajectory(path+md_type+'.traj') oh = [] oh_distances = [] o_index = [atom.index for atom in traj[0] if atom.symbol == 'O'] h_index = [atom.index for atom in traj[0] if atom.symbol == 'H'] bonds_init = [ (o,h,traj[0].get_distance(o,h,mic=True)) for o in o_index for h in h_index] bonds_pva = [ (o,h) for o,h,d in bonds_init if d < 1.1 ] no = len(o_index) assert len(bonds_pva) == no for atoms in traj: bonds = [ (o,h,atoms.get_distance(o,h,mic=True)) for o1,h in bonds_pva for o in o_index] bonds_pva_traj = [ d for o,h,d in bonds if d < 1.2 ] assert len(bonds_pva_traj) == no bonds_oh = [ d for o,h,d in bonds if d <= 2.0] bonds_no_pva = [ d for d in bonds_oh if d > 1.1] oh += [1.0*len(bonds_no_pva)/no] oh_distances += bonds_no_pva plt.figure(4) plt.subplot(211) plt.title(title) plt.ylabel('Number of bonds/O atom') plt.xlabel('Time [fs]') plt.plot(oh, 'r-') plt.subplot(212) plt.xlabel('Number of bonds/O atom') plt.annotate("using t0 = {0} fs".format(t0_histo), xy=(0.75, 0.75), xycoords="axes fraction") plt.hist(oh[t0_histo:], 10) if write: plt.savefig(md_type+'_oh_number.eps', format='eps') plt.savefig(pp, format='pdf') plt.figure(5) plt.title(title) plt.xlabel('O-H distances') plt.hist(oh_distances[t0_histo:],bin_histo) if write: plt.savefig(md_type+'_oh_distance.eps', format='eps') plt.savefig(pp, format='pdf') return
def replay_trajectory(self, traj): """Initialize hessian from old trajectory.""" self.replay = True if isinstance(traj, str): from ase.io.trajectory import PickleTrajectory traj = PickleTrajectory(traj, 'r') atoms = traj[0] r0 = None g0 = None for i in range(0, len(traj) - 1): r = traj[i].get_positions().ravel() g = -traj[i].get_forces().ravel() / self.alpha self.update(r, g, r0, g0, self.p) self.p = -np.dot(self.H, g) r0 = r.copy() g0 = g.copy() self.r0 = r0 self.g0 = g0
def replay_trajectory(self, traj): """Initialize hessian from old trajectory.""" if isinstance(traj, str): from ase.io.trajectory import PickleTrajectory traj = PickleTrajectory(traj, 'r') self.H = None atoms = traj[0] r0 = atoms.get_positions().ravel() f0 = atoms.get_forces().ravel() for atoms in traj: r = atoms.get_positions().ravel() f = atoms.get_forces().ravel() self.update(r, f, r0, f0) r0 = r f0 = f self.r0 = r0 self.f0 = f0
def replay_trajectory(self, traj): """Initialize history from old trajectory.""" if isinstance(traj, str): from ase.io.trajectory import PickleTrajectory traj = PickleTrajectory(traj, 'r') r0 = None f0 = None # The last element is not added, as we get that for free when taking # the first qn-step after the replay for i in range(0, len(traj) - 1): r = traj[i].get_positions() f = traj[i].get_forces() self.update(r, f, r0, f0) r0 = r.copy() f0 = f.copy() self.iteration += 1 self.r0 = r0 self.f0 = f0
def read_and_check_results(): """Read energies from .gpw files.""" fd = sys.stdout E = {} fd.write('E = {') for formula in systems: try: atoms, calc = restart(formula, txt=None) except (KeyError, IOError): #print formula continue nspins = calc.get_number_of_spins() fa = calc.get_occupation_numbers(spin=0) assert ((fa.round() - fa)**2).sum() < 1e-14 if nspins == 2: fb = calc.get_occupation_numbers(spin=1) assert ((fb.round() - fb)**2).sum() < 1e-9 if len(atoms) == 1: M = data[formula]['magmom'] else: M = sum(data[formula]['magmoms']) assert abs((fa-fb).sum() - M) < 1e-9 e = calc.get_potential_energy() fd.write("'%s': %.3f, " % (formula, e)) fd.flush() E[formula] = e dE = [] # or maybe {} ? fd.write('}\ndE = [') for formula in dimers: try: trajectory = PickleTrajectory(formula + '.traj', 'r') except IOError: continue energies = [a.get_potential_energy() for a in trajectory] dE.append((formula, (energies))) fd.write("('%s', (" % formula) fd.write(', '.join(['%.4f' % (energy - E[formula]) for energy in energies])) fd.write(')),\n ') fd.write(']\n') return E, dE
def __init__(self, atoms, logfile, trajectory, master=None): """Dynamics object. Parameters: atoms: Atoms object The Atoms object to operate on. logfile: file object or str If *logfile* is a string, a file with that name will be opened. Use '-' for stdout. trajectory: Trajectory object or str Attach trajectory object. If *trajectory* is a string a PickleTrajectory will be constructed. Use *None* for no trajectory. master: boolean Defaults to None, which causes only rank 0 to save files. If set to true, this rank will save files. """ self.atoms = atoms if master is None: master = rank == 0 if not master: logfile = None elif isinstance(logfile, str): if logfile == '-': logfile = sys.stdout else: logfile = open(logfile, 'a') self.logfile = logfile self.observers = [] self.nsteps = 0 if trajectory is not None: if isinstance(trajectory, str): trajectory = PickleTrajectory(trajectory, mode='w', atoms=atoms, master=master) self.attach(trajectory)
def __init__(self, atoms, logfile, trajectory): self.atoms = atoms if rank != 0: logfile = None elif isinstance(logfile, str): if logfile == '-': logfile = sys.stdout else: logfile = open(logfile, 'a') self.logfile = logfile self.observers = [] self.nsteps = 0 if trajectory is not None: if isinstance(trajectory, str): trajectory = PickleTrajectory(trajectory, 'w', atoms) self.attach(trajectory)
# RuntimeError: Optimal parameters not found: # Number of calls to function has reached maxfev = 1000. eos_strl3 = [m for m in eos_strl] eos_strl3.remove('AntonSchmidt') results = {} # prepare energies and volumes b = bulk('Al', 'fcc', a=4.0, orthorhombic=True) b.set_calculator(EMT()) cell = b.get_cell() volumes = [] energies = [] traj = PickleTrajectory('eos.traj', 'w') for x in np.linspace(0.97, 1.03, 5): b.set_cell(cell * x, scale_atoms=True) volumes.append(b.get_volume()) energies.append(b.get_potential_energy()) traj.write(b) for n, (v, e) in enumerate(zip(volumes, energies)): vref = ref['volumes'][n] eref = ref['energies'][n] vabserr = abs((v - vref) / vref) vstrerr = str(n) + ' volume: ' + str(v) + ': ' + str(vref) + ': ' + str(vabserr) assert vabserr < 1.e-6, vstrerr eabserr = abs((e - eref) / eref) estrerr = str(n) + ' energy: ' + str(e) + ': ' + str(eref) + ': ' + str(eabserr) assert eabserr < 1.e-4, estrerr
calc = GPAW(gpts=N_c, nbands=5, basis='dzp', txt=name + '_gs.txt', eigensolver='rmm-diis') atoms.set_calculator(calc) atoms.get_potential_energy() calc.write(name + '_gs.gpw', mode='all') del atoms, calc time.sleep(10) while not os.path.isfile(name + '_gs.gpw'): print('Node %d waiting for file...' % world.rank) time.sleep(10) world.barrier() tdcalc = TDDFT(name + '_gs.gpw', txt=name + '_td.txt', propagator='EFSICN') ehrenfest = EhrenfestVelocityVerlet(tdcalc) traj = PickleTrajectory(name + '_td.traj', 'w', tdcalc.get_atoms()) t0 = time.time() f = paropen(name + '_td.log', 'w') for i in range(1, niter+1): ehrenfest.propagate(timestep) if i % ndiv == 0: rate = 60 * ndiv / (time.time()-t0) ekin = tdcalc.atoms.get_kinetic_energy() epot = tdcalc.get_td_energy() * Hartree F_av = ehrenfest.F * Hartree / Bohr print('i=%06d (%6.2f min^-1), ekin=%13.9f, epot=%13.9f, etot=%13.9f' % (i, rate, ekin, epot, ekin+epot), file=f) t0 = time.time() # Hack to prevent calls to GPAW::get_potential_energy when saving
def write(self, filename): from ase.io.trajectory import PickleTrajectory traj = PickleTrajectory(filename, 'w', self) traj.write() traj.close()
def write_modes(self, q_c, branches=0, kT=units.kB*300, repeat=(1, 1, 1), nimages=30, acoustic=True): """Write mode to trajectory file. The classical equipartioning theorem states that each normal mode has an average energy:: <E> = 1/2 * k_B * T = 1/2 * omega^2 * Q^2 => Q = sqrt(k_B*T) / omega at temperature T. Here, Q denotes the normal coordinate of the mode. Parameters ---------- q_c: ndarray q-vector of the modes. branches: int or list Branch index of calculated modes. kT: float Temperature in units of eV. Determines the amplitude of the atomic displacements in the modes. repeat: tuple Repeat atoms (l, m, n) times in the directions of the lattice vectors. Displacements of atoms in repeated cells carry a Bloch phase factor given by the q-vector and the cell lattice vector R_m. nimages: int Number of images in an oscillation. """ if isinstance(branches, int): branch_n = [branches] else: branch_n = list(branches) # Calculate modes omega_n, u_n = self.band_structure([q_c], modes=True, acoustic=acoustic) # Repeat atoms atoms = self.atoms * repeat pos_mav = atoms.positions.copy() # Total number of unit cells M = np.prod(repeat) # Corresponding lattice vectors R_m R_cm = np.indices(repeat[::-1]).reshape(3, -1)[::-1] # Bloch phase phase_m = np.exp(2.j * pi * np.dot(q_c, R_cm)) phase_ma = phase_m.repeat(len(self.atoms)) for n in branch_n: omega = omega_n[0, n] u_av = u_n[0, n] # .reshape((-1, 3)) # Mean displacement at high T ? u_av *= sqrt(kT / abs(omega)) mode_av = np.zeros((len(self.atoms), 3), dtype=self.dtype) indices = self.dyn.get_indices() mode_av[indices] = u_av mode_mav = (np.vstack([mode_av]*M) * phase_ma[:, np.newaxis]).real traj = PickleTrajectory('%s.mode.%d.traj' % (self.name, n), 'w') for x in np.linspace(0, 2*pi, nimages, endpoint=False): # XXX Is it correct to take out the sine component here ? atoms.set_positions(pos_mav + sin(x) * mode_mav) traj.write(atoms) traj.close()
def runAndStudy(params_set, pot_key, save = False): bond = params_set['bond'] T = params_set['T'] taito = params_set['taito'] dt, fric= params_set['dt'], params_set['fric'] tau = params_set['tau'] width = params_set['width'] ratio = params_set['ratio'] edge = params_set['edge'] ncores = params_set['ncores'] Ld_i = params_set['Ldilde_i'] bend, straight, [matchL_idx, matchR_idx, vec], [L_bend, L_straight], [left_idxs, right_idxs]\ = create_bend_stucture(width, ratio, Ld_i, edge, bond) mdfile, mdlogfile, mdrelax, simulfile, folder, relaxed \ = get_fileName(pot_key, edge + '_corrStick', width, \ L_bend, L_straight, int(T), taito, key = 'corrStick') if relaxed: bend = PickleTrajectory(mdrelax, 'r')[-1] else: relaxBend(bend, left_idxs, right_idxs, edge, bond, mdrelax) bend.set_constraint([]) shift_v = -straight.positions[matchR_idx] + (bend.positions[matchL_idx] + vec) straight.translate(shift_v) atoms = bend + straight cell = [1.5*(L_bend + L_straight), L_bend + L_straight, 20] atoms.set_cell(cell) atoms.positions[:,2] = 3.4 trans_vec = trans_atomsKC(straight.positions[matchR_idx], edge, bond) atoms.translate(trans_vec) #plot_posits(atoms, edge, bond) if edge == 'ac': nx = int((cell[0]/5 - np.min(atoms.positions[:,0]))/(3*bond)) ny = int((cell[1]/5 - np.min(atoms.positions[:,1]))/(np.sqrt(3)*bond)) atoms.translate([nx*3.*bond, ny*np.sqrt(3)*bond, 0]) width_f = np.sqrt(3)/2.*bond*(width - 1) elif edge == 'zz': nx = int((cell[0]/5 - np.min(atoms.positions[:,0]))/(np.sqrt(3)*bond)) ny = int((cell[1]/5 - np.min(atoms.positions[:,1]))/(3*bond)) atoms.translate([nx*np.sqrt(3)*bond, ny*3*bond, 0]) width_f = (3./2.*width - 1)*bond cminx, cmaxx = strip_Hend(atoms, 'right') left_b = get_idxOfEnds(atoms, cminx, cmaxx)[0] # CONSTRAINTS constraints = [] constraints.append(FixAtoms(indices = left_b)) params = {} params['positions'] = atoms.positions params['chemical_symbols'] = atoms.get_chemical_symbols() params['ia_dist'] = 10 params['edge'] = edge params['bond'] = bond params['ncores'] = ncores add_pot = KC_potential_p(params) constraints.append(add_pot) atoms.set_constraint(constraints) ## # CALCULATOR calc = LAMMPS(parameters=get_lammps_params()) atoms.set_calculator(calc) ## # DYNAMICS dyn = Langevin(atoms, dt*units.fs, T*units.kB, fric) header = '#t [fs], shift y [Angstrom], Rad, theta [rad], hmax [A], epot_tot [eV], ekin_tot [eV], etot_tot [eV], F [eV/angst] \n' write_line_own(mdlogfile, header, 'w') traj = PickleTrajectory(mdfile, 'w', atoms) if T != 0: # put initial MaxwellBoltzmann velocity distribution mbd(atoms, T*units.kB) #### # SIMULATION PARAMS nframes = 1000 M = int(20*tau/dt) interval = int(M/nframes) thres_cancel= 2*bond stick = 'True' xmax_idx = np.where(atoms.positions[:,0] == np.max(atoms.positions[:,0]))[0][0] r_init = atoms.positions[xmax_idx].copy() R = L_bend/np.pi*3. print '# data_line: width, length bend, length tail, tail/bend, theta' print width_f, L_bend, L_straight, L_straight/L_bend, width_f/(2*R) # SIMULATION LOOP for i in range(nframes): print float(i)/nframes*100. dyn.run(interval) epot, ekin = saveAndPrint(atoms, traj, False)[:2] data = [i*interval*dt, epot, ekin, epot + ekin] if save: stringi = '' for k,d in enumerate(data): if k == 0: stringi += '%.2f ' %d elif k == 1 or k == 2: stringi += '%.4f ' %d else: stringi += '%.12f ' %d write_line_own(mdlogfile, stringi + '\n', 'a') #print np.linalg.norm(atoms.positions[xmax_idx] - r_init) if thres_cancel < np.linalg.norm(atoms.positions[xmax_idx] - r_init): stick = 'false' break make_stick_simul_param_file(simulfile, width, L_bend, L_straight, T, \ dt, fric, interval, M, edge, stick) return stick == 'True' #plot_posits(atoms, edge, bond) #view(atoms)
from numpy import linspace from ase.calculators.fleur import FLEUR from ase.lattice import bulk from ase.io.trajectory import PickleTrajectory atoms = bulk('Ni', a=3.52) calc = FLEUR(xc='PBE', kmax=3.6, kpts=(10, 10, 10), workdir='lat_const') atoms.set_calculator(calc) traj = PickleTrajectory('Ni.traj','w', atoms) cell0 = atoms.get_cell() for s in linspace(0.95, 1.05, 7): cell = cell0 * s atoms.set_cell((cell)) ene = atoms.get_potential_energy() traj.write()
-p[0] * np.sin(p[1] * (t - p[2])) * (t - p[2]), p[0] * np.sin(p[1] * (t - p[2])) * p[1], np.ones_like(t)]) for name in ['h2_osc', 'n2_osc', 'na2_md', 'na2_osc']: print '\nAnalysing %s\n%s' % (name, '-'*32) # Import relevant test and make sure it has the prerequisite parameters m = __import__(name, {}, {}) for attr in ['d_bond', 'd_disp', 'timestep', 'period', 'ndiv', 'niter']: if not hasattr(m, attr): raise ImportError('Module %s has no %s value' % (name, attr)) # Read dimer bond length time series from trajectory file traj = PickleTrajectory(name + '_td.traj', 'r') nframes = len(traj) natoms = len(traj[0]) symbol = traj[0].get_name() t_i = m.timestep * m.ndiv * np.arange(nframes) Ekin_i, Epot_i = np.empty(nframes), np.empty(nframes) R_iav = np.empty((nframes, natoms, 3)) V_iav = np.empty((nframes, natoms, 3)) A_iav = np.empty((nframes, natoms, 3)) for i in range(nframes): Ekin_i[i] = traj[i].get_kinetic_energy() Epot_i[i] = traj[i].get_potential_energy() R_iav[i] = traj[i].get_positions() V_iav[i] = traj[i].get_velocities() A_iav[i] = traj[i].get_forces() / traj[i].get_masses()[:,np.newaxis] print 'Read %d frames from trajectory...' % nframes