Skip to content

feat(lcao): add optional LibRI GPU contractions through DDLA - #29

Open
Stardust0831 wants to merge 79 commits into
review/lcao-hse-gpu-basefrom
experiment/lcao-hse-gpu
Open

Stardust0831 wants to merge 79 commits into
review/lcao-hse-gpu-basefrom
experiment/lcao-hse-gpu

Conversation

@Stardust0831

@Stardust0831 Stardust0831 commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

What's changed?

Enable optional GPU acceleration of LCAO Kohn–Sham exact-exchange tensor contractions through LibRI's DDLA CUDA backend. ENABLE_LIBRI_GPU defaults to OFF; INPUT device_exx defaults to cpu. To select GPU RI, build with USE_CUDA=ON, ENABLE_LIBRI_GPU=ON, an explicit compatible LIBRI_DIR and a CUDA DDLA installation, then set:

device      gpu
device_exx  gpu
symmetry    -1

GPU RI requires LibRI v0.3.0.0 or newer and DDLA's handle-selected batched GEMM API. The verified DDLA revision is 7c0ca08b4349a527cec2a0c0af7d1a1082bd38c7; the original DDLA v0.0.6 release has an incompatible interface. CMake consumes LibDDLAConfig.cmake / ddla::ddla and checks real/complex GPU API compilation and linkage. GPU RI requires C++17; CPU RI retains its existing dependency selection and C++14 requirement.

GPU EXX temporarily rejects effective symmetry 1, regardless of exx_symmetry_realspace. The guard reports an error after normal INPUT processing, without changing settings itself; existing resets such as MD setting symmetry to 0 still apply. Use symmetry 0 (time reversal only), symmetry -1 (no symmetry), or CPU RI. exx_symmetry_realspace is an existing parameter; this restriction adds no parameter. Remove the restriction only after corrected dependencies pass application-level symmetry validation.

The selector applies to LCAO Kohn–Sham exchange. LR/RDMFT engines retain CPU contractions, including when LR reuses Kohn–Sham exchange geometry. All ranks on a node must see the same allocated GPU list, with at least as many visible GPUs as local ranks; per-rank single-GPU masking is unsupported. Build/install instructions and INPUT help are updated.

Unit Tests and/or Case Tests for my changes

HSE runtime and performance results below are pinned to f2667c6eed30e661a36bfb0ae1844802c99f171e on SAI 16V100. The subsequent integration/test cleanup at 6dd58cf762fd730d62eb61ed36e3383e660066bb has separate targeted validation; the benchmark executable is unchanged.

  • At the benchmark source: complete GPU executable builds, CPU/GPU serial EXX INPUT suites pass 33/33 tests each, and 8/8 CLI checks cover GPU rejection with symmetry 1 and true/false/default real-space settings, implicit defaults, CPU symmetry, and GPU symmetry 0/−1. Governance and changed-file formatting checks pass.
  • Fresh Si64 benchmark: 10/10 scientific runs and 9/9 energy/force comparisons pass, including a displaced structure with maximum force 0.398013 eV/Å. Same-executable CPU/GPU differences are at most 9.664e-13 eV/atom and 3.163e-10 eV/Å across these cases. The displaced pair has force-vector difference 1.415e-10 eV/Å. All calculations converge below scf_thr=1e-8 and report 64 force vectors; forces are enabled, stress and symmetry disabled.
  • The source tree, executable, inputs, pseudopotential/orbital files and runtime placement were audited. A driver assertion and a mistakenly duplicated recovery attempt are retained separately; the completed ten-run sample and all failed-attempt records are preserved.

Targeted follow-up validation: the original GPU Debug MODULE_RI_exx_workspace link failure was reproduced (14 unresolved DDLA symbols); linking its existing target to LibRI::LibRI fixes it. CPU/GPU Debug workspace tests and standalone consumer tests all pass (four CTest invocations, 1/1 each). Real INPUT-reader + EXX-item suites pass 47/47 CPU and 49/49 GPU, with zero skips on a visible V100; masking GPUs skips exactly the two GPU reader cases. Cases cover omitted symmetry, explicit symmetry=1 with real-space reduction disabled, accepted 0/−1, CPU symmetry and MD's normal reset to 0. The existing reader source is moved to unittests/test_read_input_serial.cpp without changing its tested contents. Runtime OMP/BLAS=1. Combined governance/format checks pass.

The duplicate LibRI numerical accumulation test is removed from ABACUS. Upstream LibRI owns its contraction regression; ABACUS retains the small dependency-interface check and HSE application comparisons. No additional INPUT parameter, dependency implementation patch, compatibility shim or custom DDLA finder is added by this cleanup. LR help now reflects the existing CPU workspace behavior. These test/build/help changes do not change HSE runtime algorithms.

Download follow-up validation logs, scripts, patches and source hashes · validation report. Targeted builds and limits are recorded separately from the pinned HSE benchmark.

Raw HSE inputs, outputs and analysis scripts are directly downloadable in the benchmark section below; archive payload hashes and offline reanalysis pass.

Commands recorded in the evidence:

cmake --build build/abacus-gpu --target abacus_std_gpu MODULE_IO_read_item_serial --parallel 28
cmake --build build/abacus-cpu --target MODULE_IO_read_item_serial --parallel 24
ctest --test-dir build/abacus-gpu -V -R '^MODULE_IO_read_item_serial$'
ctest --test-dir build/abacus-cpu -V -R '^MODULE_IO_read_item_serial$'
abacus_std_gpu --version
abacus_std_gpu -h device_exx
abacus_std_gpu --check-input
python3 analyze.py
python3 audit-assets.py
python3 verify-analysis.py

Targeted follow-up commands (full configure flags and return codes are in the validation archive):

cmake --build build/abacus-gpu-debug --target MODULE_RI_exx_workspace --parallel 24 --verbose
ctest --test-dir build/abacus-gpu-debug -V -R '^MODULE_RI_exx_workspace$'
ctest --test-dir build/abacus-cpu-debug -V -R '^MODULE_RI_exx_workspace$'
ctest --test-dir build/consumer-cpu -V
ctest --test-dir build/consumer-gpu -V
cmake --build build/final-gpu --target MODULE_IO_read_input_serial MODULE_IO_read_item_serial --parallel 32
ctest --test-dir build/final-cpu -V -R '^MODULE_IO_read_(input|item)_serial$'
ctest --test-dir build/final-gpu -V -R '^MODULE_IO_read_(input|item)_serial$'

The archive includes the per-case INPUT files and expected CLI exit codes. Runtime/INPUT checks use OMP=1; performance measurements explicitly use one MPI rank, OMP=4, BLAS=1 and four bound physical CPU cores per V100.

Earlier release validation at 64b7ef613 passed four dependency CTest checks and ten application runs / five backend comparisons covering real/complex tensors, spin polarization, one/two MPI ranks, forces and stress with real-space EXX symmetry disabled. Pinned earlier evidence. Those earlier acceptance results do not override the current broader symmetry restriction. The separate CPU build validated the INPUT target; BSE numerics, HIP, MAGMA, multi-node execution, SOC and long MD are outside this validation.

Benchmark results

HSE06 Si64 on SAI 16V100: one V100, one MPI rank/four bound physical CPU cores, OMP=4, BLAS=1; APNS efficiency LCAO, Γ-only, 128 bands, 100 Ry, SCF=1e-8, RI thresholds=1e-4. Fresh atomic starts; symmetry -1, forces enabled, stress disabled. The existing exx_symmetry_realspace parameter automatically becomes 0 here.

Download original inputs and small outputs — 2.57 MiB tar.gz, 490 files · full report · individual timings CSV · numerical comparisons CSV · file/checksum manifest.

The archive contains original INPUT/STRU/KPT files, Si pseudopotential/orbitals, outputs ≤10 MiB/file, scripts and validation logs; larger omissions are listed in the manifest. Downloaded archive SHA256 verified: 4ca994d552094f9e3180751b6572653798d1463ccec9c893c3308f5143fe5587.

“beta13 baseline” denotes a baseline built from ABACUS v3.11.0-beta13, with the versions below. Commit IDs distinguish dependency revisions that share a header version string.

Build ABACUS LibRI LibXC
beta13 baseline 4e9f1636b7ca b0eff7ad70ab, CPU; header version 2.1.1 7.0.0, CPU
beta13 + GPU libraries same beta13 revision + recorded adapter patch 0e8afc393, GPU 3c7794c5047d, GPU
PR, CPU/GPU LibRI f2667c6ee, same executable v0.3.0.0 (a385ac9), CPU/GPU 7.0.0, CPU

Before/after timing composition. Ideal Si64, two starts per variant, paired within two allocations with reversed execution order. Means in seconds; wall time includes initialization, the initial GGA SCF, HSE SCF and complete atomic forces. Three decimals preserve means of timers printed to 0.01 s.

Component / s beta13 baseline beta13 + GPU libraries PR, CPU LibRI PR, GPU LibRI
Electronic EXX 359.895 26.295 104.265 24.980
EXX forces 398.015 29.105 115.645 28.020
Remaining wall time 84.920 30.265 32.680 32.600
Complete calculation 842.830 85.665 252.590 85.600
Comparison Overall speedup Electronic EXX saved / s EXX forces saved / s Remainder saved / s
beta13 baseline → beta13 + GPU libraries 9.84× 333.600 368.910 54.655
beta13 baseline → PR CPU LibRI 3.34× 255.630 282.370 52.240
PR CPU → GPU LibRI 2.95× 79.285 87.625 0.080

The 9.84× beta13 comparison saves 757.165 s: electronic EXX contributes 44.06%, EXX forces 48.72%, and remaining work 7.22%. It includes dependency/build changes. Baseline → PR CPU LibRI already gives 3.34×, combining ABACUS/dependency/build changes; this is not an isolated LibRI-version comparison. Selecting GPU in that same PR executable then gives 2.95×, with LibXC fixed on CPU and 99.95% of the saving in the two EXX scopes. Baseline → PR GPU LibRI is 9.85× overall.

The paired gains are 10.69×/9.11× for beta13 → experimental and 3.05×/2.85× for PR CPU → GPU; only two repetitions are available. Remainder = wall − electronic EXX − EXX forces. The following nested timers overlap these scopes and must not be added again; effective potential includes LibXC potential.

Nested timer / s beta13 baseline beta13 + GPU libraries PR, CPU LibRI PR, GPU LibRI
Effective potential 30.355 10.160 13.695 13.700
LibXC potential 20.250 4.025 8.165 8.185
LCAO solver 31.090 7.990 6.555 6.590

Calculation consistency. All 10/10 scientific runs finish normally, converge below 1e-8 and output 64 force vectors; 9/9 numerical comparisons pass. Ideal runs retain 12 GGA + 8 HSE iterations. The displaced CPU/GPU pair both use 12 + 12 iterations, with final residual 9.742e-9. The table reports maximum differences across paired runs.

Comparison max ΔE / eV max ΔE / eV/atom max atom-wise ‖ΔF‖ / eV/Å Result
beta13 baseline → GPU libraries 1.388e-07 2.169e-09 1.273e-09 PASS
beta13 baseline → PR CPU LibRI 1.455e-11 2.274e-13 2.236e-10 PASS
beta13 baseline → PR GPU LibRI 4.729e-11 7.390e-13 4.583e-10 PASS
PR CPU → GPU, ideal Si64 6.185e-11 9.663e-13 3.162e-10 PASS
PR CPU → GPU, displaced Si64 3.638e-12 5.684e-14 1.414e-10 PASS

Cross-build limits are 1e-6 eV/atom and 1e-5 eV/Å; same-PR CPU/GPU limits are 1e-8 eV/atom and 1e-6 eV/Å. Force differences are per-atom Euclidean vector norms. The extra pair moves the first Si atom by (+0.01,+0.02,−0.015) Å and has maximum force 0.398013 eV/Å, verifying nontrivial forces; it is not pooled into the ideal-structure timings. Original references and tolerances are unchanged.

Earlier beta13/CP2K and LibRI PR #17 comparisons remain separately documented with their original inputs and outputs.

Known symmetry limitation

Released LibRI v0.3.0.0 gives real/complex Si2 GPU energy and stress differences of 0.0324593 eV and 0.305868 kbar when real-space EXX symmetry is enabled. Its standalone symmetry fixture is outdated, and migrating only the fixture to the Wrapper API still fails GPU contractions.

