本文整理汇总了Python中ase.io.trajectory.PickleTrajectory.close方法的典型用法代码示例。如果您正苦于以下问题:Python PickleTrajectory.close方法的具体用法?Python PickleTrajectory.close怎么用?Python PickleTrajectory.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ase.io.trajectory.PickleTrajectory
的用法示例。
在下文中一共展示了PickleTrajectory.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: eos
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例2: accept_move
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例3: breed
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例4: fit_volume
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例5: _test_timestepping
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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()
示例6: mainBasinLoop
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例7: write_optimized
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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()
示例8: write_mode
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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()
示例9: fit_bond_length
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例10: MD
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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()
示例11: fit_volume
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例12: write_mode
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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()
示例13: append_equilibrium_trajectory
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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')
示例14: fit_bond_length
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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
示例15: optimizeMolecule
# 需要导入模块: from ase.io.trajectory import PickleTrajectory [as 别名]
# 或者: from ase.io.trajectory.PickleTrajectory import close [as 别名]
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