本文整理汇总了Python中ase.calculators.calculator.Calculator.calculate方法的典型用法代码示例。如果您正苦于以下问题:Python Calculator.calculate方法的具体用法?Python Calculator.calculate怎么用?Python Calculator.calculate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ase.calculators.calculator.Calculator
的用法示例。
在下文中一共展示了Calculator.calculate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None, properties=['energy'],
system_changes=all_changes):
"""EAM Calculator
atoms: Atoms object
Contains positions, unit-cell, ...
properties: list of str
List of what needs to be calculated. Can be any combination
of 'energy', 'forces'
system_changes: list of str
List of what has changed since last calculation. Can be
any combination of these five: 'positions', 'numbers', 'cell',
'pbc', 'initial_charges' and 'initial_magmoms'.
"""
Calculator.calculate(self, atoms, properties, system_changes)
# we shouldn't really recalc if charges or magmos change
if len(system_changes) > 0: # something wrong with this way
self.update(self.atoms)
self.calculate_energy(self.atoms)
if 'forces' in properties:
self.calculate_forces(self.atoms)
# check we have all the properties requested
for property in properties:
if property not in self.results:
if property is 'energy':
self.calculate_energy(self.atoms)
if property is 'forces':
self.calculate_forces(self.atoms)
示例2: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms, properties, system_changes)
try:
results = self.checkpoint.load(atoms)
prev_atoms, results = results[0], results[1:]
try:
assert atoms_almost_equal(atoms, prev_atoms)
except AssertionError:
raise AssertionError('mismatch between current atoms and those read from checkpoint file')
self.logger.pr('retrieved results for {0} from checkpoint'.format(properties))
# save results in calculator for next time
if isinstance(self.calculator, Calculator):
if not hasattr(self.calculator, 'results'):
self.calculator.results = {}
self.calculator.results.update(dict(zip(properties, results)))
except NoCheckpoint:
if isinstance(self.calculator, Calculator):
self.logger.pr('doing calculation of {0} with new-style calculator interface'.format(properties))
self.calculator.calculate(atoms, properties, system_changes)
results = [self.calculator.results[prop] for prop in properties]
else:
self.logger.pr('doing calculation of {0} with old-style calculator interface'.format(properties))
results = []
for prop in properties:
method_name = CheckpointCalculator.property_to_method_name[prop]
method = getattr(self.calculator, method_name)
results.append(method(atoms))
_calculator = atoms.get_calculator
try:
atoms.set_calculator(self.calculator)
self.checkpoint.save(atoms, *results)
finally:
atoms.set_calculator(_calculator)
self.results = dict(zip(properties, results))
示例3: run_calculation
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def run_calculation(self, atoms=None, properties=None,
system_changes=all_changes):
'''
Internal calculation executor. We cannot use FileIOCalculator
directly since we need to support remote execution.
This calculator is different from others.
It prepares the directory, launches the remote process and
raises the exception to signal that we need to come back for results
when the job is finished.
'''
if properties is None:
properties = ['energy']
Calculator.calculate(self, atoms, properties, system_changes)
self.write_input(self.atoms, properties, system_changes)
if self.command is None:
raise RuntimeError('Please configure RemoteQE calculator!')
olddir = os.getcwd()
errorcode=0
try:
os.chdir(self.directory)
output = subprocess.check_output(self.command, shell=True)
self.jobid=output.split()[0]
self.submited=True
#print "Job %s submitted. Waiting for it." % (self.jobid)
# Waiting loop. To be removed.
except subprocess.CalledProcessError as e:
errorcode=e.returncode
finally:
os.chdir(olddir)
if errorcode:
raise RuntimeError('%s returned an error: %d' %
(self.name, errorcode))
self.read_results()
示例4: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None, properties=['energy'],
system_changes=None):
"""Runs a calculation, only if necessary."""
if self.calculation_required(atoms, properties):
# The subclass implementation should first call this
# implementation to set the atoms attribute.
Calculator.calculate(self, atoms, properties, system_changes)
self.write_input(atoms, properties, system_changes)
if self.command is None:
raise RuntimeError('Please set $%s environment variable ' %
('ASE_' + self.name.upper() + '_COMMAND') +
'or supply the command keyword')
olddir = os.getcwd()
try:
os.chdir(self.directory)
errorcode = subprocess.call(self.command,
stdout=subprocess.PIPE,
shell=True)
finally:
os.chdir(olddir)
if errorcode:
s = '{} returned an error: {}'
raise RuntimeError(s.format(self.name, errorcode))
# This sets self.results, and updates the atoms
self.read_results()
示例5: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms, properties, system_changes)
if self.qmatoms is None:
self.initialize_qm(atoms)
self.qmatoms.positions = atoms.positions[self.selection]
if self.vacuum:
self.qmatoms.positions += (self.center -
self.qmatoms.positions.mean(axis=0))
energy = self.mmcalc2.get_potential_energy(atoms)
forces = self.mmcalc2.get_forces(atoms)
energy += self.qmcalc.get_potential_energy(self.qmatoms)
qmforces = self.qmcalc.get_forces(self.qmatoms)
if self.vacuum:
qmforces -= qmforces.mean(axis=0)
forces[self.selection] += qmforces
energy -= self.mmcalc1.get_potential_energy(self.qmatoms)
forces[self.selection] -= self.mmcalc1.get_forces(self.qmatoms)
self.results['energy'] = energy
self.results['forces'] = forces
示例6: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms, properties, system_changes)
if system_changes: # if anything at all changed (could be made more fine-grained)
self.logger.pr('calculation triggered with properties={0}, system_changes={1}'.format(properties,
system_changes))
self.server.put(atoms, 0, self.label)
if self.label != 1:
# send atoms over socket, unless first time
self.logger.pr('socket calculator sending Atoms label={0}'.format(self.label))
self.server.handle_request()
# wait for results to be ready
self.logger.pr('socket calculator waiting for results label={0}'.format(self.label))
self.server.handle_request()
self.label += 1
[results] = self.server.get_results()
# we always compute energy, forces and stresses, regardless of what was requested
stress = -(results.info['virial']/results.get_volume())
self.results = {'energy': results.info['energy'],
'forces': results.arrays['force'],
'stress': full_3x3_to_Voigt_6_stress(stress)}
else:
self.logger.pr('calculation avoided with properties={0}, system_changes={1}'.format(properties,
system_changes))
示例7: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None, properties=['energy'],
system_changes=['positions', 'numbers', 'cell',
'pbc', 'charges', 'magmoms']):
Calculator.calculate(self, atoms, properties, system_changes)
epsilon = self.parameters.epsilon
rho0 = self.parameters.rho0
r0 = self.parameters.r0
positions = self.atoms.get_positions()
energy = 0.0
energies = np.zeros(len(self.atoms))
forces = np.zeros((len(self.atoms), 3))
preF = 2 * epsilon * rho0 / r0
for i1, p1 in enumerate(positions):
for i2, p2 in enumerate(positions[:i1]):
diff = p2 - p1
r = sqrt(np.dot(diff, diff))
expf = exp(rho0 * (1.0 - r / r0))
energy += epsilon * expf * (expf - 2)
energies[i1] += epsilon * expf * (expf - 2)
energies[i2] += epsilon * expf * (expf - 2)
F = preF * expf * (expf - 1) * diff / r
forces[i1] -= F
forces[i2] += F
self.results['energy'] = energy
self.results['forces'] = forces
self.results['potential_energies'] = energies
示例8: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
"""
Calculation of the energy of system and forces of all atoms.
"""
# The inherited method below just sets the atoms object,
# if specified, to self.atoms.
Calculator.calculate(self, atoms, properties, system_changes)
log = self.log
log('Calculation requested.')
images = hash_images([self.atoms])
key = images.keys()[0]
if properties == ['energy']:
log('Calculating potential energy...', tic='pot-energy')
self.descriptor.calculate_fingerprints(images=images,
log=log,
calculate_derivatives=False)
energy = self.model.get_energy(self.descriptor.fingerprints[key])
self.results['energy'] = energy
log('...potential energy calculated.', toc='pot-energy')
if properties == ['forces']:
log('Calculating forces...', tic='forces')
self.descriptor.calculate_fingerprints(images=images,
log=log,
calculate_derivatives=True)
forces = \
self.model.get_forces(self.descriptor.fingerprints[key],
self.descriptor.fingerprintprimes[key])
self.results['forces'] = forces
log('...forces calculated.', toc='forces')
示例9: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
# call parent method:
Calculator.calculate(self, atoms, properties, system_changes)
if not(system_changes is None):
self.update_atoms()
if 'energy' in properties:
energy = self.ff.Energy()
# energy units are kcal/mole according to http://forums.openbabel.org/Energy-units-td1574278.html
# and in Avogadro they are reported as kJ/mole ...
self.results['energy'] = energy * units.kJ / units.mol
if 'forces' in properties:
d = 0.001
F_ai = np.zeros( (self.natoms, 3) )
for iatom in xrange( self.natoms ):
for iaxis in xrange( 3 ):
obatom = self.mol.GetAtom( 1 + iatom )
vec = obatom.GetVector()
obatom.SetVector( self._shift_OBvec(vec, iaxis, d) )
self.ff.Setup( self.mol )
eplus = self.ff.Energy() * units.kJ/units.mol
obatom.SetVector( self._shift_OBvec(vec, iaxis, -2*d) )
self.ff.Setup( self.mol )
eminus = self.ff.Energy() * units.kJ/units.mol
obatom.SetVector( self._shift_OBvec(vec, iaxis, d) ) # put it back
F_ai[iatom, iaxis] = (eminus - eplus) / (2 * d)
self.results['forces'] = F_ai
示例10: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None, properties=['energy'],
system_changes=all_changes):
"""GEBF Calculator
"""
Calculator.calculate(self, atoms, properties, system_changes)
if len(system_changes) > 0: # something wrong with this way
self.update(self.atoms)
if 'energy' in properties:
self.calculate_energy(self.atoms)
if 'forces' in properties:
self.calculate_forces(self.atoms)
if 'charges' in properties:
self.calculate_charges(self.atoms)
# check we have all the properties requested
for property in properties:
if property not in self.results:
if property is 'energy':
self.calculate_energy(self.atoms)
if property is 'forces':
self.calculate_forces(self.atoms)
if property is 'charges':
self.calculate_charges(self.atoms)
#FUMPORTANT|
atoms.set_initial_charges(self.results['charges'])
示例11: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None, properties=['energy'],
system_changes=all_changes):
# We don't call FileIOCalculator.calculate here, because that method
# calls subprocess.call(..., shell=True), which we don't want to do.
# So, we reproduce some content from that method here.
Calculator.calculate(self, atoms, properties, system_changes)
# If a parameter file exists in the working directory, delete it
# first. If we need that file, we'll recreate it later.
localparfile = os.path.join(self.directory, '.dftd3par.local')
if os.path.isfile(localparfile):
os.remove(localparfile)
# Write XYZ or POSCAR file and .dftd3par.local file if we are using
# custom damping parameters.
self.write_input(self.atoms, properties, system_changes)
command = self._generate_command()
# Finally, call dftd3 and parse results.
with open(self.label + '.out', 'w') as f:
errorcode = subprocess.call(command, cwd=self.directory, stdout=f)
if errorcode:
raise RuntimeError('%s returned an error: %d' %
(self.name, errorcode))
self.read_results()
示例12: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None, properties=None,
system_changes=all_changes):
'''Do the calculation.'''
if(not properties):
properties = ['energy']
Calculator.calculate(self, atoms, properties, system_changes)
if('numbers' in system_changes or
'initial_magmoms' in system_changes):
self._release_force_env()
if(self._force_env_id is None):
self._create_force_env()
n_atoms = len(self.atoms)
if('cell' in system_changes):
cell = self.atoms.get_cell()
self._send('SET_CELL %d' % self._force_env_id)
self._send(' '.join(['%.10f' % x for x in cell.flat]))
assert(self._recv() == '* READY')
if('positions' in system_changes):
self._send('SET_POS %d' % self._force_env_id)
self._send('%d' % (3 * n_atoms))
for pos in self.atoms.get_positions():
self._send('%.10f %.10f %.10f' % (pos[0], pos[1], pos[2]))
self._send('*END')
assert(float(self._recv()) >= 0) # max change -> ignore
assert(self._recv() == '* READY')
self._send('EVAL_EF %d' % self._force_env_id)
assert(self._recv() == '* READY')
self._send('GET_E %d' % self._force_env_id)
self.results['energy'] = float(self._recv()) * Hartree
assert(self._recv() == '* READY')
forces = np.zeros(shape=(n_atoms, 3))
self._send('GET_F %d' % self._force_env_id)
assert(int(self._recv()) == 3 * n_atoms)
for i in range(n_atoms):
line = self._recv()
forces[i, :] = [float(x) for x in line.split()]
assert(self._recv() == '* END')
assert(self._recv() == '* READY')
self.results['forces'] = forces * Hartree / Bohr
self._send('GET_STRESS %d' % self._force_env_id)
line = self._recv()
assert(self._recv() == '* READY')
stress = np.array([float(x) for x in line.split()]).reshape(3, 3)
assert(np.all(stress == np.transpose(stress))) # should be symmetric
# Convert 3x3 stress tensor to Voigt form as required by ASE
stress = np.array([stress[0, 0], stress[1, 1], stress[2, 2],
stress[1, 2], stress[0, 2], stress[0, 1]])
self.results['stress'] = stress * Hartree / Bohr**3
示例13: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms)
self.kpts = kpts2ndarray(self.parameters.kpts, atoms)
icell = atoms.get_reciprocal_cell() * 2 * np.pi * Bohr
n = 7
offsets = np.indices((n, n, n)).T.reshape((n**3, 1, 3)) - n // 2
eps = 0.5 * (np.dot(self.kpts + offsets, icell)**2).sum(2).T
eps.sort()
self.eigenvalues = eps[:, :20] * Ha
self.results = {'energy': 0.0}
示例14: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms, properties, system_changes)
nat = len(self.atoms)
atnums = self.atoms.numbers
atnums_in_system = set(atnums)
i_n, j_n, dr_nc, abs_dr_n = neighbour_list(
'ijDd', self.atoms, self.dict)
e_n = np.zeros_like(abs_dr_n)
de_n = np.zeros_like(abs_dr_n)
for params, pair in enumerate(self.dict):
if pair[0] == pair[1]:
mask1 = atnums[i_n] == pair[0]
mask2 = atnums[j_n] == pair[0]
mask = np.logical_and(mask1, mask2)
e_n[mask] = self.f[pair](abs_dr_n[mask])
de_n[mask] = self.df[pair](abs_dr_n[mask])
if pair[0] != pair[1]:
mask1 = np.logical_and(
atnums[i_n] == pair[0], atnums[j_n] == pair[1])
mask2 = np.logical_and(
atnums[i_n] == pair[1], atnums[j_n] == pair[0])
mask = np.logical_or(mask1, mask2)
e_n[mask] = self.f[pair](abs_dr_n[mask])
de_n[mask] = self.df[pair](abs_dr_n[mask])
epot = 0.5*np.sum(e_n)
# Forces
df_nc = -0.5*de_n.reshape(-1, 1)*dr_nc/abs_dr_n.reshape(-1, 1)
# Sum for each atom
fx_i = np.bincount(j_n, weights=df_nc[:, 0], minlength=nat) - \
np.bincount(i_n, weights=df_nc[:, 0], minlength=nat)
fy_i = np.bincount(j_n, weights=df_nc[:, 1], minlength=nat) - \
np.bincount(i_n, weights=df_nc[:, 1], minlength=nat)
fz_i = np.bincount(j_n, weights=df_nc[:, 2], minlength=nat) - \
np.bincount(i_n, weights=df_nc[:, 2], minlength=nat)
# Virial
virial_v = -np.array([dr_nc[:, 0]*df_nc[:, 0], # xx
dr_nc[:, 1]*df_nc[:, 1], # yy
dr_nc[:, 2]*df_nc[:, 2], # zz
dr_nc[:, 1]*df_nc[:, 2], # yz
dr_nc[:, 0]*df_nc[:, 2], # xz
dr_nc[:, 0]*df_nc[:, 1]]).sum(axis=1) # xy
self.results = {'energy': epot,
'stress': virial_v/self.atoms.get_volume(),
'forces': np.transpose([fx_i, fy_i, fz_i])}
示例15: calculate
# 需要导入模块: from ase.calculators.calculator import Calculator [as 别名]
# 或者: from ase.calculators.calculator.Calculator import calculate [as 别名]
def calculate(self, atoms=None,
properties=['energy'],
system_changes=all_changes):
Calculator.calculate(self, atoms, properties, system_changes)
natoms = len(self.atoms)
sigma = self.parameters.sigma
epsilon = self.parameters.epsilon
rc = self.parameters.rc
if rc is None:
rc = 3 * sigma
if 'numbers' in system_changes:
self.nl = NeighborList([rc / 2] * natoms, self_interaction=False)
self.nl.update(self.atoms)
positions = self.atoms.positions
cell = self.atoms.cell
e0 = 4 * epsilon * ((sigma / rc)**12 - (sigma / rc)**6)
energy = 0.0
forces = np.zeros((natoms, 3))
stress = np.zeros((3, 3))
for a1 in range(natoms):
neighbors, offsets = self.nl.get_neighbors(a1)
cells = np.dot(offsets, cell)
d = positions[neighbors] + cells - positions[a1]
r2 = (d**2).sum(1)
c6 = (sigma**2 / r2)**3
c6[r2 > rc**2] = 0.0
energy -= e0 * (c6 != 0.0).sum()
c12 = c6**2
energy += 4 * epsilon * (c12 - c6).sum()
f = (24 * epsilon * (2 * c12 - c6) / r2)[:, np.newaxis] * d
#print d
#print r2**.5
#print offsets
#print f
#print neighbors
forces[a1] -= f.sum(axis=0)
for a2, f2 in zip(neighbors, f):
forces[a2] += f2
stress += np.dot(f.T, d)
#stress = np.dot(stress, cell)
stress += stress.T.copy()
stress *= -0.5 / self.atoms.get_volume()
self.results['energy'] = energy
self.results['forces'] = forces
self.results['stress'] = stress.flat[[0, 4, 8, 5, 2, 1]]