Source tracing and isolated reproduction identify a later Wrapper regression after the previously merged symmetry fix. A proposed local loop/generator repair passes the standalone real/complex regression; it has not yet been validated in ABACUS. LibRI PR #24 at d8fc6eca97f6ccf0b4448644f2f891ad7f2eb2e9 was separately tested: it reduces failing individual GPU labels from 8/18 to 4/18; real, complex and the combined sum still fail. Removing the four remaining intermediate-atom filter calls in a separate diagnostic source copy passes all 456 checks. This does not establish ABACUS symmetry acceptance. Report, raw sources/logs and diagnostic patch. The guard therefore remains in place. References and tolerances are unchanged.

At 6dd58cf762fd730d62eb61ed36e3383e660066bb, all 17 reported CI check runs pass, including the CUDA runtime tests, GNU/Intel builds, CPU tests, pre-commit and governance. The CUDA error 209 failures at earlier f2667c6/853b1644e heads are historical results; the current CUDA run passes. The explicit V100 LibRI validation and its stated symmetry limits remain as documented above.

Linked Issue

Reproduction data and timing composition.

Governance Notes

  • INPUT metadata, help, validation and MPI broadcast cover device_exx; both affected INPUT entries document the temporary symmetry restriction. Generated INPUT documentation is not committed.
  • INPUT tests use the existing serial target and public registry accessor; no new test access macros are introduced.
  • Core impact: select the backend before LCAO EXX initialization and encapsulate dependencies in LibRI::LibRI and ddla::ddla.
  • The removed standalone numerical test carried direct MPI initialization/finalization calls; these are absent from the final PR, so no exception for them is needed. Reader tests reuse the serial target, with the migrated source registered in unittests/CMakeLists.txt.
  • Follow-up: add DDLA installation to the existing toolchain workflow.

@Stardust0831 Stardust0831 changed the title experiment(lcao): 接入 LibRI/DDLA GPU 杂化泛函并验证 HSE feat(lcao): add optional LibRI GPU contractions through DDLA Oct 18, 2026
Stardust0831 and others added 19 commits October 18, 2026 11:04
…ling#8277)

* fix(md): support Angstrom and atomic-unit STRU coordinates

* test(md): cover Cartesian STRU units with wrapping and replication

* test(md): keep reader failure paths collective-safe
…pmodeling#8170)

* fix(rt): convert sHG density to ordinary NAO frame for RI exchange

* fix(rt): preserve RI image phases before exchange contraction

* test(rt): refresh PBE0 references for corrected RI input density

* fix(rt): unify direct-kernel RI image phase handling

* fix(rt): preserve two-spin storage when EXX grows HR

* style(rt): use explicit types and concise test descriptions

* style(rt): keep EXX field arguments on the call line

* refactor(rt): obtain EXX field context through electronic state

* style(ri): name density copy ranges and expand mixing setup

* refactor(ri): move EXX interface and hybrid helpers into source files

* style(ri): trim redundant phase and interface comments

* refactor(ri): forward-declare hybrid phase interface types

---------

