pyraimd README

The project's README from github.com/kpleo/pyraimd. As one markdown file: README.md.

Pyramid

Python wrapped Ab initio Molecular Dynamics — a name drawn from the PYR-AIMD letters.

Pyramid brings first-principles engines, machine-learned interatomic potentials (MLIPs), solvers and molecular dynamics into one extensible Python framework. Reference calculations supply energies and forces; fast potentials propagate atomic motion; the framework coordinates when to evaluate, check and update them.

Its energetic force-error method connects force accuracy to the motion of the atoms. A local directional response predicts how force errors grow away from a reference configuration. Signed residual work measures their energetic effect along the trajectory. Together, these quantities guide reference calculations and provide a physical account of the forces used during a run.

Install

Python 3.12 or later. The core install needs only NumPy and ASE — no torch, no PySCF, no external programs. From a checkout:

pip install .            # user install
pip install -e '.[dev]'  # development: adds pytest and ruff

Or install the 0.7.5 wheel into a clean virtual environment. The wheel and source distribution are attached to the corresponding GitHub Release; the examples and example plugins below come from that tag's source tree:

python -m venv ~/.venvs/pyramid && . ~/.venvs/pyramid/bin/activate
pip install pyraimd2-0.7.5-py3-none-any.whl

A first run with the built-in harmonic model — the analytic demo needs no backend installation and finishes in seconds. Validation has three separate layers, and the CLI keeps them explicit:

  1. pyramid validate run.toml — is the configuration well-formed? This never touches the machine's programs or packages.
  2. pyramid validate run.toml --check-environment — are the local runtime prerequisites present (executables, optional packages, local model files)? Read-only and zero-computation: it starts no backend, runs no command, loads no weights, downloads nothing. A blocked/unverified answer explains what it could and could not confirm.
  3. pyramid validate run.toml --probe-backends — explicitly evaluate the structure once per backend (the only layer that computes).
pyramid init --template harmonic --output my_run
pyramid validate my_run/run.toml
pyramid validate my_run/run.toml --check-environment   # harmonic: ready
pyramid run my_run/run.toml
pyramid inspect my_run/runs/harmonic-demo
pyramid resume my_run/runs/harmonic-demo --steps 5
pyramid export my_run/runs/harmonic-demo --force-source driving

All three validation scopes also accept --json, which writes one machine-readable report object to stdout (handy for submission scripts: a blocked environment is distinguishable from an invalid configuration by exit status and by readiness).

Optional backends install separately and are only imported when selected:

pip install '.[pyscf]'   # molecular reference engine
pip install '.[mace]'    # MACE surrogate potentials

all installs both; builders adds optional structure-building tools. Quantum ESPRESSO additionally needs a pw.x executable and pseudopotentials installed outside Python.

The Python import is pyraimd2; the CLI is pyramid (alias pyraimd2). pyramid --version and pyramid --help work offline and download nothing.

Pick your task

Run a first adaptive MD in five minutes

examples/harmonic_adaptive/ is a complete, offline adaptive NVE run: builtin analytic reference and surrogate models drive a toy H2O molecule. It exercises anchoring, surrogate acceptance, independent checks, checkpoints, stop and resume — no external programs, no model downloads, finishes in seconds:

cd examples/harmonic_adaptive
pyramid validate run.toml
pyramid run run.toml
pyramid inspect runs/harmonic-demo
pyramid resume runs/harmonic-demo --steps 10
pyramid export runs/harmonic-demo --force-source reference --output reference.extxyz

pyramid init --template harmonic --output my_run writes the same pair of files as a starting point for your own configuration. The template's policy and verification numbers are demonstration values, not accuracy recommendations for any material. The full field reference is in docs/configuration.md.

A serial relax → NVT → NVE workflow, offline

examples/periodic_lj/ runs a 32-atom fcc Lennard-Jones cell through the three stages with only NumPy + ASE plus the example plugin. The NVT stage is adaptive (fixed model) and the NVE stage continues with the NVT boundary's complete momenta — never rethermalized:

