API reference¶
Scheduler¶
- class atombatch.Scheduler(max_active=None, batch_log=100000, round_timeout=None)[source]¶
Run ASE tasks in worker threads and batch their model evaluations.
Each task runs ordinary ASE code with
BatchCalculatorinstances. When every running task is waiting for a result, the scheduler evaluates all pending requests in batched calls, one or more per model, and resumes the tasks. At mostmax_activetasks run at once; finished tasks are replaced from the queue so that batches stay full.batch_logis the number of model calls kept inbatch_log(the most recent ones);Nonekeeps none.batch_totalscounts calls, structures, and atoms per model over the scheduler’s lifetime.With
round_timeout(seconds), a round starts once its first request has waited that long, even if some tasks are still running Python code between evaluations. Those tasks are then stalled: later rounds do not wait for them until they submit their next request, which joins the next round. Without it, a slow or hung task holds back every other task.waiting_on()shows which tasks a round is waiting for.- batch_log¶
A
collections.dequewith one entry(model, structures, atoms)for each of the most recent batched calls (100,000 by default, set by thebatch_logargument).
- batch_totals¶
{model: {"calls": ..., "structures": ..., "atoms": ...}}, counted over every call the scheduler has made.
- add_model(name, model, max_atoms=None)[source]¶
Register a model under
name.modelis aBackend, a Symmetrix calculator withcalculate_batch, a TorchSim model, a function with theBackend.evaluate()signature, or any other ASE calculator, which is evaluated one structure at a time.max_atomsbounds the atoms in one batched call.
- submit(function, model, name=None)[source]¶
Queue
function(context); its return value becomes the result.Tasks may be submitted from any thread, also while
run()is running; they start as soon asmax_activeallows.
- run(until=None, on_result=None)[source]¶
Run queued tasks and return their results in submission order.
The result list contains every task that finished during this call, including tasks submitted from other threads while it ran. Without
until,run()returns once no task is running or queued. Withuntil, athreading.Eventor any object withis_set(), it waits for further submissions while idle and returns onceuntilis set and no task is running or queued.on_result(result)is called in this thread with eachTaskResultas its task finishes.
- class atombatch.TaskContext(scheduler, model)[source]¶
Handle given to a task function to request batched evaluations.
- calculator(model=None, properties=('energy', 'forces'))[source]¶
Return a new batched calculator for
model(default: the task’s).Every request from the calculator includes
properties, so a task that reads several properties at each state (for example forces and stress under a cell filter) is evaluated once per state.
- evaluate(structures, model=None, properties=('energy', 'forces'))[source]¶
Evaluate independent structures in one request and return the results.
Use this when a task needs many evaluations that do not depend on each other, such as displaced supercells or trial configurations: they join the same batched call instead of one call per round. Each result is a dictionary with
energy,free_energy,forces, and any furtherproperties.
- class atombatch.TaskResult(name: str, value: Any = None, error: BaseException | None = None)[source]¶
Outcome of one task: its return value, or the exception it raised.
- class atombatch.BatchCalculator(scheduler, model, properties=('energy', 'forces'))[source]¶
ASE calculator whose evaluations are batched by a
Scheduler.Each instance belongs to one task and one model.
calculatesubmits a request and blocks the task’s thread until the scheduler has evaluated it together with the requests of the other tasks.Calculators created together with
TaskContext.linked_calculators()form a group: a request from one member also evaluates every other member whose structure changed, so a task that queries several structures in turn, such as an NEB band, submits them as one request.- check_state(atoms, tol=1e-15)[source]¶
Return the system changes since the last evaluation.
Same result as
ase.calculators.calculator.Calculator.check_state(), which ASE calls several times per optimizer step. Arrays are first compared for exact equality, which is much cheaper than ASE’snp.allclosefor small structures; ASE’s tolerance comparison runs only when they differ.
Tasks¶
- atombatch.relax(atoms, fmax=0.05, steps=500, optimizer=<class 'ase.optimize.fire.FIRE'>, optimizer_kwargs=None, cell_filter=None, filter_kwargs=None)[source]¶
Relax one structure with any ASE optimizer, optionally with its cell.
- atombatch.neb(images, fmax=0.05, steps=500, optimizer=<class 'ase.optimize.fire.FIRE'>, optimizer_kwargs=None, neb_kwargs=None, interpolate=None)[source]¶
Optimize one NEB band built from
images(endpoints included).neb_kwargsare passed toase.mep.NEB(for exampleclimb=True);interpolateisNonefor images that are already placed, or anNEB.interpolatemethod such as"linear"or"idpp".
- atombatch.molecular_dynamics(atoms, dynamics, steps, observers=(), **dynamics_kwargs)[source]¶
Run
stepsof any ASE molecular-dynamics integrator.dynamicsis an integrator class such asVelocityVerletorLangevin;dynamics_kwargsare passed to it.observersare(function, interval)pairs attached withdynamics.attach; each function receives the movingAtoms.
Workflows¶
- atombatch.displacement_forces(phonon)[source]¶
Compute forces on the displaced supercells of a phonopy or phono3py object.
phononis aPhonopyorPhono3pyobject on whichgenerate_displacementshas been called. All displaced supercells are evaluated in one request and the forces are assigned tophonon.forces(andphonon.phonon_forceswhen phono3py uses a separate fc2 supercell). The task returnsphonon; force constants are then produced as usual, for example withproduce_force_constantsorproduce_fc3.
- atombatch.equation_of_state(atoms, scales=None, eos='birchmurnaghan')[source]¶
Evaluate isotropically scaled copies of
atomsand fit an EOS.scalesare linear scale factors of the cell (default 0.97 to 1.03 in seven points). All scaled cells are evaluated in one request. The fit usesase.eos.EquationOfState; the bulk modulus is in eV/Å^3.
- atombatch.swap_monte_carlo(atoms, temperatures_K, steps, sites=None, exchange_interval=10, rng=None)[source]¶
Sample site occupancies by Metropolis swaps, with replica exchange.
One replica runs at each temperature in
temperatures_K. A step proposes one swap of two unlike atoms per replica, chosen uniformly among unlike pairs ofsites(default: all atoms), and evaluates the trial configurations of all replicas in one request. Everyexchange_intervalsteps, neighboring temperatures attempt to exchange configurations. Positions are not relaxed: energies are those of the configurations on the fixed lattice ofatoms.The result holds the final configuration and energy at each temperature, the lowest-energy configuration visited, swap and exchange acceptance ratios, and the energy trace with one row per step.
Random structure searching¶
- atombatch.airss(generate, seed=None, pressure=0.0, fmax=0.05, steps=1000, optimizer=<class 'ase.optimize.fire.FIRE'>, optimizer_kwargs=None)[source]¶
Generate one random structure and relax it at
pressure(GPa).generate(rng)returns the random structure;rngis a NumPy generator seeded withseed. Positions and cell are relaxed together (Frechet cell filter). The result holds the relaxed and initial structures, energy, enthalpyH = E + pV(eV per cell and per atom), volume per atom, convergence, and steps.
- atombatch.hot_airss(generate, seed=None, pressure=0.0, temperature_K=1000.0, md_steps=300, timestep=0.09822694788464063, friction=0.2036101134231345, prerelax=True, fmax=0.05, steps=1000, optimizer=<class 'ase.optimize.fire.FIRE'>, optimizer_kwargs=None)[source]¶
Generate a random structure, relax it, anneal it with MD, and relax it again.
The anneal is Langevin dynamics at
temperature_Kformd_stepssteps in the cell of the first relaxation; velocities and the Langevin noise are drawn fromseed. Withprerelax=Falsethe anneal starts from the random structure. The relaxations are as inairss(), and the result additionally records the steps of every stage.
- atombatch.workflows.airss.random_structure(symbols, volume_per_atom, minsep, rng=None, varvol=0.1, max_attempts=1000)[source]¶
Return random periodic
Atomswith atoms at leastminsepapart.The cell has random lengths and angles (between 60 and 120 degrees) and a volume of
len(symbols) * volume_per_atom, varied by up tovarvol(a fraction). Atoms are placed uniformly at random and rejected when closer thanminsep(A) to an atom already placed, including periodic images. Unlikebuildcell, it imposes no symmetry.
- atombatch.workflows.airss.buildcell(seed, attempts=10)[source]¶
Return a generator that runs the AIRSS
buildcellprogram onseed.seedis an airsspySeedAtomsor the text of a buildcell seed (.cellfile). Needs airsspy andbuildcellon thePATH. buildcell draws its own random numbers, sorngis not used.
- atombatch.workflows.airss.rank(results, enthalpy_tolerance=0.002, volume_tolerance=0.02, same=None)[source]¶
Sort search results by enthalpy per atom and merge duplicates.
Two results are taken as the same structure when their enthalpies per atom differ by less than
enthalpy_tolerance(eV/atom) and their volumes per atom by less thanvolume_tolerance(a fraction); a functionsame(atoms1, atoms2), such as one built on pymatgen’sStructureMatcher, can confirm the match. Results that did not converge are skipped. Returns a list of dictionaries with the lowest-enthalpyresultof each structure and the number of times it was found (count), lowest enthalpy first.
Backends¶
- class atombatch.Backend[source]¶
Evaluate a list of ASE structures with one model.
evaluatereturns one result dictionary per structure with at leastenergyandforces, plusstress(ASE Voigt order) when requested.max_atomsbounds the number of atoms in one call;Nonemeans unbounded.
- class atombatch.SymmetrixBackend(calculator, max_atoms=None, batch_mode='native', native_atoms=None, calculator_factory=None, max_calculators=4)[source]¶
Evaluate structures with a Symmetrix calculator in one native call.
atombatch joins the structures into one disconnected neighbor graph and calls the Symmetrix evaluator directly (
atombatch.symmetrix), with one Symmetrix neighbor cache per trajectory so that neighbor lists are rebuilt only when atoms move beyond the neighbor skin. Structures with at leastnative_atomsatoms gain little from joining and are instead evaluated one at a time on Symmetrix’s own prepared-geometry path, which keeps the neighbor graph on the device and reduces forces and stress there; their results equal the Symmetrix calculator’s. These share the calculator, so their neighbor graphs are built on the host. With acalculator_factory(seefrom_model()), up tomax_calculatorstrajectories of large structures each get a calculator of their own and run exactly as with the Symmetrix calculator alone, including neighbor graphs built on the device. This works from Symmetrix-XL 0.1.1, and Symmetrix-XL 0.2 evaluates source-keyed joined batches natively on the device.Symmetrix.calculate_batch, which no Symmetrix-XL release provides, is used only for calculators without the evaluator interface. MACE-POLAR-1 models are evaluated withSymmetrix.calculate_polar_batchwhere Symmetrix provides it. Other long-range families, models with dispersion corrections, and field-coupled models fall back to one ASE evaluation per structure.- classmethod from_model(model_file, max_atoms=None, native_atoms=None, max_calculators=4, **symmetrix_options)[source]¶
Create the backend from a model file, with dedicated calculators.
symmetrix_optionsare passed tosymmetrix.Symmetrix(for exampledtype="float32"ormetal=True). Besides the shared calculator, up tomax_calculatorstrajectories of large structures each get a calculator of their own, so that Symmetrix can keep their neighbor graphs on the device. Each costs one model load and its own device memory.
- class atombatch.TorchSimBackend(model, max_atoms=None)[source]¶
Evaluate structures in one call of a TorchSim
ModelInterface.TorchSim provides batched interfaces for MACE, fairchem, SevenNet, ORB, MatterSim, NequIP, Nequix, metatomic, and classical potentials. The structures are joined into one
SimStateon the model’s device and dtype, and the outputs are split back per structure. Stress requires a model constructed withcompute_stress=True.
- class atombatch.FunctionBackend(function, max_atoms=None)[source]¶
Evaluate structures with a user function of the backend signature.
function(structures, properties)returns one result dictionary per structure, asBackend.evaluate()does. This connects any model with its own batched evaluation without subclassingBackend.
Symmetrix graph batching¶
Batched evaluation with Symmetrix-XL.
The structures of a batch are joined into one disconnected neighbor graph and evaluated by a single native call of the Symmetrix evaluator. Message passing runs only along graph edges, so the structures do not interact. Energies are summed per structure from node energies, forces are reduced per atom, and stresses are reduced per structure from the directed pair forces.
Adapted from symmetrix.batch in the batched-evaluation branch of the
deng-group fork of Symmetrix-XL (MIT License). It uses only evaluator calls
present since Symmetrix-XL 0.1.1. Symmetrix-XL 0.2 recognizes the source keys
of joined structures and evaluates them as one prepared segment group with the
geometry kept on the device; the results are the same.
- class atombatch.backends.symmetrix.SymmetrixBackend(calculator, max_atoms=None, batch_mode='native', native_atoms=None, calculator_factory=None, max_calculators=4)[source]¶
Evaluate structures with a Symmetrix calculator in one native call.
atombatch joins the structures into one disconnected neighbor graph and calls the Symmetrix evaluator directly (
atombatch.symmetrix), with one Symmetrix neighbor cache per trajectory so that neighbor lists are rebuilt only when atoms move beyond the neighbor skin. Structures with at leastnative_atomsatoms gain little from joining and are instead evaluated one at a time on Symmetrix’s own prepared-geometry path, which keeps the neighbor graph on the device and reduces forces and stress there; their results equal the Symmetrix calculator’s. These share the calculator, so their neighbor graphs are built on the host. With acalculator_factory(seefrom_model()), up tomax_calculatorstrajectories of large structures each get a calculator of their own and run exactly as with the Symmetrix calculator alone, including neighbor graphs built on the device. This works from Symmetrix-XL 0.1.1, and Symmetrix-XL 0.2 evaluates source-keyed joined batches natively on the device.Symmetrix.calculate_batch, which no Symmetrix-XL release provides, is used only for calculators without the evaluator interface. MACE-POLAR-1 models are evaluated withSymmetrix.calculate_polar_batchwhere Symmetrix provides it. Other long-range families, models with dispersion corrections, and field-coupled models fall back to one ASE evaluation per structure.- classmethod from_model(model_file, max_atoms=None, native_atoms=None, max_calculators=4, **symmetrix_options)[source]¶
Create the backend from a model file, with dedicated calculators.
symmetrix_optionsare passed tosymmetrix.Symmetrix(for exampledtype="float32"ormetal=True). Besides the shared calculator, up tomax_calculatorstrajectories of large structures each get a calculator of their own, so that Symmetrix can keep their neighbor graphs on the device. Each costs one model load and its own device memory.
- atombatch.backends.symmetrix.supports_graph_batching(calculator)[source]¶
Return whether
calculatorexposes the evaluator calls used here.
- class atombatch.backends.symmetrix.GraphBatcher(calculator, neighbor_cache_size=64, trajectory_cache_size=1024, native_atoms=None, calculator_factory=None, max_calculators=4)[source]¶
Evaluate structures with one Symmetrix calculator in one native call.
Neighbor lists are cached by positions, cell, and periodicity, so structures that differ only in species, such as Monte Carlo trials on one lattice, share a neighbor list.
- atombatch.backends.symmetrix.uses_ase_neighbor_list()[source]¶
Return whether Symmetrix fell back to
ase.neighborlist.
- atombatch.backends.symmetrix.edge_forces(evaluator, num_edges)[source]¶
Return the directed pair forces of the last evaluation.
- atombatch.backends.symmetrix.segment_virials(pair_forces, xyz, edge_offsets)[source]¶
Return the virial
-sum(F_e outer xyz_e)of every edge segment.
- atombatch.backends.symmetrix.supports_polar_batch(calculator)[source]¶
Return whether MACE-POLAR-1 structures can be evaluated in one call.
Symmetrix.calculate_polar_batchevaluates independent MACE-POLAR-1 structures in shared native calls, each with its own cell, graph inputs, and long-range solver. Its first version omitted the correction pipeline (D3), so a calculator with corrections uses it only when the batch adds them (_add_polar_batch_corrections).
atomate2¶
- atombatch.integrations.atomate2.atomate2_task(maker, structure, model=None)[source]¶
Return a task that runs
makeronstructurewith batched evaluations.makeris an atomate2 maker with arun_asemethod and a jobmake(for exampleForceFieldRelaxMaker(relax_cell=True)), andstructurea pymatgenStructureorMolecule. The job runs directly, not as a jobflowJob, and the task’s value is its document, such as aForceFieldTaskDocument.modelnames the atombatch model (default: the model the task is submitted with).