Co-authored-by: memii-x <memii-x@users.noreply.github.com>
…sources there without a test_ prefix (deepmodeling#8245)

The checker now enforces the unit test layout under source/ as an error:

- no file may be added (or renamed/copied in) to a legacy test directory
  such as test/, tests/, test_serial/, test_parallel/, test_gpu/, and a
  .c/.cc/.cpp/.cxx/.cu modified there blocks too, so a touched legacy test
  is migrated into unittests/; deletions and edits to legacy headers,
  CMakeLists.txt and data stay allowed;
- a source added or modified directly in unittests/ must start with test_;
  headers (.h/.hpp/.cuh) are free-named for mocks and helpers;
- subdirectories of unittests/ hold data only: any code file there blocks.

Whether the name after test_ matches the file under test is left to review.
AGENTS.md rule 11, the grading matrix, CodeRabbit and Copilot instructions
are updated to match.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…g#8274)

* Governance: require Autotest cases for integration tests

Integration tests are Autotest case directories with result.ref, listed
in CASES_*.txt. Recent PRs instead register standalone Python drivers
with add_test() that launch ABACUS, rewrite fixtures at run time, and
assert on output themselves. Add AGENTS.md rule 22 and an "Integration
Test Drivers" section that keep Autotest as the default, allow a
standalone driver only for checks Autotest cannot express, and set
placement, fixture, optional-interpreter, and MPI requirements for
those drivers. Add a matching human-confirmation row to the rule
grading matrix; no mechanical check is introduced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: shorten integration test driver guidance

* docs: further condense integration test guidance

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* test(md): register MD/RT boundary contract as integration coverage

* test(rt): move boundary coverage out of MD unit tests

Add dedicated boundary_fix and td_folding units with independent phase oracles. Preserve the complete MD/RT contract and all its assertions in the CTest integration tree. Remove RT, HContainer and orbital sources from MODULE_MD_base_mpi.

Validation: full CPU/MPI binary build; 18 related CTest variants; 4 MD variants with LCAO/OpenMP disabled; clang-format 23.1.3 and cmake-format 0.6.13. No production documentation update required: numerical behavior and interfaces are unchanged; test coverage and commands are documented alongside the integration case.

* style(md): format retained MD base unit tests

* test(rt): share boundary checks and relocate MD contract

Keep the MD/RT contract in the existing RT test directory and register its own CTest target after MD support sources are available. Share matrix and coefficient checks with direct boundary units; retain MD-owned state assertions in MD units. Restore tests/integrate to the upstream version.

Preserve saved-A folding, skew-cell conversion, both matrix layouts, MPI/OpenMP variants, migration, repeated sync and next-step clearing. Fix floating-point reduction and name the combined folding angle. Validation: 18 relevant tests and 4 MD-only tests passed; official clang-format/cmake-format checks passed. No production documentation update required: test-only refactor.

* test(rt): reuse original boundary checks and trim folding coverage

Remove the MatrixBuilder callback and analytic-matrix abstraction. Move the original fold_hybrid body directly, share its existing H/S/psi assertions, and keep hybrid checks before migration and Bloch checks after repeated sync. Replace the expanded folding matrix/layout suite with one focused Bloch/hybrid phase test.

Original MD assertions, saved-field discrimination, skew-cell conversion, distributed/gathered matrices, Psi cursor and 1/4-rank OpenMP coverage are preserved. Validation: 18 relevant CTest variants and 4 MD-only variants passed; official formatting checks passed. No production documentation update required: tests only.

* test(rt): combine folding and MD boundary test source

Keep direct boundary_fix units isolated. Put the unchanged folding test in test_md_rt_boundary.cpp and build it with the MD/RT contract once. Preserve separate unit and integration CTest entries through explicit GoogleTest filters for all MPI/OpenMP variants.

Validation: 18 related CTest variants and 4 MD-only variants passed. Verified all 8 shared-binary entries ran the intended nonempty test suites. Official C++/CMake format checks passed. No production documentation update required: tests only.
…_max_iter (deepmodeling#8301)

* docs(dfpt): drop the PR number from a historical review comment

Source comments should state the technical fact without referencing
workflow metadata.

* feat(dfpt): dedicated Sternheimer solver knobs dfpt_lin_conv_thr/dfpt_lin_max_iter

dfpt_conv_thr and dfpt_max_iter controlled three nested loops at once:
the outer irrep re-pass, the per-displacement response-SCF mixing, and
the projected-CG solve of the Sternheimer equation. That coupling makes
it impossible to keep a tight outer criterion while limiting the depth
of the inner linear solve, which flat semicore band systems need: with
2s2p semicore the shifted operator is near-singular and a full-depth
inner solve against an unconverged screening potential amplifies the
response beyond what the outer mixing can damp (residual pinned at 1.0
for the full iteration budget).

Add dfpt_lin_conv_thr and dfpt_lin_max_iter, non-positive sentinels
that inherit the outer values (the historical single-knob behavior), so
existing INPUT files are unaffected. The five Sternheimer call sites now
read the dedicated getters; outer-loop semantics are unchanged.

* docs(dfpt): document the lin-knob accuracy tradeoff; extend the inheritance test

Review follow-up on the input metadata: define dfpt_lin_conv_thr as the
relative residual ||P_c r|| / ||P_c b|| of the projected system, state
that the outer mixing residual does not check the achieved Sternheimer
residual, that the knobs also affect the one-shot Gamma position
response, and recommend validating phonons / dielectric tensor / Born
charges against tighter inner settings when the knobs are loosened.

Extend LinSolverKnobsInheritByDefault: resetting an explicit override
to the sentinel resumes inheritance immediately, the resumed
inheritance keeps tracking later outer changes, and one knob can stay
pinned while the other inherits.

* test(dfpt): public-forwarding check of the lin knobs through DFPT_PW

Review follow-up: a default-constructed DFPT_PW already owns its Impl
(the constructor builds it), and the set_lin_* setters only touch
Impl::data_, so the forwarding path is inspectable through get_data()
before init() with no basis or pseudopotential setup. Pins the
inherit-before-set and pinned-survives-outer-change semantics through
the public API; the sentinel reset stays pinned at the data layer.
…g#8307)

* perf(pw): reuse structure factors in Ewald stress

* test(pw): validate order-10 Ewald stress regression

* test(ofdft): align interpolated Ewald stress references

* fix(pw): accept dense structure factor prefixes in Ewald stress
…epmodeling#8313)

* Update read_inp_sys.cpp

* Refactor DSP k-point layout validation functions

Refactor DSP layout validation functions for clarity and correctness.

* Update test_read_inp_sys.cpp

* Refine comments on DSP layout and k-point handling

Updated comments for clarity and accuracy regarding DSP layout constraints and effective k-point calculations.
Stardust0831 and others added 30 commits November 21, 2026 15:02
… outputs (deepmodeling#8293)

* update INPUT file

* fix(bands): add BANDS/ subdirectory and per-step filename suffix for out_app_flag=2

The band output did not honor out_app_flag=2: the filename never received
a g{step} suffix and always wrote into global_out_dir, so multi-step runs
(MD/relax) would overwrite bands1.txt / bands2.txt and only keep the last
step.

Changes:
- Add global_band_dir to System_para, mapped to OUT/<suffix>/BANDS/ in mode 2
  and falling back to global_out_dir otherwise; includes MPI broadcast.
- write_bands: use global_band_dir as the output directory, add g{istep+1}
  suffix when out_app_flag==2, and lazily ensure the BANDS/ directory exists.
- Tests: sync io_sys_var_test directory assertions and test_write_bands
  TestParameters with the new global_band_dir.

Verified: MODULE_IO_write_bands (10/10), MODULE_IO_system_variable_test pass;
esolver builds cleanly; governance check has no new blockers.

* Unify ionic step label to "Ionic_Step" across all output files.

Replace the legacy "RELAX STEP" keyword and pre-existing inconsistent
"Ionic Step" (with space) occurrences with "Ionic_Step" (underscore) to
match the established convention already used by write_cube.cpp and
related integration-test fixtures.

Production code:
- source_relax/relax_stru_io.cpp: STRU file provenance header
- source_io/module_output/print_info.cpp: stdout/ofs_running run logs
- source_io/module_hs/vxc_op_tools.cpp: eband decomposition energy header
- source_pw/module_pwdft/dftu_base_io.cpp: DFTU occ_mat provenance header
- source_io/module_dm/write_dmk.cpp: DM(k) frame header (historical)
- source_io/module_dm/write_dmr.cpp: DM(R) CSR frame header (historical)
- source_io/module_hs/hsr_writer.cpp: H(R)/S(R) CSR frame header (historical)
- source_io/module_mulliken/output_mulliken.cpp: Mulliken output frame header (historical)

Tests:
- source_relax/unittests/test_relax_stru_io.cpp
- source_io/unittests/test_print_info.cpp
- source_io/module_dm/test/write_dmk_test.cpp
- source_io/module_dm/test/test_write_dmr.cpp
- source_io/module_hs/unittests/test_hsr_writer.cpp

Comments / doc strings:
- source_base/module_out/csr_reader.h: CSR format example
- source_io/module_parameter/read_inp_out.cpp: out_stru parameter description

Verification:
- make -j 30 -> 100%
- ctest -R "(RELAX_relax_stru_io|IO_print_info|IO_vxc_op_tools|PW_dftu_base|
  IO_mulliken|IO_write_dmk|IO_write_dmr|IO_hsr_writer)" -> 10/10 PASSED
- grep -rn "RELAX STEP" / "Ionic Step " -> zero matches in source tree

* Unify IONIC STEP to Ionic_Step in WFC and band output headers.

Production code:
- source_io/module_wf/write_wfc_nao.cpp: wf{ki}s{spin}_nao.txt provenance header
- source_io/module_energy/write_bands.cpp: band eigenvalue provenance header

Tests:
- source_io/unittests/test_write_wfc_nao.cpp
- source_io/unittests/test_read_wfc_nao.cpp
- source_io/unittests/test_write_bands.cpp

Verification:
- make -j 30 -> 100%
- ctest -R "(IO_write_wfc_nao|IO_read_wfc_nao|IO_write_bands|
  RELAX_relax_stru_io|IO_print_info)" -> 8/8 PASSED
- grep -rn "RELAX STEP\|Ionic Step \|IONIC STEP" -> zero matches

* unify ionic step header keyword to Ionic_Step in DOS/eig_occ/HS outputs

Three source output files wrote "# ionic step" (or "X # ionic step") in
their per-ionic-step header comments, while STRU and cube outputs already
use "Ionic_Step". Rename to the unified keyword across:
- cal_dos.cpp      -> "X    # Ionic_Step" (doss*.txt / pdoss*.txt)
- write_eig_occ.cpp -> "X     # Ionic_Step" (eig_occ.txt)
- hs_dense_io.cpp  -> "# Ionic_Step X"  (HS dense matrix)

Sync test assertions and INPUT parameter description accordingly.
Also refines the INPUT file under examples/17_relax/04_relax_with_output_lcao
with end-of-line filename comments for each enabled out_* parameter.

* Fix hs_dense_io test assertions for Ionic_Step keyword sync.

The prior commit 40387962a unified "# ionic step" to "# Ionic_Step" in
hs_dense_io.cpp but missed test_hs_dense_io.cpp, causing TextHeaderContains
StepAndDimension and TextHeaderStepTwo to fail. Sync the EXPECT_NE find()
strings and a nearby comment.

Verification: MODULE_IO_hs_dense_io_test -> 11/11 PASSED.

* unify CSR sparse-matrix step header from "STEP: N" to "Ionic_Step N"

Three writers produced per-frame headers as "STEP: N" or "IONIC_STEP: N":
- pos_op_csr.cpp       (rr_nao.csr, rx_nao.csr, ...)
- hs_sparse_io.cpp     (hrs*.csr, srg*.csr, trs*.csr, ...)
- dhs_sparse_writer.cpp (dhrx*.csr, dsrx*.csr, ...)
- overlap.cpp          (S_async(R) overlap)

Rename to "Ionic_Step N" (keyword-first, no colon) to match STRU cube,
doss, eig_occ, and HS dense-matrix headers unified in the previous commit.

Sync test assertions, fixture SR.csr, and comments accordingly.

* Unify "# istep:" to "# Ionic_Step" in PDOS text output.

PDOS text output (write_pdos_text.cpp) used "# istep:" as its per-step
header keyword while all other outputs had already been unified to
"Ionic_Step". This was the last remaining non-Ionic_Step keyword in
production output.

Production code:
- source_io/module_dos/write_pdos_text.cpp

Tests:
- source_io/module_dos/unittests/test_write_pdos_text.cpp (5 assertions)

Docs:
- docs/advanced/elec_properties/dos.md (PDOS format example and description)

Verification:
- make -j 30 -> 100%
- MODULE_DOS_write_pdos_text -> 5/5 PASSED

* sync test reference headers with Ionic_Step keyword in HS matrix outputs

hs_dense_io.cpp writes "# Ionic_Step N" since the keyword unification, but
the hk/sk/vxc/dH reference files still contained "# ionic step". CompareFile.py
compares comment lines token by token, so those matrix comparisons would fail.
Update 31 references under tests/; value data is unchanged.

* Correct out_mat_r output filename documentation

out_mat_r writes a single rr_nao.txt (or MAT/rrg{step}_nao.txt when
out_app_flag = 2) rather than separate rxrs/ryrs/rzrs CSR files. Update
the INPUT description, the position-matrix guide, and the example INPUT
comment, and align the documented frame header with the emitted
Ionic_Step keyword.

* refactor(io): disambiguate cube channel suffixes from real spin indices

Tensor quantities (sigma, vsigma, v2rho2, v2rhosigma, v2sigma2, v3rho3,
v3rho2sigma, v3rhosigma2, v3sigma3, v4rho4, v4rho3sigma, v4rho2sigma2,
v4rhosigma3, v4sigma4) previously used _s1/_s2/_s3 suffixes that collide
with the real spin-index convention used by rho and vrho.  Replace them
with explicit Libxc-channel index tuples (_00, _01, _11 for 3-channel
tensors, etc.).  Scalar quantities (exc, amag) no longer carry a
redundant _s1 suffix.  Rho and vrho keep _sN since those map to actual
spin indices.  A set of small helper lambdas generates the suffix lists
so the channel ordering stays consistent with Libxc throughout.

* Rename Vxc(R) sparse output to vxcrs{spin}_nao.csr

Follow the repository NAO sparse-matrix naming convention: one-based
spin index, "_nao.csr" suffix, and the g{step} suffix plus append
behavior driven by out_app_flag in mode 2. Pass the ionic step and
out_app_flag explicitly into write_Vxc_R instead of hard-coding
istep = -1. Update the out_mat_xc2 help text, the example INPUT
comment, and the scf_out_hxc reference fixture (including its
Ionic_Step header).

* sync remaining .ref fixtures with Ionic_Step keyword

The earlier commit 91465ba91 updated 31 .txt.ref files under tests/ for
the Ionic_Step unification, but left .csr.ref, rr_nao.txt.ref,
mulliken.txt.ref and cube.ref fixtures still carrying the legacy
"--- Ionic Step N ---", "STEP: N" or "IONIC_STEP: N" headers.
CompareFile.py does a token-by-token compare and those mismatches cause
the integrating tests (md_out_hk_syns, scf_out_hk_spin2, scf_out_mul,
scf_out_mul_spin2, ...) to fail. Update 41 remaining reference files
under tests/02_NAO_Gamma/ and tests/03_NAO_multik/ to the new unified
"Ionic_Step N" keyword. Data values are untouched.

* fix(ASE): accept Ionic_Step header when counting eig_occ frames

The eig_occ.txt per-ionic-step header was unified from "X     # ionic
step" to "X     # Ionic_Step", but the ASE reader still counted frames
with endswith('# ionic step'), yielding nframe = 0 and failing the
assertion len(ik) == nframe * nspin * nk in read_band_from_eig_occ.

Match the header with a case-insensitive regex that accepts both the
old and the new spelling, and sync the nspin4-gamma-eigocc fixture to
the current format.

* fix(io): pass band output directory explicitly to write_bands

The out_band BANDS/ change read PARAM.globalv.global_band_dir inside
write_bands, which pushed the PR over the global dependency budget
(added=4, removed=3, net_delta=1) and blocked CI.

Resolve the directory once in ESolver_KS::after_scf and pass it as an
explicit argument, following the existing write_eig_file /
output_mat_sparse convention. This keeps the band writer free of PARAM
and brings the PR-wide delta to zero.

Verified: MODULE_IO_write_bands 2/2 passed; abacus_basic_para target
builds; governance diff counting gives net_delta=0.

* fix(test): make hsr_writer tests MPI-safe for multi-rank launches

The non-MPI-specific tests in test_hsr_writer.cpp performed file I/O
on all MPI ranks simultaneously, causing file corruption and race
conditions when the test binary was launched with mpirun -np 2.

- For the 7 tests that call the non-collective write_hcontainer_csr /
  write_hcontainer_csr_binary directly, add an early return on
  non-zero ranks so only rank 0 writes/reads/removes the files.
- For WriteHsrTextCsrCarriesPerSpinFermiFromEfermi, keep the collective
  write_hsr call (which internally uses gatherParallels) on all ranks,
  but guard the file read-back, assertions, and cleanup to rank 0 only.

Verified: single-process (21 passed, 1 skipped) and mpirun -np 2
(22 passed on both ranks), plus ctest serial+parallel both pass.

* fix(io): rename MO-basis Vxc matrix to vxcmo to avoid vxck collision

The MO-basis Vxc matrix written by out_mat_xc reused the "vxc" property,
which resolved to the same vxck{ik}s{spin}_nao.txt filename as the
NAO-basis matrix from out_mat_vxck; with out_app_flag 0/1 the later
writer silently overwrote the former. Give the MO-basis matrix its own
"vxcmo" property and pass the real ionic step and out_app_flag into
write_Vxc instead of locally shadowed constants, which restores the
one-based Ionic_Step header and the mode-2 g{step} suffix. Update the
two integration fixtures and props_mat.sh accordingly.

* fix(io): make out_mat_xc2 a final-step snapshot without g suffix

write_Vxc_R is called from ctrl_runner_lcao, which runs once at the end
of the whole calculation, so out_app_flag=2 only ever produced a single
vxcrs{spin}g{N}_nao.csr file. Drop the per-step suffix and always
truncate, matching the documented vxcrs{spin}_nao.csr name, and remove
the now unused out_app_flag parameter.

* fix(io): write spin-independent H terms once with correct spin labels

write_h_term looped both spin channels while write_hk_common enumerated
only the spin-up k indices, so Vnl(k)/Vl(k)/Vh(k) were written twice
into s1 files, and Vxc(k), which is spin dependent, placed both channels
in the same s1 file. Enumerate the local k points of each spin through
K_Vectors::isk as write_hsk does, pass nspin=1 to filename_output for
spin-independent terms so they carry no spin suffix, and apply the same
enumeration to the EXX writer and to T(k).

* fix(io): add one-based Ionic_Step marker to Lx/Ly/Lz matrix output

Emit the column header only once per file and stamp each frame with
"# Ionic_Step <1-based step>" so the angular-momentum matrices match the
step labelling of the other matrix outputs. Appending frames no longer
repeats the full header.

* fix(io): honor out_app_flag for mulliken.txt output

Mode 0 previously kept every written frame and mode 2 ignored the step
number. Open the file per the selected mode: overwrite for mode 0, append
after the first step for mode 1, and write mullikeng{step}.txt in mode 2.

* fix(io): honor out_app_flag and out_freq_ion for eig_occ.txt

write_eig_file always appended after the first step and ignored the ionic
output frequency, so mode 0 kept every frame and mode 2 had no step suffix.
Gate the write by out_freq_ion and open the file per out_app_flag: overwrite
in mode 0, append after the first step in mode 1, and write eig_occg{step}.txt
in mode 2.

* fix(io): write band outputs on the out_freq_ion rhythm

out_band was dumped on every ionic step regardless of out_freq_ion, so a
run with out_freq_ion = 2 produced five band frames while the other
step-scoped outputs produced three. Gate write_bands with the same
frequency used by eig_occ.txt; a non-positive frequency still writes
every step.

* fix(io): write eband outputs on the out_freq_ion rhythm

The band-decomposed energy files were emitted only from ctrl_runner_lcao,
which runs once at the end, so a multi-step run produced a single frame and
mode 2 had no step suffix. Move the write_Vxc/write_eband_terms calls to
ctrl_scf_lcao and honour out_app_flag in the file name and open mode:
mode 0 overwrites, mode 1 appends after the first step, mode 2 writes
eband_*g{step}.txt. The CMake-listed signature of ctrl_scf_lcao now takes a
non-const Structure_Factor because the potential builders need its address.

* fix(io): number projected-band XML files per step and annotate the frame

The pbands{spin}.xml files ignored out_app_flag, so mode 2 produced the
same fixed name as the other modes, and the document carried no ionic-step
annotation. Write pbands{spin}g{step}.xml in mode 2 (XML cannot be appended,
so mode 1 keeps overwriting the fixed name) and add an Ionic_Step XML
comment that parsers ignore.

* fix(io): route xc(r) cubes through CHG/ and out_app_flag

out_xc_r wrote xc_*.cube files into the output root with a fixed name in
every mode. Build the name from the charge-density directory (CHG/ in
mode 2, matching the other cube writers) and apply out_app_flag: append
after the first written step in mode 1 and append g{step} in mode 2.

* fix(io): unify scalar-text ionic-step markers as "# Ionic_Step N"

mulliken used " --- Ionic_Step N ---" and doss used "N    # Ionic_Step",
so the same ionic step was annotated in two more shapes. Both now emit the
"# Ionic_Step N" comment line already used by bands, pdos and the eband
files, which also lets comment-aware plotters skip the line. eig_occ keeps
its "N     # Ionic_Step" form because
interfaces/ASE_interface/abacuslite/io/latestio.py parses exactly that
pattern.

* fix(io): use the bare "Ionic_Step N" marker for CSR and real-space matrices

hcontainer CSR, dmk and dmr files prefixed the step with
" --- Ionic_Step N ---" while the other sparse writers already used
"Ionic_Step N". Emit the bare spelling everywhere and teach csrFileReader
to also accept the old wrapped spelling (and the older "Ionic Step N"
form) so restart files written before this change stay readable.

* docs(example): align relax/output INPUT comments with actual products

Several comments still advertised the pre-fix naming: out_mat_xc pointed
at the eband files, out_eband omitted kin/vl/vnl/hart, vnlk/vlk/vhk/tk
still showed a spin suffix, out_mat_xc2 was not marked as a final
snapshot, out_xc_r missed the CHG/ directory, and mulliken/band/dos/
proj-band/out_stru did not spell out the out_app_flag mode behaviour.
Comment-only change; no input value is touched.

* fix(io): add spin and step suffixes to the k-space dH matrix names

dH(k)/dT(k)/d*V(k) files were named with neither the spin channel nor the
ionic step, so nspin=2 wrote both spins to one file and out_app_flag=2
overwrote the same fixed name on every step. Mirror the other MAT outputs:
append s{spin} for nspin=2 and g{step} for mode 2.

* fix(io): report the real ionic step in the LDOS cube header

cal_ldos_lcao passed a hard-coded 0 as the iteration to write_vdata_palgrid,
so the LDOS cube always claimed "Ionic_Step 1" even though it is written once
by after_all_runners for the final step. Thread the runner's ionic step through
the writer instead.

* fix(io): write a valid cube header for the out_xc_r files

The libxc files contained only the raw grid values, so they were not
readable as Gaussian cube files and appended frames had no separator.
Reuse the regular cube header (Ionic_Step line, grid geometry and atom
list) before the data block; mode 1 now appends complete frames.

* docs(input): describe the final-snapshot and cube-header behaviour

Sync the INPUT reference and the relax example comments with the recent
output changes: out_ldos and out_proj_band are written once for the final
ionic step, out_xc_r files now carry a full cube header including the
one-based ionic step, and out_mat_dh/k-space naming replaces the stale
dH(R) description.

* fix(io): report the real ionic step in the partial-charge cube header

Get_pchg_lcao passed a hard-coded 0 as the iteration to write_vdata_palgrid,
so every pchg cube claimed "Ionic_Step 1". Thread the runner's ionic step
through begin_gamma/begin_k.

* fix(io): report the real ionic step in the PW LDOS / STM cube headers

cal_ldos_pw (and its ldos_mode_pw / stm_mode_pw helpers) passed a hard-coded
0 as the iteration to write_vdata_palgrid, so every PW cube claimed
"Ionic_Step 1". Store the last ionic step in ESolver_KS_PW and thread it
through ctrl_runner_pw down to the cube writer.

* fix(test): align MO-basis Vxc references with 1-based ionic step

The ionic step in matrix output headers is now 1-based, but the
vxcmo_nao.txt and vxcmok2_nao.txt references still carried Ionic_Step 0,
so scf_out_hxc (02_NAO_Gamma) and scf_out_xc_multik (08_RI) failed
during property validation.

Verified with build_max_para_test: both categories pass
(02_NAO_Gamma 28s, 08_RI 24s).

* docs(example): document output layout convention for out_app_flag modes

Add a layout convention block to the 04_relax_with_output_lcao INPUT so
the SUB/ prefixes and g{step} suffixes are understood as mode-2 behaviour,
with mode 0 truncating and mode 1 appending fixed files in OUT.${suffix}.

Also correct the out_stru, out_elf, out_mat_ds and out_mat_t descriptions
so they match the produced file names, and switch the example to
out_app_flag=0.

* fix(io): match Libxc mixed-derivative labels to packing order

The cube channel suffixes for v2rhosigma, v3rho2sigma, v4rho3sigma, and
v4rho2sigma2 were labeled with the sigma index before the rho index, but
Libxc packs these arrays with rho as the leading (slow) index.  Correct
the labels so the filenames identify the right derivative component.

Also fix the v4rho2sigma2 allocation for polarized GGA: Libxc expects
3*6 = 18 channels, not 15.

Reported-by: ABACUS-PR-BOT <342302420+ABACUS-PR-BOT@users.noreply.github.com>

* test(io): pin sparse writer truncation for final-snapshot outputs

Add a test that seeds a stale CSR file and then calls save_sparse with
out_app_flag = 0 and istep > 0, verifying the file is truncated rather
than appended.  This covers the fix in write_Vxc_R where a fresh rerun
must not append to the previous calculation's vxcrs*_nao.csr.

Reported-by: ABACUS-PR-BOT <342302420+ABACUS-PR-BOT@users.noreply.github.com>

* fix(ase): discover eig_occ files for all out_app_flag modes

read_abacus_out() previously hard-coded eig_occ.txt, which fails when
out_app_flag = 2 writes one eig_occg{N}.txt per step.  Add
find_eig_occ_files() to discover either the single merged file or the
numbered series, and read_band_from_eig_occ_files() to parse them into
a frame list.

When out_freq_ion > 1 writes fewer eigenvalue frames than trajectory
frames, reuse the last available eigenvalue frame for the skipped steps
so the existing length assertion still passes.

Add tests covering:
- file discovery for mode 0/1 (single file) and mode 2 (numbered files)
- multi-file parsing by splitting a fixture into per-step files
- the updated read_abacus_out mock chain

Reported-by: ABACUS-PR-BOT <342302420+ABACUS-PR-BOT@users.noreply.github.com>

* refactor(io): pass out_app_flag to nscf_bands explicitly

nscf_bands previously read PARAM.inp.out_app_flag directly, violating
the rule that workflow switches should not hide in mutable globals.
Pass the value through from write_bands, which already receives the
Input_para snapshot.

Update the test fixture to set input_.out_app_flag explicitly when
exercising the append path, since the writer now uses the passed-in
value instead of the global PARAM.

Reported-by: ABACUS-PR-BOT <342302420+ABACUS-PR-BOT@users.noreply.github.com>

* fix(io): correct v4rho3sigma channel labels

Use the three-density rho groups 000, 001, 011 and 111 with the sigma
pair, matching Libxc's ordered tuples. The unpolarized suffix becomes
000_00 instead of the extra density index in 0000_00.

* fix(io): append MO Vxc matrices in mode 1

write_Vxc now runs at every selected ionic step, so always truncating
the fixed vxcmo file dropped earlier frames. Append after the first
step in mode 1 while keeping single-snapshot mode 0 and per-step mode 2.

* test(io): capture process rank once in hsr writer tests

The writer tests guarded each file I/O case with GlobalV::MY_RANK. Read the
rank once in main instead and reuse it, keeping the global only as the
value consumed by the writers themselves.

* test(io): cover mode-2 band snapshots in BANDS/

Let the band output tests use a band directory separate from global_out_dir
and check that mode 2 creates BANDS/ lazily, keeps one numbered file per
written step, and does not overwrite an earlier snapshot.

* test(io): write eig_occ test files to testing::TempDir()

Keep the writer test from leaving eig_occ artifacts in the working directory.

* test(io): write sparse H/S test file to testing::TempDir()

Keep the seeded-file test from polluting the working directory.

* docs(input): document band, Vxc and xc_r output naming

Describe the current band file names and the BANDS/ routing in mode 2, the
per-step vxcmok{ik}s{spin} matrices under MAT/, the g{step} eband files, the
Libxc tensor component suffixes of out_xc_r, and correct the final-snapshot
note in the relax example.

* fix(io): make dS/dR sparse output spin-independent

cal_dS fills only the spin-0 channel, so nspin=2 used to produce an
all-zero dS/dR spin-down file whose header still claimed the full R
block count. Restrict the writer's spin loop to dH/dR only, and label
the running log without a spin channel for the overlap derivative.

* refactor(io): drop spin suffix from dS/dR sparse output names

Since dS/dR is spin-independent, its files are now dsrx_nao.csr,
dsry_nao.csr and dsrz_nao.csr (dsrxg{step}_nao.csr in mode 2) instead
of dsrxs{spin}_nao.csr. dH/dR keeps its collinear spin index. Update
the INPUT item description and the unit-test cleanup helper accordingly.

* refactor(io): write dH/dR and dS/dR in the H(R)/S(R) CSR layout

Replace the terse two-line header of the derivative sparse output with
the self-describing H(R)/S(R) layout: ionic step, matrix label, spin
count and spin index, basis size and R count, the user_defined_lattice
cell block, the CSR banner, and per-R blocks whose values wrap every
six entries. Empty text blocks now carry all three CSR sections instead
of being skipped; binary records are unchanged. The density-derivative
unit is corrected to 1/Bohr, and save_dH_sparse takes the UnitCell so
the header can describe the cell. Update the unit tests and the dH
reference files accordingly.

* refactor(io): split r(R) sparse output into per-axis CSR files

The position-operator matrix was written as a single rr_nao.txt holding
all three Cartesian components in one stream. Split it into
rrx/rry/rrz_nao.csr, matching the dH/dS .csr family, so each component
can be read and validated independently. Share the CSR text writer
between dH/dS and r(R), and keep the binary layout consistent.

Link ucell_io.cpp into the deepks and tddft test targets, which compile
pos_op_csr.cpp directly and previously missed the new UcellIO::write_ucell
dependency.

* feat(io): align tr_nao.csr with the self-describing CSR layout

The kinetic-energy matrix T(R) was written with the legacy compact
header (dimension and R-count lines only), and its blocks carried no CSR
annotations. Give it the same text layout as the H(R)/S(R) CSR files:
ionic step, spin count/index, basis size, R count, unit cell block,
CSR banner, and annotated CSR blocks. Binary output keeps the compact
record layout so existing readers are unaffected.

Expose the layout through SparseWriteOptions (csr_format plus the unit
cell) instead of a separate writer, so rank gating and threshold logic
stay in one place and no new global dependencies are introduced.

* feat(io): write angular-momentum matrices in the self-describing CSR layout

Replace the 13-column long-table lx/ly/lz_nao.txt output with
lx/ly/lz_nao.csr, using the same header, cell information and CSR
block layout as the H(R)/S(R) files. Values are indexed by the global
NAO orbital indices obtained from ucell.itiaiw2iwt.

Because the NAO basis is real, every <phi_i|L|phi_j> element is purely
imaginary (L = -i r x grad), so only the imaginary part is stored; the
real part is identically zero. This halves the file size compared with
a complex CSR and loses no information.

The output is rejected for nspin = 4, where npol = 2 doubles the orbital
dimension and the scalar CSR writer would produce a mismatched matrix.

Tests: MODULE_IO 67/67 pass, including a new complex-CSR writer test;
the L matrices match the previous long-table reference element by
element (lx/ly 24316 entries, lz 21664, real parts all zero).

* feat(io): add per-frame provenance headers to ionic-step outputs

Text outputs now carry "# ABACUS version" and "# Written at" lines per
frame and use the unified "# Ionic_Step N" marker. Cube comments inline
the provenance on the first line to avoid breaking the two-line header,
and CSR writers append it to the existing step line while keeping the
marker at the line start, so csr_reader needs no change. The integration
comparator ignores provenance and canonicalizes old/new step markers.

* Align H(k)/S(k) text output format with write_dmk

write_hsk text output previously delegated to save_mat, which produced
a banner-style header with Row N markers and no structural metadata
(k-point index, coordinates, weight, Fermi energy, basis count or
UnitCell lattice block). This made hk1s1_nao.txt structurally very
different from dmk1s1_nao.txt that sits next to it.

The text path now writes the exact same frame layout as write_dmk:
  Ionic_Step N (1-based)
  Full metadata block (nspin, spin index, k counts, ik, Cartesian and
    direct k-point coordinates, k weight, Fermi energy, nbasis, dim)
  UnitCell lattice block via UcellIO::write_ucell
  Flat matrix body with 4 complex / 8 double values per line

Binary output (out_type == 2) keeps the save_mat .dat layout unchanged
so downstream post-processing scripts that consume binary files are not
affected. The filename convention for text hk files also switches from
filename_output (which appended a .dat suffix) to the same dmk_gen_fname
pattern: hk1s1_nao.txt, hk1s1g5_nao.txt, etc.

Changes:
  - hsk_writer.h: add K_Vectors&, UnitCell*, vector<double>& efs params
  - hsk_writer.cpp: rewrite text path; retain save_mat binary path
  - ctrl_scf_lcao.cpp: pass kv, ucell and efermis into write_hsk
  - test_hsk_writer.cpp: adapt new signature (binary tests unchanged)
  - unittests/CMakeLists.txt: add symmetry + explicit source_cell deps

* Fix text hk filename k-index and prefix

Two bugs in the write_hsk text-path filename generator:

1. The property prefix was "hk"/"sk" but make_fname itself appends a
   "k<index>" segment, producing doubled prefixes like "hkk1s1_nao.txt".
   Switch to "h"/"s" for the text path while keeping "hk"/"sk" for the
   binary path (filename_output owns its own suffix scheme).

2. The k index was the global k-spin pair index (0..nkstot-1), which
   differs between spin channels for the same physical IBZ k-point.
   Use `ibz_ik = ik - ispin * nkstot_nospin` so that hk1s1_nao.txt and
   hk1s2_nao.txt refer to the same IBZ k-point, matching dmk1s1_nao.txt
   and dmk1s2_nao.txt naming.

Metadata k-point index and kvec_c/kvec_d/wk subscripts use ibz_ik too.
Binary output is unaffected (filename_output + save_mat unchanged).

* Update integration-test refs for new H(k)/S(k) text format

The write_hsk text output was reformatted in the preceding two
commits to match write_dmk's convention (metadata block + UnitCell
lattice + full-matrix body, with IBZ k-point indexing and shortened
property prefix "h"/"s").  Refresh every affected .ref file and the
hard-coded filenames in props_mat.sh.

