/usr/share/pyshared/ase/tasks/task.py is in python-ase 3.6.0.2515-1.1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | import sys
import optparse
import traceback
from time import time
import numpy as np
from ase.parallel import world
from ase.visualize import view
from ase.io import read, write
from ase.io import string2index
from ase.constraints import FixAtoms
from ase.optimize.lbfgs import LBFGS
from ase.utils import opencew, devnull, prnt
from ase.tasks.io import read_json, write_json
from ase.data import chemical_symbols, atomic_numbers
from ase.tasks.calcfactory import calculator_factory
class Task:
taskname = 'generic-task'
def __init__(self, calcfactory='emt',
tag=None, magmoms=None, gui=False,
write_summary=False, use_lock_files=False,
write_to_file=None, slice=slice(None),
logfile='-'):
"""Generic task object.
This task will do a single of the energy and forces for the
configurations that subcalsses define in their build_system()
methods.
calcfactory: CalculatorFactory object or str
A calculator factory or the name of a calculator.
For the meaning of the other arguments, see the add_options()
and parse_args() methods."""
self.set_calculator_factory(calcfactory)
self.tag = tag
self.magmoms = magmoms
self.gui = gui
self.write_summary = write_summary
self.use_lock_files = use_lock_files
self.write_to_file = write_to_file
self.slice = slice
if world.rank == 0:
if logfile is None:
logfile = devnull
elif isinstance(logfile, str):
if logfile == '-':
logfile = sys.stdout
else:
logfile = open(logfile, 'w')
else:
logfile = devnull
self.logfile = logfile
self.write_funcs = [write_json]
self.read_func = read_json
self.data = {} # data read from json files
self.results = {} # results from analysis of json files
self.summary_header = [('name', ''), ('E', 'eV')]
self.interactive_python_session = False
self.contains = None
self.modify = None
def set_calculator_factory(self, calcfactory):
if isinstance(calcfactory, str):
calcfactory = calculator_factory(calcfactory)
self.calcfactory = calcfactory
def log(self, *args, **kwargs):
prnt(file=self.logfile, *args, **kwargs)
def get_filename(self, name=None, ext=''):
filename = self.taskname + '-' + self.calcfactory.name.lower()
if self.tag:
filename += '-' + self.tag
if name:
filename = name + '-' + filename
return filename + ext
def expand(self, names):
"""Expand ranges like H-Li to H, He, Li."""
if isinstance(names, str):
names = [names]
newnames = []
for name in names:
if name.count('-') == 1:
s1, s2 = name.split('-')
Z1 = atomic_numbers.get(s1)
Z2 = atomic_numbers.get(s2)
if Z1 is None or Z2 is None:
newnames.append(name)
else:
newnames.extend(chemical_symbols[Z1:Z2 + 1])
else:
newnames.append(name)
return newnames
def exclude(self, names):
newnames = []
for name in names:
atoms = self.create_system(name)
if (self.contains is None or
self.contains in atoms.get_chemical_symbols()):
newnames.append(name)
return newnames
def run(self, names):
"""Run task far all names.
The task will be one of these four:
* Open ASE's GUI
* Write configuration to file
* Write summary
* Do the actual calculation
"""
names = self.expand(names)
names = names[self.slice]
names = self.exclude(names)
if self.gui:
for name in names:
view(self.create_system(name))
return
if self.write_to_file:
if self.write_to_file[0] == '.':
for name in names:
filename = self.get_filename(name, self.write_to_file)
write(filename, self.create_system(name))
else:
assert len(names) == 1
write(self.write_to_file, self.create_system(names[0]))
return
if self.write_summary:
self.read(names)
self.analyse()
self.summarize(names)
return
atoms = None
for name in names:
if self.use_lock_files:
lockfilename = self.get_filename(name, '.json')
fd = opencew(lockfilename)
if fd is None:
self.log('Skipping', name)
continue
fd.close()
atoms = self.run_single(name)
return atoms
def run_single(self, name):
try:
atoms = self.create_system(name)
except Exception:
self.log(name, 'FAILED')
traceback.print_exc(file=self.logfile)
return
atoms.calc = self.calcfactory(self.get_filename(name), atoms)
tstart = time()
try:
data = self.calculate(name, atoms)
except KeyboardInterrupt:
raise
except Exception:
self.log(name, 'FAILED')
traceback.print_exc(file=self.logfile)
return
tstop = time()
data['time'] = tstop - tstart
for write in self.write_funcs:
filenamebase = self.get_filename(name)
write(filenamebase, atoms, data)
return atoms
def create_system(self, name):
if '.' in name:
system = read(name)
else:
system = self.build_system(name)
if self.magmoms is not None:
system.set_initial_magnetic_moments(
np.tile(self.magmoms, len(system) // len(self.magmoms)))
if self.modify:
exec self.modify
return system
def calculate(self, name, atoms):
e = atoms.get_potential_energy()
f = atoms.get_forces()
return {'energy': e, 'forces': f}
def read(self, names):
self.data = {}
for name in names:
filenamebase = self.get_filename(name)
try:
data = self.read_func(filenamebase)
except (IOError, SyntaxError, ValueError):
continue
self.data[name] = data
def analyse(self):
for name, data in self.data.items():
self.results[name] = [data['energy']]
def summarize(self, names):
self.log(' '.join('%10s' % x[0] for x in self.summary_header))
self.log(' '.join('%10s' % x[1] for x in self.summary_header))
for name in names:
data = self.results.get(name, [])
s = '%10s' % name
for x in data:
if x is None:
s += ' '
else:
s += '%11.3f' % x
self.log(s)
def create_parser(self):
calcname = self.calcfactory.name
parser = optparse.OptionParser(
usage='%prog [options] system(s)',
description='Run %s calculation.' % calcname)
self.add_options(parser)
return parser
def add_options(self, parser):
general = optparse.OptionGroup(parser, 'General')
general.add_option('-t', '--tag',
help='String tag added to filenames.')
general.add_option('-M', '--magnetic-moment',
metavar='M1,M2,...',
help='Magnetic moment(s). ' +
'Use "-M 1" or "-M 2.3,-2.3".')
general.add_option('-G', '--gui', action='store_true',
help="Pop up ASE's GUI.")
general.add_option('-s', '--write-summary', action='store_true',
help='Write summary.')
general.add_option('--slice', metavar='start:stop:step',
help='Select subset of calculations using ' +
'Python slice syntax. ' +
'Use "::2" to do every second calculation and ' +
'":-5" to do the last five.')
general.add_option('-w', '--write-to-file', metavar='FILENAME',
help='Write configuration to file.')
general.add_option('-i', '--interactive-python-session',
action='store_true',
help='Run calculation inside interactive Python ' +
'session. A possible $PYTHONSTARTUP script ' +
'will be imported and the "atoms" variable ' +
'refers to the Atoms object.')
general.add_option('-l', '--use-lock-files', action='store_true',
help='Skip calculations where the json ' +
'lock-file or result file already exists.')
general.add_option('--contains', metavar='ELEMENT',
help='Run only systems containing specific ' +
'element.')
general.add_option('--modify', metavar='...',
help='Modify system with Python statement. ' +
'Example: "system.positions[-1,2]+=0.1". ' +
'Warning: no spaces allowed!')
parser.add_option_group(general)
def parse_args(self, args=None):
if args is None:
args = sys.argv[1:]
parser = self.create_parser()
self.calcfactory.add_options(parser)
opts, args = parser.parse_args(args)
if len(args) == 0:
parser.error('incorrect number of arguments')
self.parse(opts, args)
self.calcfactory.parse(opts, args)
return args
def parse(self, opts, args):
if opts.tag:
self.tag = opts.tag
if opts.magnetic_moment:
self.magmoms = np.array(
[float(m) for m in opts.magnetic_moment.split(',')])
self.gui = opts.gui
self.write_summary = opts.write_summary
self.write_to_file = opts.write_to_file
self.use_lock_files = opts.use_lock_files
self.interactive_python_session = opts.interactive_python_session
self.contains = opts.contains
self.modify = opts.modify
if opts.slice:
self.slice = string2index(opts.slice)
class OptimizeTask(Task):
taskname = 'opt'
def __init__(self, fmax=None, constrain_tags=[], **kwargs):
self.fmax = fmax
self.constrain_tags = constrain_tags
Task.__init__(self, **kwargs)
self.summary_header.append(('E-E0', 'eV'))
def optimize(self, name, atoms):
mask = [t in self.constrain_tags for t in atoms.get_tags()]
if mask:
constrain = FixAtoms(mask=mask)
atoms.constraints = [constrain]
optimizer = LBFGS(atoms, trajectory=self.get_filename(name, '.traj'),
logfile=None)
optimizer.run(self.fmax)
def calculate(self, name, atoms):
data = Task.calculate(self, name, atoms)
if self.fmax is not None:
self.optimize(name, atoms)
data['minimum energy'] = atoms.get_potential_energy()
data['minimum forces'] = atoms.get_forces()
return data
def analyse(self):
Task.analyse(self)
for name, data in self.data.items():
if 'minimum energy' in data:
self.results[name].append(data['energy'] -
data['minimum energy'])
else:
self.results[name].append(None)
def add_options(self, parser):
Task.add_options(self, parser)
optimize = optparse.OptionGroup(parser, 'Optimize')
optimize.add_option('-R', '--relax', type='float', metavar='FMAX',
help='Relax internal coordinates using L-BFGS '
'algorithm.')
optimize.add_option('--constrain-tags', type='str',
metavar='T1,T2,...',
help='Constrain atoms with tags T1, T2, ...')
parser.add_option_group(optimize)
def parse(self, opts, args):
Task.parse(self, opts, args)
self.fmax = opts.relax
if opts.constrain_tags:
self.constrain_tags = [int(t)
for t in opts.constrain_tags.split(',')]
|