Writing tasks

A task is any function that takes a TaskContext and returns a value. The scheduler runs it in its own thread, and the return value becomes TaskResult.value. The built-in tasks are written this way, so any ASE script can become a task.

The context provides three ways to request evaluations, depending on how the script uses the model.

One structure: a batched calculator

context.calculator() returns an ASE calculator. Attach it to an Atoms object and use any ASE code. Each evaluation blocks until the scheduler has evaluated it together with the requests of the other tasks.

from ase.build import bulk
from ase.calculators.emt import EMT
from ase.optimize import BFGS
from atombatch import Scheduler


def relax_then_strain(context):
    atoms = bulk("Cu", "fcc", a=3.6, cubic=True).repeat(2)
    atoms.rattle(0.05, seed=0)
    atoms.calc = context.calculator(properties=("energy", "forces", "stress"))
    BFGS(atoms, logfile=None).run(fmax=0.05)
    if atoms.get_stress()[0] > 0:
        atoms.set_cell(atoms.cell * 1.01, scale_atoms=True)
        BFGS(atoms, logfile=None).run(fmax=0.05)
    return atoms.get_potential_energy()


scheduler = Scheduler()
scheduler.add_model("emt", EMT())
scheduler.submit(relax_then_strain, "emt")
print(scheduler.run()[0].value)

Pass every property the script reads at each state in properties. A script that reads forces and stress at the same positions, as a cell filter does, is then evaluated once per state rather than twice.

Independent structures: context.evaluate

When a task needs many evaluations that do not depend on each other, submit them in one request. context.evaluate(structures) returns one result dictionary per structure, with energy, free_energy, forces, and any further requested properties.

from ase.build import bulk
from ase.calculators.emt import EMT
from atombatch import Scheduler


def vacancy_energies(context):
    host = bulk("Cu", "fcc", a=3.6, cubic=True).repeat(3)
    vacancies = []
    for index in range(4):
        cell = host.copy()
        del cell[index]
        vacancies.append(cell)
    results = context.evaluate([host, *vacancies])
    bulk_energy = results[0]["energy"] / len(host)
    return [r["energy"] - (len(host) - 1) * bulk_energy for r in results[1:]]


scheduler = Scheduler()
scheduler.add_model("emt", EMT())
scheduler.submit(vacancy_energies, "emt")
print(scheduler.run()[0].value)

Evaluating these structures one at a time through a calculator would take five rounds. With context.evaluate they take one.

Structures queried in turn: linked calculators

Some algorithms query several structures one after another within a single step. NEB, for example, reads the forces of each image in turn. context.linked_calculators(structures) attaches one calculator to each structure and groups them: the first query submits every structure in the group whose state changed, and the following queries are served from the cache. neb() is built this way.

Several models in one task

context.calculator, context.evaluate, and context.linked_calculators each take an optional model name, which defaults to the model the task was submitted with. A task can therefore compare models, or screen with a cheap model and refine with an expensive one.

Errors

An exception raised in a task is stored in TaskResult.error and does not stop other tasks. If a backend call fails, the exception is raised in every task whose requests were in that call.

Calculators inside a task

context.calculator() returns a new calculator, and each calculator is one trajectory to the backend, which may keep per-trajectory state such as a Symmetrix neighbor list. The context holds its calculators weakly: a calculator the task no longer references is released together with that state. Still, take one calculator per trajectory and keep it for the whole run, so that the state is reused between steps.

Long-running schedulers

A scheduler can serve tasks that arrive while it runs, such as runs fed from a cluster queue. submit() may be called from any thread at any time, and a task submitted during run() starts in the current batch as soon as max_active allows. run(until=event) keeps serving while idle until event is set, and on_result receives each TaskResult as its task finishes:

import threading

from ase.build import bulk
from ase.calculators.emt import EMT

from atombatch import Scheduler, relax

scheduler = Scheduler(max_active=8, round_timeout=1.0)
scheduler.add_model("emt", EMT())
stop = threading.Event()
service = threading.Thread(
    target=scheduler.run,
    kwargs={"until": stop, "on_result": lambda result: print(result.name, result.ok)},
)
service.start()

for seed in range(3):  # for example, as jobs arrive
    atoms = bulk("Cu", cubic=True).repeat(2)
    atoms.rattle(0.05, seed=seed)
    scheduler.submit(relax(atoms, fmax=0.05), "emt", name=f"job-{seed}")

stop.set()  # return once the submitted tasks have finished
service.join()

The results are printed as the relaxations converge:

job-0 True
job-2 True
job-1 True

A round starts when every running task is waiting for an evaluation, so Python work in one task between its evaluations, such as writing a checkpoint, delays the others, and a hung task would block them. With round_timeout (seconds), a round starts once its first request has waited that long, later rounds do not wait for the slow task until it submits again, and its next request joins the following round; its results are unaffected. waiting_on() lists the running tasks that have no pending evaluation and the time since each last received a result, which identifies a stalled task.

batch_log keeps the most recent 100,000 calls (Scheduler(batch_log=n), or None to keep none), and batch_totals counts calls, structures, and atoms per model over the scheduler’s lifetime, so memory stays bounded in long runs.