gamma_only layout — property prefix dropped "k":
  hk_nao.txt  -> h_nao.txt   (Hamiltonian, nspin=1)
  sk_nao.txt  -> s_nao.txt   (overlap, nspin=1)
  hks1/hks2   -> hs1/hs2     (Hamiltonian, nspin=2)
  sk_nao.txt  -> ss1_nao.txt (overlap, nspin=2, only spin-up written)

Multi-k-point layout unchanged (property "h"/"s" + "k<ibz_ik>" yields
the same hk2/sk2 filenames the old code produced via filename_output
with the global k-spin index).  Only the matrix body content changes
(upper-triangle -> full matrix), so hk2_nao.txt.ref / sk2_nao.txt.ref
are updated in place.

props_mat.sh gamma_only branches updated to the new filenames
(both text-compare and binary-compare paths).  Multi-k-point branches
need no change.

* S(k) filename: drop redundant spin suffix

S(k) is spin-independent — write_hsk skips all spin-down channels
and only produces one S(k) copy per IBZ k-point.  The previous
text-path naming still appended "s1" when nspin == 2, yielding
redundant filenames like ss1_nao.txt (gamma-only) or sk1s1_nao.txt
(multi-k-point, hypothetical but consistent with the buggy branch).

Add a `spin_suffix` parameter to make_fname so that S(k) passes
false and never appends "s<N>".  H(k) continues to append spin
suffixes exactly when nspin == 2.

  nspin=1, gamma_only:   s_nao.txt      (unchanged)
  nspin=2, gamma_only:   s_nao.txt      (was ss1_nao.txt)
  nspin=1, multi-k:      sk1_nao.txt    (unchanged)
  nspin=2, multi-k:      sk1_nao.txt    (was sk1s1_nao.txt, had no test)