pip install .                       # the core package
pip install examples/backends/pyraimd2_lj   # the example backend plugin
cd examples/periodic_lj
python run_recipe.py --output results/lj-recipe   # relax + NVT + NVE
python run_recipe.py --output results/lj-recipe   # continue/resume, idempotent
pyramid inspect results/lj-recipe/nvt
pyramid export results/lj-recipe/nve --force-source driving

For guarded online model updates under NVT (Python interface), examples/guarded_nvt.py runs offline on analytic potentials, with stop and new-process resume.

Periodic materials (Quantum ESPRESSO + MACE)

examples/qe_mace_skeleton/ shows the configuration shape for a real-material adaptive run: pw.x as the reference engine and a MACE foundation model as the surrogate over a small periodic silicon cell. It is a skeleton, not a verified materials recipe. For complete structure generators and task configurations, see the bulk Si and Al(111) slab examples. They include input requirements, short NVE runs, resume and export commands.

Before pyramid run works you need, on that machine:

Without them, pyramid validate run.toml still parses the configuration and reports configuration problems — and pyramid validate run.toml --check-environment is the layer that reports the local prerequisites themselves before any run is committed (a missing pw.x, a missing optional package, a not-yet-downloaded foundation-model name, or a launcher command such as srun -n 4 pw.x whose solver layer cannot be confirmed statically are reported as blocked or unverified, with the remedy spelled out). With them, pyramid validate run.toml --probe-backends evaluates the structure once with each backend before committing to a run.

Stop, resume and recover

Understand persistent-density retention (read-only)

Plain serial reference MD runs can opt into the persistent density chain ([density] persist = true): every successful evaluation publishes one immutable, content-verified generation under restart/density/ in the run directory. To see why each generation is kept — without changing anything — run:

pyramid density inspect RUN_DIR

The JSON answer lists every generation with its decision (keep / reclaim_candidate / hold / reclaimed), the concrete reasons (latest pointer, retained checkpoints, committed boundary, in-flight inputs, unconsumed producer seeds, tombstones), any blocked references, and the space report per class. reclaim_candidate there is a preview, not a deletion authorization, and the report claims no bound on the run's whole-disk usage. The command is strictly read-only and applies to the plain serial reference-MD workflow shape.

Plug in your own ASE calculator

Two routes, both without modifying the core package:

  1. Python API — the generic adapters wrap separately configured ASE calculator instances:

    from pyraimd2.engines import AseEngine
    from pyraimd2.surrogate import AseSurrogate
    
    engine = AseEngine(reference_calculator, force_consistent=True)
    surrogate = AseSurrogate(potential_calculator)
    
  2. Plugin package — register factories under the pyraimd2.backends entry-point group and the backend name becomes usable from TOML configurations. examples/backends/pyraimd2_harmonic/ is a minimal, installable example (two analytic backends, ~one file of code). pyramid backends lists everything the registry can see.

Capability declarations (energy kind, force consistency, stress, uncertainty) are checked when a backend is created — before any expensive calculation. See docs/architecture.md for the protocols.

Develop a new method

Current scope

The energetic MD loop

  1. Anchor. Evaluate the reference and fast potential at the same atomic configuration. A constant force correction matches the reference there.
  2. Forecast. Probe the local force response along a configuration-space direction. Use the observed displacement to predict the residual force and signed work before requesting a reference at the new geometry.
  3. Propagate or request a reference. Use the corrected fast force while the forecast meets the chosen force budget and domain settings. Otherwise, obtain a new reference label.
  4. Measure the work. At a labeled endpoint, compare reference and anchored potential energies to evaluate signed residual work over the preceding segment. Independently sampled checks also measure errors of accepted forces.
  5. Update and reanchor. An optional on_label callback can use new labels to adapt the potential. A model change or a detected violation requires a fresh anchor and response before accepting further fast forces.

Directional probes supply an empirical forecast. Independent accepted-force checks provide a separate statistical assessment of violations under their sampling protocol. The method guide explains these quantities, their units and the conditions for interpreting them.

Documentation and development

Run the offline core suite (NumPy + ASE only, no optional backends needed):

pytest tests/unit tests/test_smoke.py -q

Backend integration tests marked slow require the corresponding optional software and model files; they are deselected by default and never count as passing when their dependency is missing. Configure production executables, model locations and compute resources in your own run setup.

