Skip to content

Add NVT post-processing for TDEP input generation - #698

Merged
ElliottKasoar merged 31 commits into
stfc:mainfrom
junwen94:dev/tdep
Oct 30, 2026
Merged

ElliottKasoar merged 31 commits into
stfc:mainfrom
junwen94:dev/tdep

Conversation

@junwen94

@junwen94 junwen94 commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR lets janus-core write TDEP input files after NVT molecular dynamics, through post_process_kwargs, so TDEP can fit temperature-dependent force constants to the sampled structures without a separate conversion step.

janus md --ensemble nvt --struct tests/data/NaCl.cif --arch mace_mp --steps 2000 --traj-start 1000 --traj-every 100 --stats-every 100 --post-process-kwargs "{'tdep_compute': True, 'tdep_unit_cell_file': 'tests/data/NaCl-primitive.extxyz', 'tdep_supercell_file': 'tests/data/NaCl.cif'}"

This writes infile.ucposcar, infile.ssposcar, infile.positions, infile.forces, infile.stat and infile.meta to janus_results/NaCl-nvt-T300.0-tdep-inputs.

Changes

  • janus_core/processing/tdep.py: build_tdep_inputs_from_nvt writes the TDEP input files from the MD trajectory and statistics. It pairs frames with statistics by step, falls back to <arch>_forces, and writes the stress columns in the order TDEP reads them.
  • janus_core/calculations/md.py: the tdep_* options in post_process_kwargs. The settings are checked when the MD is created (_config_tdep), so an invalid setup fails before the MD runs. The output directory is reported in output_files and the log.
  • janus_core/helpers/janus_types.py: the TDEP keys in PostProcessKwargs.
  • Tests (tests/test_tdep.py): input generation, error paths and the CLI always run. When TDEP is on PATH, TDEP is also run on committed NVT output, with the phonon frequencies checked against reference values, and on a short seeded MD.
  • CI: TDEP is built in the ci.yml tests job and the release build-docs job, pinned to 6ccdf13, with continue-on-error like PLUMED.
  • Docs: Python and CLI tutorials, the TDEP options in command_line.rst, a TDEP section in installation.rst, the README, and the tdep_* options in the nvt, nvt-nh and nvt-csvr example configs.

Why there is no janus-core[tdep] extra or TDEP_KERNEL

Unlike PLUMED, TDEP support needs no optional extra and no environment variable.

The plumed extra installs the PyPI package plumed ("Python wrappers for plumed"). janus-core uses it during MD through ASE's Plumed calculator. At run time the wrapper loads the PLUMED library from the path in PLUMED_KERNEL, and otherwise raises "PLUMED not available, check your PLUMED_KERNEL environment variable". That is why PLUMED needs both.

TDEP is a set of Fortran command-line programs, built on a Fortran library (libolle). Neither has Python bindings, and TDEP is not packaged on PyPI or conda-forge. janus-core never calls TDEP. With tdep_compute: True, it only writes TDEP's infile.* text files after the MD, using ASE and NumPy, which are already core dependencies. So there is nothing for an extra to install and nothing for janus-core to locate, and no TDEP_KERNEL equivalent is needed.

To run TDEP on the generated files, and for the optional TDEP tests, the TDEP executables only need to be on PATH. That is what TDEP's installation instructions set up. The TDEP tests are skipped when the executables are not found, and the TDEP section of installation.rst explains this.

Testing

uv run pytest tests/test_tdep.py

The two tests that run TDEP are skipped unless extract_forceconstants and phonon_dispersion_relations are on PATH.

Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
@junwen94
junwen94 requested a review from oerc0122 April 21, 2026 11:08
@junwen94

Copy link
Copy Markdown
Contributor Author

Addressed Jacob's review comments and pushed an update. Verified with uv run pytest tests/test_tdep.py -q.

oerc0122
oerc0122 previously approved these changes Apr 21, 2026

@oerc0122 oerc0122 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some minor recommendations, otherwise looks ok.

Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
@alinelena

Copy link
Copy Markdown
Member

be sure we add tdep in CI and we actually test it

Comment thread .gitignore Resolved

@ElliottKasoar ElliottKasoar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, @junwen94!

Would you be able to add a (very brief) CLI tutorial for this too?

Related to that, it would be great to include these kwargs in the example configs found in docs/source/examples/full/, similarly to how we already show rdf_compute etc. This provides another example for how you can specify these.

Co-authored-by: Jacob Wilkins <46597752+oerc0122@users.noreply.github.com>
@alinelena

Copy link
Copy Markdown
Member

@junwen94 can you go through the comments please? and also we will need to install tdep in the ci to have a proper test, in the sense tdep runs and we get to test the real data.