Update the three nspin=2 gamma_only S(k) refs and props_mat.sh
accordingly.  Binary output is unaffected.

* Fix ibz_ik formula for symmetry-reduced k-point lists

After symmetry reduction K_Vectors::nkstot holds the IBZ k-point
count (doubled for spin-polarised runs), while nkstot_nospin stays
at the original MP-mesh size.  The previous text-path formula

    ibz_ik = ik - ispin * nkstot_nospin

therefore produced negative indices whenever symmetry was active
together with nspin == 2, e.g. a 2x2x2 mesh reduced to 3 IBZ k
points yields nkstot=6 but nkstot_nospin=8, so ik=3 under ispin=1
gave ibz_ik = -5.  The filenames hk-2s2_nao.txt etc. and their
metadata (negative k-point index, garbage kvec coordinates read
out-of-bounds) were symptoms of this.

Replace with

    ibz_k_count = nkstot / nspin
    ibz_ik      = ik - ispin * ibz_k_count

which matches how set_kup_and_kdw doubles nkstot: ispin==0 owns
ik in [0, ibz_k_count), ispin==1 owns [ibz_k_count, nkstot).

Verified with the nspin=2 + symmetry case in
examples/17_relax/04_relax_with_output_lcao: the filenames are now
hk1s1/hk1s2 ... hk3s1/hk3s2 and their metadata exactly aligns with
the sibling dmk1s1/dmk1s2 ... dmk3s1/dmk3s2 files — same IBZ k
index, same Cartesian/direct coordinates, same weight.  No
integration-test refs need updating because all current hk
test cases are either gamma_only or nspin=1.

* Align T(k) text output format with write_dmk / write_hsk

The kinetic matrix T(k) (out_mat_tk) previously followed the generic
save_mat layout: single-line banner, per-row "Row N" markers, and an
upper-triangular matrix body.  This changes ctrl_scf_lcao's tk block
to emit the same flat format used by write_dmk and write_hsk:

  * header: Ionic_Step N + full metadata block (nspin, spin index,
    total IBZ k-point counts, k-point index with Cartesian / direct
    coordinates, weight, 0.0 Fermi placeholder with a "(not applicable
    to T(k))" comment, nbasis, dim)
  * UnitCell lattice block via ModuleIO::UcellIO::write_ucell
  * full-matrix body: flat layout, 8 double / 4 complex per line, no
    row markers

Implementation notes:

  * T(k) is spin-independent (same convention as S(k)) so the filename
    carries no spin suffix; gamma_only drops "k", multi-k keeps "k"
    (t_nao.txt vs tk1_nao.txt), matching the h_/hk_ pattern for H(k).
  * MPI: gather the distributed matrix to rank 0 with Cpxgemr2d<TK>
    using a BlockCyclicDistribution descriptor identical to the one
    write_hsk uses.  Rank 0 alone writes the file.
  * Binary .dat output is not affected — this commit only rewrites the
    text path.

A small write_matrix_body_flat helper (with tag dispatch on
std::is_same<T, double>) avoids type-checked dead branches under
C++11 when TK is actually std::complex<double>.

No integration-test refs need updating because no test case currently
enables out_mat_tk.

* Align Hamiltonian-term H(k) text output with write_dmk / write_hsk

vhk / vlk / vnlk / vxck / vexxk were written through save_mat, which
emitted a separator banner plus per-row "Row N" markers and no k-point
metadata or UnitCell block.  In addition, save_mat was handed a
full-size folded matrix but indexed it with the block-cyclic local
offsets, so the values written were wrong even for a serial run (and
differed between serial and MPI runs).

Rewrite write_hk_at_k to fold the term and write it directly in the
same text layout used by write_dmk / write_hsk:

  * header: Ionic_Step N followed by the metadata block (nspin, spin
    index, nkstot_nospin, nkstot, IBZ k index, Cartesian / direct
    k coordinates, weight, a "0.0 # ... (not applicable to <term>)"
    Fermi placeholder, nbasis, dim)
  * UnitCell lattice block via ModuleIO::UcellIO::write_ucell
  * flat matrix body: 8 real values per line for gamma_only, 4 complex
    values per line otherwise, with a 1e-16 zero threshold

For MPI the distributed HContainer is first gathered onto the writing
rank with gatherParallels (same convention as the H(R) writer) so that
the folded matrix is complete and matches the serial result.  Only the
writing rank folds and writes; the running log no longer prints a spin
tag for the spin-independent terms.

vehicle changes: write_h_exx_impl drops its now-unused ks_solver and
drank parameters, and the now-unused hs_dense_io.h include is removed.

No integration-test references or unit tests cover these files, so no
reference updates are needed.  Verified with the LCAO relax example
(serial and mpirun -np 2): H(k) equals T(k) + V^NL + V^L + V^H + V^XC
to 4e-5, MPI and serial term files agree to 1e-11, gamma_only output
uses the real-valued layout, and out_app_flag=1 appends clean frames.

* Align Vxc(R) CSR output with the H(R) CSR layout

Emit the self-describing header (spin metadata, cell block, CSR banner)
and write an explicit zero block for every R vector of the declared list,
so vxcrs{spin}_nao.csr matches hrs{spin}_nao.csr. Route the out_mat_xc2
precision into the writer instead of the hard-coded default, and update
the affected reference files.

* Unify running-log file-written notices

Route every "file written" message through shared inline helpers in
module_output/write_notice.h so the verb, preposition, spin label and
quantity name are identical across writers. Canonicalize the matrix names
(H(k), S(k), Vnl(k), Vl(k), Vh(k), Vxc(k)) and drop the manual padding hack
in the S(k) notice.

* Announce remaining LCAO output files in running log

Extend the shared file-written notice to DOS/PDOS, NAO orbital
table, Mulliken population, band-decomposed energies, Vxc(MO),
LCAO wavefunction coefficients, and libxc cube outputs, so every
file written by the LCAO output path is named in the running log.

* Announce structural and run-metadata files in running log

Report INPUT.info, KPT.info, element information, STRU_NOW,
STRU_FINAL and the converged restart files through the shared
file-written notice, and replace the stale STRU_SIMPLE.cif
message with a description of what the code actually did.

* Fix running-log banners, units and cube descriptors

Close the DOS, H(k) and LCAO WFC/pchg banners with '<' as in the
rest of the log, keep the projected-band box width at 71 columns,
correct the Fermi-energy unit to eV in the two-Fermi branch,
capitalize cube descriptors, and fix the Calcualte, unticell and
elments typos.

* Write the NAO orbital table once per run

Keep a single write_orb_info implementation, call it after the LCAO
basis setup, and drop the duplicate CellIndex copy together with its
redundant callers and tests. Also announce the density restart file
when the SCF stops at scf_nmax without converging.

* Drop the duplicated H(k)/S(k) banner

The boxed description repeated the WRITE H(k) OR S(k) heading printed
right below it.

* Wrap the skipped-autoset warning across several log lines

* fix(ase): align eig_occ frames by Ionic_Step ID

The eig_occ writer now emits "# Ionic_Step N" preceded by provenance
lines, but the ASE reader only recognized the older "N # Ionic_Step"
shape.  A freshly written snapshot therefore yielded nframe = 0 and
failed the k-point/frame assertion in read_band_from_eig_occ.

Accept the producer and legacy header spellings case-insensitively and
keep the recorded step ID.  Align eigenvalue frames with trajectory
steps by ID instead of duplicating the last spectrum, leaving skipped
steps without eigenvalues.  Select eig_occ files from the running-log
announcements so stale files in a reused output directory are ignored.
Regenerate the fixture in the current producer shape and cover the
producer/legacy headers, stale-file discovery and skipped-step alignment.

* docs(example): refresh output comments in 04_relax_with_output_lcao INPUT

Document the recent IO changes: per-frame provenance headers, the shared
self-describing layout of the k-space MAT/*.txt matrices, the CSR-based
lx/ly/lz_nao.csr angular-momentum output, the total dH/dR CSR files and
the multi-k _ik suffix of the out_mat_dh family, and the H(R)-style CSR
layout of vxcrs*.csr.

* fix(io): align H(k)/T(k) naming and dense text output contract

Accept the Gamma T(k) property in filename_output and always build it from
"t"; keep MPI ranks in the same collective sequence when an H(k) file cannot
be opened; teach the binary comparator to read the new dense text references;
and document the text/binary filename and traversal differences.

* chore(io): clean reference whitespace and lock T(k) naming

Strip trailing blanks from the refreshed H(k)/S(k) references without
touching their values, remove the stray EOF blank line in cell_index.cpp,
hoist two conditional call arguments into named locals for AGENTS rule 14,
and add a filename test covering the gamma-only and multi-k T(k) names.

* test(io): cover dense H(k) text output and isolate dS/dR artifacts

Add a text-mode WriteHsk case that checks row-major order, signed imaginary
parts, filenames and append records; it skips under MPI because the 1x1 block
distribution leaves off-diagonal elements unowned. Move the dS/dR sparse case
into testing::TempDir() per AGENTS rule 17.

* CI: add paths-ignore to non-required-check workflows

Only cuda.yml, pytest.yml and ase_plugin_test.yml are filtered. The three
heavy workflows that produce branch-protection-required checks
(build_test_cmake.yml, build_test_makefile.yml, test.yml) are left
untouched, so docs-only PRs still pass required checks and can be merged.

* test(io): parse DOS grid size past the provenance header

DosPWTest.Dos2 assumed the DOS file started with a one-line
"# ionic step" marker, but cal_dos now emits the three-line
provenance block (version, timestamp, "# Ionic_Step N") via
prov_step(). Scan for the "# number of points" line instead of
relying on fixed line offsets, so the data-row checks start on
the first numeric grid line again.

* fix(io): report H(R) term output only after a successful write

write_hcontainer_csr() silently ignored stream failures: the
ofstream destructor swallowed a failed flush (e.g. disk full), and
gather_and_write() announced "Write H(R) (X term) matrix ..." even
when the record was not written.

Return a bool from write_hcontainer_csr() (true only when the stream
is good after close()) and gate the H(R) notice on it, mirroring the
write_hk_text() contract used for the H(k) path. Extend the CSR
header test to assert the success return value.

* fix(io): write H(k)/S(k) text bodies in row-major order

genelpa/elpa/scalapack_gvx store the local block column-major and the
Cpxgemr2d serial destination keeps that layout, so reading
mat[i*nlocal+j] emitted the transpose of H(k)/S(k). For a Hermitian
H(k) that is the complex conjugate, flipping every imaginary
off-diagonal sign while the documented text format is row-major.

Select the traversal order from the solver storage convention and add
a regression test that distributes a non-symmetric complex probe in
production column-major order.

* fix(io): truncate H(k) term files at the first ionic step

Callers pass append = (out_app_flag == 1) without a step guard, so a
fresh run at istep 0 appended to an existing Vnl/Vl/Vh/Vxc/EXX term
file instead of truncating it. The previous save_mat path truncated the
first step; apply the same istep > 0 check next to open(), covering
both write_h_term and the EXX term path.

* refactor(io): pass rank and log handles explicitly to cut global use

The PR added 46 GlobalV/PARAM references against 32 removed, so the
governance budget failed with a net delta of +14.

Reuse handles that are already in scope instead of reading the globals
again: hoist my_rank/drank in ctrl_scf_lcao, give stru_out and
write_h_exx_impl explicit rank and log parameters, and let the PDOS
text tests write to a fixture stream rather than the global running
log. Net delta is now -13 (added 30, removed 43).

* fix(ase): never fall back to a stale eig_occ.txt for announced runs

find_eig_occ_files() filtered announced paths by existence before
deciding whether the log described the current layout. When a mode-2 run
announced eig_occg{N}.txt files that were later removed, the empty set
fell through to filename discovery and returned an eig_occ.txt left by an
earlier run, silently pairing old bands with the current geometry.

Treat the announcement set as authoritative: keep only the announced
files that exist and skip the fallback whenever the log announced any
eigenvalue output. Filename discovery still applies to logs without such
an announcement.

* chore(io): trim header includes and align output docs with tests

- forward declare K_Vectors/UnitCell in hsk_writer.h and include the
  definitions directly in the writer and its test
- include <iosfwd> instead of <fstream> in eight interfaces that only
  declare std::ofstream&
- write the hsk text test into testing::TempDir() and route the rank
  query through Parallel_Common::comm_size
- document the real sparse thresholds (binary 1e-10, text complex
  1e-16) and label the per-atom matrix as dH(k)/dR_I

* test(io): cover the Vxc(MO) text append contract

The MO Vxc writer delegates its records to save_mat with
append = (out_app_flag == 1) && (istep > 0). Exercise the same call
shape in the dense IO tests: a staled file must be truncated by the
first step of a rerun, and the next step must append in order.

Also hoist the band-decomposed notice strings into named locals so the
call site carries no inline concatenation (AGENTS rule 14).

* test(io): smoke-test the Angmom_op CSR assembly path

The Lx/Ly/Lz kernels (cal_LxijR and friends) had unit tests, but the
assembly layer above them -- orbital block index mapping, the
Grid_Driver neighbor search, and the save_sparse CSR writer -- was
never exercised end-to-end.

Add a smoke test that constructs Angmom_op against a minimal one-atom
Si UnitCell, calls calculate(), and checks that lx_nao.csr, ly_nao.csr
and lz_nao.csr are written with the Ionic_Step provenance line and the
CSR banner.  Numerical assertions on the assembled values follow in a
separate commit so this one stays reviewable.

The new test needs two index helpers that tmp_mocks.cpp previously did
not stub, so add Atom::set_index and UnitCell::set_iat2itia there.

Verified with:
  make -j4 MODULE_IO_angmom_op_mat_test
  ctest -R angmom_op_mat --output-on-failure   -> 1/1 passed
The generated CSR bodies carry the expected l=1 couplings (+-1, +-2,
+-sqrt(3)) plus Ionic_Step 1, so the assembled blocks are non-empty.

* test(io): assert Angmom_op CSR values against the L kernels

The assembly test previously only checked that lx/ly/lz_nao.csr exist and
carry the provenance line.  Parse each CSR block back and compare it entry
by entry with cal_LxijR/cal_LyijR/cal_LzijR evaluated on an independently
tabulated two-center table, so orbital block offsets, the real-harmonic
order 0, +1, -1, ..., the 1e-10 cutoff and the row/column/row-pointer
layout are all covered.

The expected matrix re-derives the offset and m-position mapping from
l_nchi instead of sharing the production helper, so a change of that
mapping shows up as a failure.  A separate anchor checks the l = 1 block
of Lz against the analytic 3x3 matrix documented at the top of the file
(<px|Lz|py> = -i, <py|Lz|px> = +i), independent of the kernel oracle.

Verified with:
  make -j4 MODULE_IO_angmom_op_mat_test
  ctest -R angmom_op_mat --output-on-failure   -> 1/1 passed
Mutation check: flipping the sign of the oracle in expected_l_matrix makes
the comparison fail, so the new assertions are live.

* docs(io): document vxc matrix naming and gate README-only PRs

- spell out the gamma_only and lcao_in_pw variants of the out_mat_xc
  matrix names in the INPUT description
- hoist the Vxc notice strings into named locals (AGENTS rule 14)
- add a lightweight workflow so README/pyproject-only changes still get
  a metadata check when the pytest workflow is skipped

* fix(io): adapt local writers to the Parallel_Blkcyclic rename

Pass the new LCAO_Orbitals argument at the write_eband_terms call site and
switch the remaining local code from BlockCyclicDistribution to
Parallel_Blkcyclic so the upstream merge builds.

* test(io): decouple band dir from the global one and assert shifted spectra

Pass a band directory distinct from PARAM.globalv.global_band_dir so a
regression to the global lookup fails, and verify the second snapshot's
band energies shift by the expected amount instead of only differing in
the Ionic_Step header.

* test(ase): cover the legacy ionic step marker in eig_occ parsing

Run the existing eig_occ fixture through both the current "# Ionic_Step N"
marker and the legacy "N # ionic step" spelling, then compare the parsed
frames, k-points, energies and occupations.

* refactor(io): extract libxc cube channel suffixes and test them

Move the 13 suffix tables out of write_libxc_r into
ModuleIO::libxc_r_channel_suffixes so the channel-to-filename mapping can
be regression-tested for both nspin values without Libxc evaluation.

* refactor(io): centralize the per-step frame append decision

Give write_Vxc a single predicate for its two output paths and lock the
contract with a unit test: mode 1 appends after step 0, while mode 0/2 and
a fresh run (step 0) always truncate.

* fix(io): stop emitting transposed T(k) and DM(k) text bodies

The flat text body of T(k) and DM(k) was read as mat[i * nlocal + j] while
the gathered buffer of a column-major eigensolver keeps the column-major
layout, so the files carried the transpose of the matrix. For a Hermitian
matrix the transpose is the complex conjugate, which flips the sign of
every imaginary off-diagonal element. H(k)/S(k) had already been fixed, so
T(k) and DM(k) have to use the same solver-aware indexing.

Extract the shared body writer into module_hs/dense_text_body, route
H(k)/S(k), T(k) and DM(k) through it, and pass the storage order
explicitly: write_dmk gains a column_major argument instead of reading
PARAM inside the IO layer. Migrate the DM(k) unit test into unittests and
add a column-major probe case, plus a dedicated test for the shared writer.

* fix(io): make DM(k) reading match the written format

read_dmk still expected an outdated three-line header, so it aborted with
"nlocal does not match!" on any file produced by the current writer, and it
distributed the row-major body through Cpxgemr2d as if it were column-major,
which returned the transpose of the matrix.

Parse the header in the order write_dmk emits it and validate nspin, spin
index, k-point and basis size; index the body with the shared column_major
mapping; let dmk_readData report failures instead of aborting; and broadcast
the result through Parallel_Common so every rank leaves cooperatively.

istep and out_app_flag are part of the interface now: mode 2 reads the
g{istep+1} file and checks its frame marker, and mode 1 locates the requested
Ionic_Step frame instead of always taking the first record.

* feat(io): restart LCAO from DM(k) with streaming reads

Read one global block per (spin, k) and redistribute it immediately, so the
peak memory no longer scales with nspin * nk * nlocal^2. The caller's DM(k) is
only replaced after every file has been read, which keeps a failed restart from
mixing old and new matrices.

init_chg=dm now falls back to DM(k) when no DMR CSR file exists, converts it
with cal_dmr and refuses to continue when neither format is usable. The
established DMR restart keeps precedence.

Cover multi-matrix round trip, partial failure, spin/k-point/basis mismatches,
truncated input and the shared layout index in the unit tests.

* fix(io): always persist the final ionic step output

The out_freq_ion gate in ctrl_scf_lcao skipped the final ionic step of an
MD run when it did not fall on the cadence, so eband/DM/H(k) snapshots
stopped one step early compared with the unrestricted writer.

Mark the final ionic step on UnitCell from the MD driver (including the
restart-aware setup path) and let the gate treat it as an output step
regardless of SCF convergence; the step is not duplicated when it already
matches the cadence. Also supplement the final STRU frame after the MD
loop under the same rule. The cadence predicates move to run_md.h as
inline helpers so they can be unit-tested in a dedicated target.

* refactor(io): unify CSR text headers and skip empty R blocks

Sparse text output was persisting every candidate R block, including
all-zero ones, which made T(R)/L(R) files grow with the R grid instead of
the non-zero R set. save_sparse now lists only blocks with values above
the threshold and reports the matching R count in the header.

The self-describing CSR header, R record and append decision were
duplicated across five writers; they now live in hs_sparse_io_detail.h so
H(R), S(R), DM(R), dH/dR, r(R) and the save_sparse outputs cannot diverge.

* refactor(io): use the shared CSR header for S(R) output

output_SR wrote a compact "Matrix Dimension" header while write_hsr wrote
the self-describing CSR header for the same sr_nao.csr file name. Pass the
unit cell explicitly and enable csr_format so both paths emit one layout;
the binary record path is unchanged.

* refactor(io): centralize sparse R-space file naming

Every R-space writer assembled its own "<prefix>[s<spin>][g<step>]_nao"
name, which let the S(R) path drift: output_SR ignored out_app_flag=2 and
always wrote sr_nao.csr into the run directory with step 0.

Add make_sparse_R_filename in the shared detail header and route H(R),
S(R), DM(R), dH/dR, r(R), L(R), T(R) and Vxc(R) through it. output_SR now
takes the ionic step and writes into global_matrix_dir with the mode-2
step suffix; existing names are unchanged.

* docs(input): state that CSR outputs omit empty R blocks

save_sparse now writes only R blocks with elements above the threshold,
but the out_mat_t and out_mat_r descriptions (and the r(R) format note)
still promised one block per candidate R vector. Describe the header
count and block list as the non-empty R set actually written.

* fix(pw): resolve EXX source files in the mode-2 output layout

prepare_exx_nscf assumed a flat directory with fixed file names, so an
SCF run with out_app_flag=2 (eig_occg{step}.txt in the output root and
wavefunctions under PSI/) could not feed the hybrid NSCF. Resolve the
latest written ionic/electronic step, preferring the fixed name so that
modes 0 and 1 keep their existing paths.

* docs(pw): describe EXX source file discovery for hybrid NSCF

State that source files need no renaming: fixed names win, and otherwise
the latest g{step}/e{iter} snapshot is read from the output root and its
PSI/ subdirectory.

* refactor(io): use out_freq_ion as the only output cadence

Remove the RT-TDDFT-only out_freq_td branches from every writer; in RT-TDDFT
istep is already the cumulative electronic step, so the same frequency works.
Keep out_freq_td as a deprecated input alias that is forwarded to out_freq_ion
when the canonical key is not set, and ignore it outside RT-TDDFT.

* fix(io): reject out_mat_l with nspin=4 during input parsing

The CSR angular-momentum writer only fills the scalar real-harmonic block, so
a spinor basis would produce a silently incomplete L(R). Fail in ReadInput
instead of aborting after SCF, document the reason, and keep the writer guard
as a defensive check.

* refactor(io): share the CSR banner between sparse writers and HContainer

Move the duplicated CSR description banner to the lower ModuleIO layer so
Output_HContainer and the R-space sparse writers emit byte-identical text
without a source_hamilt -> source_io dependency.

* perf(io): skip row-wise reductions for empty CSR blocks

The text dH/dR and r(R) writers must keep a zero block for every R counted
in their shared header, but a globally empty component needs no MPI
collective. Write the zero block directly on the owning rank so empty
components no longer pay one allreduce per row, while output stays
byte-identical.

* fix(io): pass real istep to write_Vxc_LIP so # Ionic_Step is 1-based

The local istep_mat=-1 bypassed the zero-based to one-based conversion
in save_mat, producing "# Ionic_Step 0" in vxc matrix headers. Use the
istep parameter directly so the header prints step 1 as intended.

* fix(io): reject non-positive text precision for out_hsk/out_dmk/out_mat_tk

The dense text body writer asserts a positive precision, but the three
INPUT keywords that feed it accepted 0 or negative values and tripped the
assertion during text output. Validate the precision during input parsing
in prepare_input, where the error string is broadcast to every rank before
aborting, and document the positive-integer requirement for each keyword.
Cover the boundary with input-error cases for out_hsk/out_dmk/out_mat_tk.

* docs(input): correct out_mat_xc description for lcao_in_pw output directory

The write_Vxc_LIP caller passes global_mat_dir, so with basis_type =
lcao_in_pw the fixed-name matrices and eband_vxc*.txt files go to the
MAT directory (OUT.${suffix}/MAT/ when out_app_flag = 2), not the root
output directory. Clarify the mode-2 behavior and give concrete file
names for Gamma-only and multi-k cases.

* test(io): cover stale-frame truncation and payload in Vxc(MO) append test

The TextAppendTwoStepsAndFirstStepTruncates test previously deleted the
file before writing, so it never exercised replacing a stale record.
It also only checked step headers, not the matrix values.

Seed a stale frame first, then write a fresh-run step 0 (truncating)
and step 1 (appending). Assert exactly two frames remain, their upper-
triangle payloads match the new matrices, and no stale values survive.

* fix(esolver): create MAT/ before output_SR in get_s mode-2 runs

With calculation=get_s and out_app_flag=2, output_SR opens a .csr file
under global_matrix_dir (MAT/) before any ensure_directory call ran, so
a fresh output directory made the open fail. Create the directory once
before output_SR and drop the now-redundant calls in the out_mat_r and
out_mat_ds branches.

* fix(io): validate stored k coordinates in read_dmk

read_dmk only checked nkstot and the k-point index, so a reordered or
shifted k-mesh of the same size was silently accepted; the init_chg=dm
fallback then folded the stored DM(k) with the current KPT phases and
produced a wrong density. The reader now parses header[6] (kvec_d) and
rejects the file unless the direct coordinates match the running mesh
modulo a reciprocal lattice vector (integer shifts leave e^{ik·R}
unchanged). A same-count mismatch test covers swapped, shifted and
wrapped meshes.

* fix(lcao): broadcast DMR presence decision in init_chg_dm

Rank 0 now probes the DMR CSR files and broadcasts the result to all
ranks, ensuring every rank selects the same communication path (DMR
distribution vs DM(k) broadcast). Previously each rank decided
independently, which could deadlock when file visibility differed
across ranks.

* test(io): use TempDir and assert stream opens in empty-CSR test

Hardcoded /tmp paths ignore the configured scratch directory, and two
failed writes could previously compare as equal empty outputs. Build the
paths from testing::TempDir() per rule 17 and assert both output and
readback streams open before comparing contents.

* test(io): replace default basis argument with PW convenience overload

Rule 5 prohibits adding default arguments to existing interfaces. Drop
the default "pw" from write_input/reject_input in the input-domain test
fixture and provide an explicit one-argument overload that forwards
"pw", so the 24 existing PW call sites stay unchanged while the LCAO
case keeps its basis explicit.

Verified: OMP_NUM_THREADS=1 ./MODULE_IO_input_domain_reader, 19/19 pass.

* test(io): rename dH/dk outputs to dhkK<dir>_iaN and update refs

Change the dense dH/dk filename to put the 1-based k-point index right
after the prefix and use _ia for the atom index: dhk1x_ia1_nao.txt
replaces dhkx_iat1_ik0_nao.txt. The _nao suffix is kept. Update the
unit test and the scf_out_dh / scf_out_dh_t reference files and
result.ref keys to match.

* fix(io): reject non-finite DM(k) restart values

Check strtod range errors and finite components so malformed restart
matrices cannot propagate infinity or NaN into the density.

* docs(io): document DM(k) conj-first element convention

The DM(k) text files produced by write_dmk carry D(i,j) = sum_n w_n
conj(c_n,i) c_n,j because dm_from_psi builds DM = conj(P) (the physical
one-body density matrix P with the complex conjugate on the first band
index). This convention was only implicit in a consumer-side note at
source/source_io/module_mulliken/output_mulliken.cpp ~L37 (added in PR
#8250), so restart readers and external post-processing tools could
silently mix conj-first and conj-last interpretations.

- Emit a '#' comment line inside the 11-line header of every DM(k) file
  stating the exact element convention. Placing it inside the header block
  lets read_dmk's read_data_line skip it transparently; put it after the
  UnitCell block would break the matrix-body stream extractor which does
  not skip comment lines.
- Document the same convention in write_dmk's Doxygen @details, including
  the relation to the physical density matrix sum_n w_n c_n,i conj(c_n,j).
- Add a unit test HeaderStatesConjFirstConvention that asserts the header
  comment is present and that a non-symmetric complex probe round-trips
  through write_dmk/read_dmk without losing off-diagonal imaginary signs.

* test(ref): sync CSR refs with case-input R counts after hs_sparse_io format upgrade

The hs_sparse_io writer was upgraded in c1ff9a657 ("align tr_nao.csr with
the self-describing CSR layout", 2026-11-09) to emit the header block with
#-comment annotation, lattice info, and CSR format banner. The commit updated
two integration-test refs but did not touch get_s/sr_nao.csr.ref, which was
still in the legacy "Matrix Dimension of S(R)" / "Matrix number of S(R)"
format. A follow-up update at 1500ceced ("Align Vxc(R) CSR output with the
H(R) CSR layout") then changed the R count of the two tr_nao.csr.ref files
to values that do not match the case INPUT (125 and 9 vs the actual 9 and 1,
respectively). Both gaps are fixed here by running the three cases under the
current writer and capturing what it emits:

- get_s/sr_nao.csr.ref: legacy -> new self-describing header, R count 3
  (c1ff9a657 did not update this file at all).
- nscf_out_hsr_tr_rr/tr_nao.csr.ref: R count 125 -> 9 (matches c1ff9a657's
  correct value; 1500ceced had changed it by hand).
- scf_out_dh_t/tr_nao.csr.ref: R count 27 -> 1 (the case INPUT emits one R
  block; previous ref was R=27 from c1ff9a657, already a case/INPUT mismatch).

Also remove the untracked KPT file left behind under tests/02_NAO_Gamma/ by a
local run. No INPUT changes are present in this commit — the refs now reflect
what the cases actually compute.

* fix(dmk): propagate UnitCell parse failures instead of misreading coordinates as DM

UcellIO::read_ucell used to be a void line skipper: when the per-type
atom-count line in a DMK file was malformed (non-numeric, empty), the
std::istringstream loop yielded total_natom == 0, so the function only
consumed the "Direct" marker and left the coordinate rows on the stream.
A subsequent small-matrix body read (e.g. nlocal = 2 gamma) would then
happily consume those coordinate numbers and hand back a bogus density
matrix.  The init_chg = dm restart path trusts read_dmk's return value,
so a silently wrong density would seed the next SCF.

- Change UcellIO::read_ucell signature from void to bool.
- Every getline now checks the stream state; the atom-count line must
  yield at least one non-negative integer summing to a positive total,
  otherwise the block is indeterminate and we bail out.
- read_dmk handles the new return value: failure sets read_success,
  prints a diagnostic, and breaks out of the rank0 body so the existing
  bcast_bool cooperative-failure path propagates the error.
- Add a handwritten unit test ReadDMKRejectsMalformedAtomCount that
  rewrites the per-type count line to a non-numeric token and asserts
  read_dmk returns false without touching the caller buffer.

Test: DMKTest.* 24/24 pass (1 new, 23 existing no regression).

* fix(dmk): broadcast read status on descriptor communicator

* docs(input): clarify out_xc_r cube file naming channels

The old description compressed scalar, spin-resolved and tensor outputs
into one optional-suffix pattern, so users could not derive file names
such as xc_v2rhosigma_0_00.cube. List the three channel forms explicitly
and align the examples with libxc_r_channel_suffixes.

* test(md): split final-step predicate tests into a standalone translation unit

MODULE_MD_final_step was meant to test only the header-only loop predicates
(is_last_step / is_frame_write_step) and links without the heavy MD/cell
stack. After the source_md test consolidate, RunMdFinalStepTest ended up in
the same test_run_md.cpp as prepare_mdcell_from_unitcell, so the
dependency-free target failed to link with undefined references to
UnitCell / MDCell / DomainDecomposition / Run_MD::prepare_mdcell.

Move RunMdFinalStepTest into its own test_run_md_final_step.cpp (only
includes run_md.h + gtest) and point MODULE_MD_final_step at it. The heavy
prepare_mdcell and cadence tests stay in test_run_md.cpp, built by
MODULE_MD_run with the full dependency set.

* test(io): route MPI rank/size, barrier and reduction through parallel helpers

Replace raw MPI calls in test_write_dmk.cpp and test_hs_dense_io.cpp
with the project parallel helpers (ParaWorld::make_mpi + Parallel::barrier
/Parallel::reduce_min), following the world_barrier precedent in
test_read_wfc_nao.cpp. Encapsulate the MPI_Comm_split/free pair in a
test-local RAII guard (SplitCommGuard) since the parallel helpers
deliberately do not own communicator lifetimes. Add para_world.cpp and
para_mpi_func.cpp to MODULE_IO_hs_dense_io_test sources, which lists
files manually instead of linking base.

* test(io): slim down test_write_dmk.cpp

- Introduce a DMKTest fixture owning the Si UnitCell, replacing 24
  repeated create/delete boilerplate blocks and removing raw delete.
- Add expect_dmk_eq helpers (double/complex) to replace six handwritten
  element-wise EXPECT_NEAR loops in round-trip and mode tests.
- Collapse WriteDMK's six copy-pasted read/assert/remove blocks into a
  table-driven loop, keeping the trailing-newline check.
- Drop Mode1FixedNameAppend: its append semantics are fully covered by
  ReadDMKMode1FrameSelection.
- Compress the // ---- banner comments to one or two informative lines.

Net -238 lines (1817 -> 1579); serial and 2-rank MPI runs both pass.

* docs(io): sync out_mat_dh help and write_dh.h with actual dH(k) filename pattern

The writer embeds the 1-based k-point index right after the prefix
(dhk{k}{xyz}_ia{I}[s{spin}][g{step}]_nao.txt), but the out_mat_dh help
still documented dhk[xyz]_iat{I} with an optional _ik suffix, and the
write_dh.h comment used the same stale pattern. Update both to the real
naming, noting the spin suffix is always present for dH(R) (dhr_gen_fname)
but only for nspin=2 in dH(k) (dhk_gen_fname).

* fix(pw): require EXX source files to share one SCF snapshot

The hybrid-NSCF source resolver picked the latest g{step}/e{iter}
variant independently for each wavefunction file and for eig_occ.txt,
so an interrupted or partia…
* Document the Wannier90 spin-matrix regression

* Place the README with the Wannier90 interface tests and document pytest

---------

Co-authored-by: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com>
Co-authored-by: Mohan Chen <mohanchen@pku.edu.cn>
* CI: validate OpenBLAS and select a compatible kernel for ASE tests

* Keep OpenBLAS selection helpers with ASE tests

* Simplify the OpenBLAS regression probe and selection loop

* CI: use the Prescott OpenBLAS kernel for ASE tests
…eling#8361)

* Fix(cell): validate core STRU fields against malformed input

Confirmed with a local driver on current develop: an ATOMIC_SPECIES line
without a mass is accepted with mass = 0; a LATTICE_VECTORS block with
fewer than 9 components keeps the unread tail at the Matrix3 identity
default (det stays 1, surviving even a determinant check); a truncated
coordinate line is caught only deep in parse_atom_properties() with the
misleading 'mismatch in atom number' message and exit(1); a non-numeric
atom count leaves na = 0 and triggers the 'atom number is 0' banner for
the wrong reason.

- read_atom_species(): quit if the species label/mass extraction fails;
- read_lattice_constant(): read the 9 LATTICE_VECTORS components with a
  single extraction chain and quit on failure;
- read_atom_positions(): reject a failed coordinate-triplet extraction
  at the extraction point with a clear message;
- read_atom_type_header(): reject a failed atom-count extraction
  (extraction checked before the line remainder is consumed, so a valid
  final zero at EOF is still accepted).

New unit tests in unittests/test_read_atom_species.cpp and
unittests/test_read_atoms.cpp; both binaries built and run locally,
6/6 pass.

Refs deepmodeling#8356.

* Fix(cell): preserve READ_VALUE line semantics in LATTICE_VECTORS and EOF handling

READ_VALUE swallows the rest of the line after each extraction, and real
STRU files annotate lattice vector rows with trailing comments
(0.5 0.5 0.0  # a3); the single 9-component chain rejected those valid
files. Read per row and getline the remainder instead, keeping the
extraction check.

A coordinate triplet that fails at EOF means fewer lines than the
declared atom count; leave that to the existing mismatch-in-atom-number
exit in parse_atom_properties, and reject only malformed numeric
content (fail without eof).

* Fix(cell): consume STRU reader returns in setup_cell and fix EOF handling

setup_cell ignored the return values of read_atom_species and
read_lattice_constant, silently continuing after a failed read; fold
them into the ok flag that is already broadcast and checked.

The legacy signed-char EOF check in parse_atom_properties was
non-portable and misreported a complete final coordinate triplet ending
exactly at EOF as a count mismatch; distinguish the cases by stream
state instead.

Tests: two-species discriminating count case with warning-text
assertion, literal-zero-count control, valid exact-EOF control, and
fixture repairs (Atom ownership, full temp-file tracking, rule-16 read
confirmations).
…nsions (deepmodeling#8353)

* Fix(source_cell): reject invalid k-point counts and MP grid dimensions

Confirmed against current develop with a small driver through the public
read_kpoints path: a negative k-point count is silently accepted
(nkstot=-4 returns success), a zero or non-numeric Monkhorst-Pack grid
dimension is accepted with nkstot=0, and a negative dimension crashes
with an uncaught std::length_error from renew().

- parse_kfile(): reject nkstot < 0 next to the existing MAX_KPOINTS check;
- read_mp_mesh(): require successful extraction of all three grid
  dimensions, all positive, with the product within int range;
- QList::read_from_file(): apply the same grid validation, following its
  existing warning-and-reset style.

Refs deepmodeling#8352.

* test(cell): link module_neighlist sources into klist validation test

The cell and domain_decomposition object libraries reference
NeighborSearch::init/build_neighbors/refresh_mdcell; mirror the
mdcell_adapter test target, which compiles the three module_neighlist
sources into the test executable.

* Fix(cell): harden MP grid validation against negative pairs and overflow

Address review on deepmodeling#8353: a negative dimension pair (-1 -1 4) has a
positive product and passed the product-sign check, and the long long
product itself can overflow for extreme dimensions. Validate each
dimension individually and compare before multiplying
(nmp[0] <= INT_MAX/nmp[1], then nmp[0]*nmp[1] <= INT_MAX/nmp[2]), in
both the KPT and QPT readers. Verified with the local driver: -1 -1 4
and 2097152^3 are now rejected, valid grids unaffected.

Also make the QPT regression test discriminating: a negative dimension
crashed the old code, instead of the zero-dimension case that left
nkstot==0 in both old and new implementations.

* Fix(cell): add 2^63 MP grid overflow regression for KPT and QPT readers

2097152^3 = 2^63 overflows even a 64-bit signed product; the guard
compares before multiplying, and these cases pin that behavior down.
Keep the upstream restart-test source and the serial reader registrations.
Remove the temporary symmetry rejection and update input coverage and installation guidance for LibRI v0.3.0.0.
* Precommit: Format source_hamilt (Part I)

* Fix CUDA build
Consume DDLA's public GPU capability without relying on its private backend
definitions. Remove the C++17 requirement from ABACUS and update the
installation guidance and standalone consumer check.
…eepmodeling#8355)

* Fix(cell): require LATTICE_PARAMETERS for non-cubic named lattices

Confirmed empirically on current develop: a named non-cubic lattice
without LATTICE_PARAMETERS silently builds a zero-volume cell
(hexagonal, trigonal, ...: shape factors stay zero) or a NaN cell
(triclinic: 0/0 in the shape formula), and the reciprocal-lattice
inversion then fails far from the actual input mistake.

- read_lattice_constant(): require the LATTICE_PARAMETERS line for all
  non-cubic named lattices and quit with a clear message naming the
  lattice type otherwise;
- reject degenerate (zero-volume) or non-finite lattice vectors after
  construction, covering malformed parameter values and the
  LATTICE_VECTORS path as well.

Refs deepmodeling#8354.

* Fix(cell): validate trigonal cos(alpha) extraction in LATTICE_PARAMETERS

A failed extraction left cosab = 0 and silently built the simple-cubic
(alpha = 90 degree) special case instead of the intended trigonal cell;
this is the only named-lattice branch where a malformed parameter line
still yields a finite, nonzero-volume cell, so the determinant check
alone does not catch it.

Also add the corresponding death test and run the new test binary
locally: 6/6 pass.

* Fix(cell): validate multi-value LATTICE_PARAMETERS reads in sm/bacm/triclinic

Address review on deepmodeling#8354: a partially malformed parameter line such as
'2 3 bad' leaves the earlier values in place and the failed one at zero,
producing a finite nonzero-volume cell (e.g. sm gives a diag(1,2,3)-like
lattice with det = 6) that the determinant check alone accepts. Read the
parameter values with a single extraction chain and reject on failure.

Add death tests for the three branches plus a valid sm control; the
local test binary passes 10/10.

* Fix(cell): validate remaining LATTICE_PARAMETERS reads against range errors

An out-of-range value such as 1e999 sets failbit but stores DBL_MAX,
leaving a finite nonzero determinant that escaped both the unchecked
READ_VALUE extraction and the determinant check. Every named-lattice
parameter read (hexagonal, st, bct, so, baco, fco, bco) now validates
extraction directly, matching the sm/bacm/triclinic branches.

* Fix(cell): report unsupported latname before requiring LATTICE_PARAMETERS

The parameter-section guard ran before the lattice-name cascade, so an
unsupported latname was met with a demand for LATTICE_PARAMETERS instead
of 'latname not supported' (caught by legacy ReadAtomSpeciesWarning5).
Move the guard after the branches so the name validates first.

* Test(cell): pin the latname-then-params diagnostic order

The legacy Warning5 fixture contains LATTICE_PARAMETERS, so it passes
with the presence guard on either side of the name cascade. Add an
unsupported-latName case without the section to lock in the order.

* CI: retrigger transient ReadTheDocs build failure
…eepmodeling#8346)

* fix(source_cell): guard read_orb_file against orbital channels beyond Lmax

An .orb file with Lmax=0 that still declares "Number of Porbital--> 0"
(a convention of orbital generators, e.g. tests/PP_ORB/H_gga_8au_100Ry_1s.orb)
made read_orb_file() write past the end of l_nchi, which is resized to
nwl+1 entries. The write is out-of-bounds UB that usually goes unnoticed
because the value happens to be zero.

- tolerate zero-count declaration lines for channels beyond Lmax,
  still consuming the value to keep the stream in sync;
- reject nonzero counts beyond Lmax as malformed input;
- reject channel lines appearing before the Lmax declaration.

Add unit tests in source_cell/unittests/test_read_orb.cpp covering both
boundaries plus a normal multi-channel file.

Refs deepmodeling#8345.

* test(source_cell): pass mutable orb path in read_orb boundary test

read_orb_file() takes the orbital filename as a non-const std::string&,
so the test temporaries must be mutable lvalues; const-qualifying them
broke the build.

* test(source_cell): fix read_orb boundary test fixtures and assertions

- Append the "SUMMARY  END" marker to the multi-channel fixture so it
  matches real .orb file structure; without trailing content the parser's
  while(ifs.good()) loop reprocesses the final count line at EOF and
  double-counts it.
- Drop stdout capture from the rejection tests: ModuleBase::WARNING
  writes to GlobalV::ofs_warning, not std::cout. The boolean return is
  the contract under test.

* fix(source_cell): validate count extraction for channels beyond Lmax

Address review: READ_VALUE hides extraction failure, so a missing or
non-numeric count beyond Lmax passed the zero check and left the stream
failed, silently skipping the rest of the header. Extract the count
explicitly and reject on failure; the loop condition is now
'while (ifs >> word)' so the final token is no longer reprocessed at
EOF and a failed extraction is always genuinely malformed input.

Add rejection tests for non-numeric and missing counts, and log the
fixture file creation to the running log (AGENTS.md rule 16).
* Drop deprecation

* Re-order CMake options

* Drop unused GIT_SUBMODULE option

* Fix MKL linking in pyabacus CMake

* Use CMake's built-in FindLAPACK directly, including BLAS discovery
* Docker: Update to Ubuntu 24.04

* CI: Drop unused pip installation

* Revert "CI: use the Prescott OpenBLAS kernel for ASE tests (deepmodeling#8348)"

This reverts commit 31ddd31.

With this Docker update the CI workaround is no longer needed in the future.

* Build superlu_dist manually

PEXSI 2.0.0 is incompatible with superlu_dist >=8
…invariant and align complex cuBLAS scalars (deepmodeling#8372)

* Test: Make plane-wave wavefunction checks phase invariant

* Fix: Align complex cuBLAS scalars and correct scalar einsum contractions
* Fix PW spinor DFT+U occupation-matrix flattening

* Remove PW SOC integration case from DFT+U mixing fix

* Clarify spinor mixer regression buffer size

* Retrigger CI after documentation network timeout
…os 2 (deepmodeling#8332)

* feat: write and plot LCAO projected DOS in NumPy format

* feat: share NumPy output between total and projected DOS

* refactor: name the DOS format selector out_dos_format

* refactor: keep NumPy DOS output separate from the text writer

* Share PDOS orbital sums and simplify NumPy output

* Limit NumPy output to single-point LCAO projected DOS

* Handle ambiguous PDOS directories and test native NumPy output

* Exercise spin-polarized NPY PDOS in Autotest and validate record metadata

* Propagate PDOS validation failures to Autotest

* Select NumPy total and projected LCAO DOS with out_dos 2

* Store all total DOS spin channels in dos.npy

* docs: clarify precision and write costs for out_dos 2

* refactor: pass out_dos directly to the LCAO DOS writer

* test: cover in-memory capture of total DOS

* refactor: use explicit types in LCAO DOS output and tests

---------

Co-authored-by: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com>
Co-authored-by: Mohan Chen <mohanchen@pku.edu.cn>
…its (deepmodeling#8351)

* refactor(io): add precision parameter to out_mat_xc

* refactor(io): feed out_mat_xc precision into write_Vxc

* refactor(io)!: remove deprecated out_ndigits

* feat(io): add precision parameter to out_dos

* fix(io): validate out_dos/out_mat_xc tokens and clean up DOS precision test

- Validate one or two complete tokens for out_dos and out_mat_xc in
  prepare_input, so partial tokens such as "1junk" and overflowing values
  are reported through input_error instead of being accepted or escaping.
- Catch std::exception in both read hooks so std::out_of_range can no longer
  escape a direct read_value call.
- Move the precision test scratch output to testing::TempDir(), drop the
  redundant MPI rank guard and assert exact four-decimal fields.
- Document the optional out_dos precision integer in dos.md.

---------

Co-authored-by: abacus_fixer <mohanchen@pku.eud.cn>
* Use CMake build of NEP_CPU

* Update NEP module file

* Test NEP in CI

* Fix CI failure
…ity (deepmodeling#8384)

Map destination lattice nodes directly to the periodic source grid. The
previous half-cell mapping shifted density and extrapolated at the origin
during refinement, producing negative values from nonnegative input.

Cover node alignment, periodic wraparound, all three axes, same-grid copying
and coarsening. Update the real-cube reference values to the corresponding
source nodes.

Validation of these exact file contents on SAI:
- Four real ABACUS initialization cases, including same-grid control.
- MODULE_IO_rho_io: 8 tests passed.
- New interpolation regressions fail against the original implementation.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.