Citing

If you use Pyramid in your research, please cite the underlying method paper:

License

Pyramid is released under the MIT License.

pyraimd (kpleo/pyraimd)

Searching Database…

Что это такое?Pyramid — это расширяемый Python-фреймворк для молекулярной динамики из первых принципов: движки первых принципов и машинно-обученные межатомные потенциалы (MLIP) работают вместе — эталонные расчёты поставляют энергии и силы, а быстрые обученные потенциалы двигают атомы.
Это Python-библиотека, которую я импортирую, или утилита командной строки?И то и другое: пакет импортируется как pyraimd2 для работы через API, а запуски управляются из терминала через CLI pyramid (псевдоним pyraimd2) — validate, run, resume и backends — это всё подкоманды.
Как мне его запустить?Нужен Python 3.12 или новее; для установки ядра требуются только NumPy и ASE. Установите wheel 0.7.5 из GitHub Releases в чистый venv, затем попробуйте pyramid init --template harmonic --output myrun — это офлайн-демо, которое завершается за считанные секунды.
Для реальных расчётов мне нужна программа квантовой химии вроде Quantum ESPRESSO?Для периодических материалов — да: нужен pw.x в PATH плюс псевдопотенциалы (устанавливаются вне Python) и pip install '.[mace]' для суррогата на базе MACE. Доступны бэкенды QE, closed-shell PySCF, MACE и аналитический гармонический, но необязательные бэкенды устанавливаются отдельно и импортируются только при выборе.
Какие типы симуляций поддерживает текущий релиз?Релиз 0.7.2 охватывает расчёт одиночной точки, релаксацию методами FIRE/BFGS и молекулярную динамику NVE/NVT с фиксированной ячейкой (ASE Langevin) с FixAtoms — в режимах только эталон, только суррогат или адаптивном. Динамика с переменной ячейкой и другие типы ограничений не поддерживаются, а онлайн-обновление модели работает только через Python-интерфейс — ни один TOML-ключ не устанавливает callback обновления.
Он запустится на моём ноутбуке или нужен HPC-кластер?Подойдёт любая машина с Python 3.12+ — встроенные гармонические примеры завершаются офлайн за секунды на ноутбуке. Расчёты реальных материалов обычно выполняются на кластерах: команды запуска вроде srun -n 4 pw.x обрабатываются, и валидация по ним отчитывается.
Что проверяет pyramid validate перед запуском?Три явных уровня: обычный validate разбирает конфигурацию; --check-environment в режиме только чтения проверяет локальные предпосылки (исполняемые файлы, необязательные пакеты, файлы моделей), ничего не запуская; --probe-backends вычисляет структуру один раз для каждого бэкенда — это единственный уровень, который считает. Все три принимают --json для скриптов отправки задач.
Как он решает, когда довериться быстрому потенциалу, а не эталонному движку?Его энергетический метод оценки ошибки сил связывает точность сил с движением атомов: локальный направленный отклик предсказывает, как ошибка сил растёт при удалении от эталонной конфигурации, а знаковая остаточная работа измеряет её энергетический эффект вдоль траектории. Вместе эти величины определяют, когда запускать эталонные расчёты.
Могу ли я объединить этапы relax, NVT и NVE в один рабочий процесс?Да — runserialrecipe выстраивает этапы в цепочку с отдельными идентификаторами запусков для каждого этапа. При передаче сохраняются позиции, ячейка/PBC, массы, FixAtoms, заряды/magmoms и полные импульсы; импульсы инициализируются один раз и никогда не перегреваются заново. examples/periodiclj запускает ячейку из 32 атомов Леннарда-Джонса полностью офлайн.
Помогает ли он управлять временной дисковой памятью на кластерах?По желанию: секция [scratch] в корне направляет временные файлы решателя в один управляемый tmp-корень с политикой хранения. pyramid scratch inspect --root PATH и pyramid scratch clean --root PATH [--dry-run] позволяют просматривать её и безопасно освобождать, при этом проверенные результаты сначала архивируются из scratch.
Creator
kpleo
Size
87 MB
Stars
714
Age
1mo
Commits · 90 Days