junwen94 and others added 6 commits May 22, 2026 13:24
janus_core/processing/tdep.py (oerc0122 round 2):
- Fix syntax error in positions writer and define out_fmt = '{:.12f}'.format
- Collapse meta_path.write_text into a single triple-quoted f-string
- Refactor stat_path block to iterate data tuple through out_fmt

docs/source/tutorials/python/anharmonic_phonons.ipynb (ElliottKasoar):
- Clear all cell outputs and execution counts
- Drop the static dispersion PNG; notebook now runs TDEP via !-shell calls
  and embeds the gnuplot-generated PDF (converted via pdftoppm)
- Add nbsphinx execute=always + timeout metadata so this notebook is the
  only one executed at docs build time (global default remains 'never')

docs/source/examples/full/nvt.yml (ElliottKasoar):
- Add tdep_compute / tdep_unit_cell_file / tdep_supercell_file /
  tdep_output_dir under post_process_kwargs, mirroring rdf_compute

.gitignore (ElliottKasoar):
- Remove ! exceptions for the tutorial notebook and dispersion PNG

.github/workflows/ci.yml (alinelena):
- Install TDEP via conda-forge per upstream INSTALL.md and build with
  build_things.sh; cache the build under ~/tdep
- Add poppler-utils for pdftoppm
- Bump docs job timeout to 30 min and switch shell to bash -el
The previous run produced no PDF because gnuplot was not on the CI runner.
Use gnuplot-nox to avoid pulling in X11/Qt. Also print produced TDEP
outputs at the end of the !-shell pipeline to aid future debugging.
Previous run still failed at Image cell, meaning a silent failure earlier
in the TDEP pipeline. Bash with set -ex aborts on first error and echoes
each command, so the next CI run will show exactly which step is failing.
TDEP libolle/lo_phonon_bandstructure_on_path.f90 appends a _pdf suffix
when pdfplot is true (the -p / --pdf flag), so the script TDEP actually
writes is outfile.dispersion_relations.gnuplot_pdf, not .gnuplot.

Also drop -x from set -ex now that the failure is identified; keep -e
for fail-fast on future regressions.
Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread tests/test_tdep.py Resolved
@alinelena
alinelena requested a review from oerc0122 July 18, 2026 06:59
- Build TDEP 6ccdf13 before make all, as in ci.yml, so the TDEP
  tutorials run TDEP when the docs are published
- Continue on error: if TDEP does not build, a warning is shown and the
  tutorials skip their TDEP steps, so the release is never blocked
- List other TDEP calculations that the generated inputs can be used
  for, such as higher-order force constants, free energies and the
  thermal conductivity, linking to the TDEP tutorials
- Note what MLIPs do not usually provide (Born effective charges for
  --polar, dielectric tensors for infrared and Raman spectra), that
  classical MD has no nuclear quantum effects, and that higher-order
  properties are more sensitive to MLIP errors
@junwen94

Copy link
Copy Markdown
Contributor Author

@alinelena @ElliottKasoar @oerc0122 Sorry for the long silence. I've pushed changes for all the review comments and replied in each thread. Here's a summary.

CI (docs workflow, two package managers, gnuplot/poppler)

  • The ci.yml docs job is back to exactly what's on main (08d20a4). It only needed TDEP because the notebook's nbsphinx execute: always, now removed, overrode make html's nbsphinx_execute=never.
  • As Elliott suggested, TDEP is built only in the tests job, after PLUMED and with continue-on-error like PLUMED. It uses TDEP's own CI recipe (its apt packages, .github/important_settings.x86_64 and build_things.sh), pinned to 6ccdf13. TDEP is added to PATH only if the build succeeds; otherwise a warning annotation is shown and the TDEP tests skip. There's no conda or second Python.
  • gnuplot and poppler are gone. They only turned TDEP's plot into a PNG; the tutorial now plots TDEP's HDF5 output with matplotlib and h5py, which phonopy already installs.
  • The release build-docs job in publish-on-pypi.yml, which runs the tutorials with make all, also builds TDEP the same way (947b60c), so the published tutorials show TDEP's results. With continue-on-error, a failed TDEP build can't block the PyPI publish: the tutorials' TDEP cells then print a message and skip.
CI details
  • TDEP is pinned so that changes to it can't move the reference values in the tests. I used a main commit because TDEP's last release, 25.03, is 111 commits behind it, and TDEP's own CI passes on 6ccdf13.
  • TDEP is cloned into $RUNNER_TEMP, outside the checkout, so pytest . doesn't collect TDEP's own tests. The build steps have their own timeout-minutes.
  • ubuntu-latest moves to 26.04 between 19 October and 19 November (actions/runner-images#14748). I ran the recipe in x86_64 Docker containers for both Ubuntu 24.04 and 26.04: all the apt packages exist, TDEP builds, and the test frequencies match my macOS build to 7e-12.
  • TDEP is only built in ci.yml, so the TDEP tests skip in mac-ci, windows-ci and ci-dev.

Tests that run TDEP (Elliott; Alin 1, 2)

tests/test_tdep.py (4ac63a1) now covers:

  • Always: the input files written from committed janus-core MD output (forces, stats rows paired with frames by step, stress order), each error path, each check made when the MD is constructed, and the CLI (CliRunner).
  • With TDEP on PATH: TDEP run on the committed MD output, checking the number of branches, that there are no imaginary modes, and the Γ-point optical and maximum frequencies against reference values from 6ccdf13. Also a short seeded MD → TDEP run, with loose physical bounds, since fresh MD output varies.
  • The TDEP tests are skipped individually, rather than the whole module as in test_md_plumed.py, so input generation is always tested. Checking numbers matters because TDEP exits with 0 on most errors, even for missing inputs or wrong physics (table below).
Test details
  • The fixture is janus-core NVT output for NaCl at 300 K (MACE-MP small, seeded, after equilibration): a 64-atom supercell of the two-atom primitive cell, which is a non-diagonal supercell, with 10 frames and 21 stats rows. It's about 130 KB, added with git add -f, and committed so that the reference values don't depend on MACE or torch versions. Frequencies are compared at rel. 1e-4.
  • Reintroducing any of the 10 bugs fixed below makes at least one test fail. tdep.py and the new code in md.py are fully covered.
  • TDEP 6ccdf13 exits with 0 for all of these:
Input Result
infile.ucposcar missing "Could not open infile.ucposcar"
unknown command-line flag "switch ... is unknown!"
forces sign-flipped imaginary modes down to -6.22 THz
forces scaled by 0.01 maximum frequency 0.62 THz instead of 6.22
forces shifted by one frame imaginary modes down to -4.88 THz
atom order scrambled imaginary modes

Tutorials and docs (saved outputs, CLI tutorial)

  • The notebooks have no saved outputs, and the nbsphinx execute: always metadata is removed, so they only run in make all. Their TDEP and plot cells print a message and skip if TDEP isn't on PATH.
  • I rewrote the Python tutorial (primitive unit cell, sampling after equilibration, plot of TDEP's HDF5 output) and added a very brief CLI tutorial. Both are titled "Anharmonic Phonons with TDEP".
  • command_line.rst describes the TDEP options, what is checked before the MD starts, and what to watch out for (file formats, forces in the trajectory). installation.rst has a TDEP section next to PLUMED's, and the README lists TDEP under phonons.
  • The docs also list further TDEP calculations that the files can be used for (higher-order force constants, free energies, thermal conductivity, spectral functions), note what needs data that MLIPs don't usually provide (e.g. Born effective charges for --polar), and note that higher-order properties are more sensitive to MLIP errors.
  • Locally, make html builds with no warnings, and make all with TDEP runs all the tutorials. The TDEP tutorials also run without TDEP.

Fixes found by running TDEP and the example configs

Running TDEP exposed several bugs; docs/source/examples/full/nvt.yml, for example, failed after the whole MD. The main fix (48d0b60) checks the TDEP settings when the MD object is created (_config_tdep, like _config_plumed), so a bad setup fails before the MD starts, following Jacob's earlier point about checking first.

Full list
  • Checked when the MD is created (48d0b60):
    • the tdep_* files are given (as paths) and exist;
    • the ensemble is NVT (nvt, nvt-nh or nvt-csvr), since TDEP fits configurations sampled from a canonical ensemble at temperature T;
    • there's no PLUMED, since its forces are biased;
    • minimize doesn't relax the cell;
    • traj_every is a multiple of stats_every;
    • with a temperature ramp, frames are only saved after the ramp;
    • at least one frame will be saved;
    • the supercell matches the MD structure (atoms, order and cell);
    • the unit cell and supercell are commensurate, as TDEP checks: the volume ratio, the number of atoms, and an integer supercell matrix. A primitive cell written as CIF loses its orientation, and extract_forceconstants then fails with "Supercell matrix with non-integer values"; the error message explains this.
  • Stats rows matched to frames by step (26f4bd1). Only the counts were compared before. With equal stats and trajectory intervals, any traj_start > 0 failed, and with different intervals, rows and frames could be paired wrongly without an error.
  • Forces with invalidate_calc: True (26f4bd1): the <arch>_forces column (e.g. mace_mp_forces) is used when forces is absent.
  • Stress order in infile.stat (26f4bd1): the off-diagonals are now written as xy, yz, xz, the order TDEP's reader uses. TDEP's docs/files.md says xz, yz, xy, but TDEP's own writer agrees with the reader. This changes the tuple from Jacob's second style thread. Reported upstream as docs/files.md: infile.stat off-diagonal stress order doesn't match read_from_file (xy, yz, xz) tdep-developers/tdep#189.
  • Real timestep in infile.meta (26f4bd1): timestep * traj_every, instead of the hard-coded 0.0.
  • The output directory is created only after all checks pass, the default directory name includes param_prefix, and the directory is reported in output_files and the log (48d0b60).
  • nvt.yml failed after the whole MD with a ValueError (2 stats rows for 1 frame, because of traj_start: 10), and then would have failed again because invalidate_calc drops the forces column. Both are fixed, and the config itself is updated (see below).

Example configs (Elliott's review)

  • nvt.yml, nvt-nh.yml and nvt-csvr.yml show the tdep_* kwargs next to rdf_compute, with tdep_compute: True and the primitive cell as the unit cell. Each parameter changed to make this valid is marked # changed for TDEP: <reason>: filter_class: null in minimize_kwargs (nvt and nvt-csvr), so the cell isn't relaxed, and traj_start: 100 (all three), so frames are saved only after the 90-step heating ramp.
  • The tdep_* kwargs are not in nve.yml or the NPT-type configs. TDEP needs structures sampled from an NVT ensemble (its tutorial: "The molecular dynamics simulations have to be in the NVT ensemble"): in NPT the cell changes, so displacements can't be defined, and NVE doesn't control the temperature. tdep_compute: True is therefore rejected for these ensembles before the MD starts, so it would make these configs fail.

No janus-core[tdep] extra or TDEP_KERNEL

janus-core never calls TDEP: it only writes TDEP's input files, and TDEP's Fortran programs (with no Python package) just need to be on PATH. PLUMED's extra is a Python wrapper, used during the MD, that finds the PLUMED library through PLUMED_KERNEL. There are more details in the PR description.

Follow-up

#733 covers TDEP workflows that this PR doesn't: stochastic sampling (sTDEP) and polar corrections.

The YAML log formatter only replaces backslashes in str arguments, so
passing the Path itself wrote Windows paths with backslashes inside a
double-quoted YAML string, making the log file invalid on Windows.
Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/publish-on-pypi.yml Resolved
Comment thread janus_core/calculations/md.py Resolved
Comment thread janus_core/calculations/md.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
Comment thread README.md Resolved
Comment thread janus_core/calculations/md.py Resolved
Comment thread janus_core/calculations/md.py Resolved
Comment thread janus_core/processing/tdep.py Resolved
@alinelena

Copy link
Copy Markdown
Member

@junwen94 @oerc0122 @ElliottKasoar can we get this in a shape to be merged? if needed have a meeting to have it done... I want to go on AL with it done.

oerc0122
oerc0122 previously approved these changes Oct 29, 2026

@ElliottKasoar ElliottKasoar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@junwen94 given this is now a requirement for the tutorials, can we also add a note somewhere in the dev docs (e.g. in the Notebook tutorials section, or maybe a little higher)

I think this is otherwise pretty much fine if between you you can resolve the remaining comments, @junwen94 and @oerc0122

ElliottKasoar
ElliottKasoar previously approved these changes Oct 29, 2026

@ElliottKasoar ElliottKasoar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @junwen94!

@ElliottKasoar
ElliottKasoar marked this pull request as draft October 29, 2026 14:32
@ElliottKasoar

Copy link
Copy Markdown
Member

Pending a fix from @junwen94

@junwen94

junwen94 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

While making the TDEP figure for the paper, I found that TDEP fails when the structure files are extxyz and the lattice parameter comes from an MLIP relaxation.
extxyz stores positions with only 8 decimals, but TDEP needs the unit cell and supercell to agree to machine precision. The tests and tutorials use a = 5.64 Å, where every position is exact with 8 decimals, so we didn't see this before.
build_tdep_inputs_from_nvt moves each supercell atom onto the exact image of a unit-cell atom before writing infile.ssposcar (by less than 1e-8 Å), so extxyz files now work. A new test runs TDEP on the committed data scaled to a relaxed lattice parameter, and fails without the fix.
9dfd7f0 fix above issues.

@ElliottKasoar
ElliottKasoar marked this pull request as ready for review October 30, 2026 14:25

@ElliottKasoar ElliottKasoar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks again, @junwen94!

@ElliottKasoar
ElliottKasoar merged commit 6f23c4f into stfc:main Oct 30, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New/improved feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants