Skip to content

feat(lcao): output momentum operator matrices via out_mat_p - #8429

Open
mohanchen wants to merge 6 commits into
deepmodeling:developfrom
mohanchen:2026-11-26-d
Open

mohanchen wants to merge 6 commits into
deepmodeling:developfrom
mohanchen:2026-11-26-d

Conversation

@mohanchen

Copy link
Copy Markdown
Collaborator

Summary

Closes #7355.

Add a new INPUT keyword out_mat_p that writes the three Cartesian components of
the momentum operator in the NAO basis:

p = -i * grad + i * [V_NL, r]

The matrices are produced in the SCF workflow and in calculation = get_s,
where they can be generated without an SCF cycle because they depend only on the
orbital tables and the pseudopotential projectors.

Output

File Content
prx_nao.csr <phi_i|p_x|phi_j>
pry_nao.csr <phi_i|p_y|phi_j>
prz_nao.csr <phi_i|p_z|phi_j>
  • Same self-describing header and CSR layout as the H(R)/S(R) sparse output.
  • out_mat_p [bool] [precision], default False 8.
  • When out_app_flag = 2, the ionic step is inserted before _nao, e.g.
    prxg1_nao.csr. With out_app_flag = 0/1 the files are overwritten/appended
    as usual.
  • get_s has no ionic step, so it passes istep = -1 and writes the step-less
    names.
  • nspin = 4 is rejected during INPUT parsing with an explicit diagnostic: the
    momentum matrix is written as a scalar (npol = 1) block.

Because the NAO basis is real, every matrix element is purely imaginary, so the
stored real part is identically zero. Both the gradient term (calculate_grad_term)
and the nonlocal-pseudopotential commutator (calculate_vcomm_r) are included;
the /2 factor in the commutator kernel converts the D matrix from Ry to Hartree.

What changed

  • New parameter: out_mat_p in Input_para, registered in
    read_inp_out.cpp, with the nspin = 4 check in read_input.cpp.
  • New writer: source_io/module_hs/mom_op_mat.{h,cpp} builds the matrices
    through the existing Velocity_op kernel and writes the three CSR files.
    Momentum_op::calculate takes every dependency explicitly
    (UnitCell, Grid_Driver, TwoCenterBundle, Parallel_Orbitals,
    LCAO_Orbitals, output dir, Input_para) and does not read PARAM.
  • Call sites: ctrl_scf_lcao.cpp (SCF) and esolver_gets.cpp (get_s),
    keeping the upstream out_mat_l path intact and running out_mat_p after it.
  • Refactor: pos_op_* and velocity_op.* move from source_io/module_hs
    into source_lcao/module_momentum_op/ (pure moves, no behavior change), wired
    through CMakeLists.txt and Makefile.Objects.
  • HContainer: expose the flattened basis indexing and block-cyclic
    distribution, and let Output_HContainer::write_single_R translate local
    block-cyclic coordinates to global indices. This removes the "to do: consider
    2D block-cyclic distribution" gap for the flattened layout.
  • Test layout: migrate the legacy module_rt/test/snap_psb_half_tddft_test.cpp
    to module_rt/unittests/test_snap_psb_half_tddft.cpp.
  • Docs: docs/advanced/elec_properties/hs_matrix.md and the calculation
    description now cover out_mat_p, the file names, and the nspin = 4
    restriction.
  • Integration test: 03_NAO_multik/get_s enables out_mat_p and compares
    prx/pry/prz_nao.csr via props_common.sh / props_mat.sh
    (ComparePx/Py/Pz_pass).

Verification

Build (CMake, GNU toolchain, OMP_NUM_THREADS=1):

make -j 30 abacus_max_para            # PASS

Unit tests:

ctest -R MODULE_LCAO_tddft_snap_psibeta_half_test   # 4/4 PASS

Integration case 03_NAO_multik/get_s (calculation = get_s, out_mat_p 1),
comparing against the new references at 8 significant digits:

sr_nao.csr, lx_nao.csr, ly_nao.csr, lz_nao.csr,
prx_nao.csr, pry_nao.csr, prz_nao.csr                # 7/7 PASS

Governance:

python3 tools/03_code_analysis/agent_governance_check.py \
    --base upstream/develop --head HEAD --format text

No blocking findings; PR-level global dependency budget is unchanged
(added = 0, removed = 0). The remaining 8 warnings are header-include
reviews, all allowed; e.g. mom_op_mat.h forward-declares Input_para and the
Momentum-op classes instead of pulling their headers.

git diff upstream/develop --check passes.

Not covered in this PR

  • The full 03_NAO_multik suite and broader TDDFT/LR regressions were not run
    locally; only the get_s case and the migrated TDDFT unit tests above.
  • Only the CMake build was validated; the legacy GNU Make build was not built.
  • out_app_flag = 2 naming and append behavior, nspin = 2, and MD/multi-step
    runs are not exercised by the integration test.
  • calculation = nscf is not wired; only SCF and get_s.

abacus_fixer added 3 commits November 27, 2026 10:59
Add a new INPUT parameter `out_mat_p` for LCAO calculations. When enabled,
the momentum (velocity) operator matrices p = -i grad + i[V_NL, r] are
written as sparse matrices prx_nao.csr, pry_nao.csr and prz_nao.csr
(prxg{step}_nao.csr etc. when out_app_flag = 2), reusing the gradient
term and the nonlocal commutator already implemented for the TDDFT
velocity operator. The matrices are built from the orbital tables and
pseudopotential projectors only, so they are available in both the SCF
and the `calculation = get_s` workflows; nspin = 4 is rejected.

- add Momentum_op::calculate and wire it into ctrl_scf_lcao and ESolver_GetS
- move pos_op_* and velocity_op into source_lcao/module_momentum_op
- extend HContainer with get_basis_index()/get_matrix_dist() and let
  Output_HContainer::write_single_R handle flattened local-to-global
  indexing for the CSR output
- update parameter description, hs_matrix.md, and add the get_s
  integration test (INPUT, refs, props_mat.sh comparisons)
Pass Input_para explicitly into Momentum_op::calculate instead of reading
PARAM, and migrate the touched snap_psibeta test into unittests to satisfy
the test layout policy. Also remove trailing blank lines from the new CSR
reference files.
# Conflicts:
#	docs/advanced/elec_properties/hs_matrix.md
#	source/source_esolver/esolver_gets.cpp
#	tests/03_NAO_multik/get_s/INPUT
#	tests/03_NAO_multik/get_s/result.ref
#	tests/integrate/validation_tools/props_common.sh
#	tests/integrate/validation_tools/props_mat.sh
Merge the position, momentum and angular-momentum matrix writers into one
module under source/source_lcao/module_op:

- rename module_momentum_op to module_op and move mom_op_mat and
  angmom_op_mat out of source_io/module_hs, together with their unit tests;
- name the angular momentum files lrx/lry/lrz_nao.csr so every R-space
  operator follows the <quantity>r<axis> pattern used by rrx and prx;
- update docs, INPUT descriptions, the relax example, integration
  references and Makefile.Objects;
- add a README describing the module scope and where new operators go.
@mohanchen mohanchen added Refactor Refactor ABACUS codes Input&Output Suitable for coders without knowing too many DFT details Features Needed The features are indeed needed, and developers should have sophisticated knowledge labels Nov 28, 2026
abacus_fixer added 2 commits November 28, 2026 11:55
Python 3.8 is unavailable on the Ubuntu 26.04 runner image now selected by
ubuntu-latest, so use a supported version for the pyabacus and readme checks.
Assemble the momentum operator on rank 0 in a serial layout so the CSR
output contains the full matrix instead of rank-local blocks.

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The new output path has two robustness issues: malformed options bypass shared validation, and failed CSR writes can go unreported. Please address the two inline error-handling comments.

Static review only; no builds or runtime tests were run.

Non-blocking: please change the PR's statement that nscf is not wired to distinguish untested behavior from reachability. The ordinary LCAO NSCF route reaches after_scf through Relax_Driver and ESolver_KS::runner, and this controller has no SCF-only guard.

Comment on lines +1482 to +1488
const size_t count = item.get_size();
if (count < 1) ModuleBase::WARNING_QUIT("ReadInput", "out_mat_p needs at least 1 value");
para.input.out_mat_p[0] = assume_as_boolean(item.str_values[0]);
para.input.out_mat_p[1] = 8;
if (count >= 2) try { para.input.out_mat_p[1] = std::stoi(item.str_values[1]); }
catch (const std::invalid_argument&) { /* do nothing */ }
catch (const std::out_of_range&) {/* do nothing */}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please validate the original out_mat_p tokens in prepare_input before this reader runs. For example, out_mat_p maybe reaches WARNING_QUIT on rank 0 before the shared input_error broadcast, while out_mat_p 1 foo and out_mat_p 1 8junk silently use 8; extra tokens are also ignored. Return a shared diagnostic and cover invalid Boolean, precision and token-count cases.

// so normalize it to the single "first" record like the other matrices.
const int header_istep = istep >= 0 ? istep : 0;

ModuleIO::write_hcontainer_csr(filename,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please check the Boolean returned by write_hcontainer_csr. It reports write/close failures after a successful open, but this caller discards it, so exhausted storage can leave a partial momentum matrix while the calculation continues. Report the failed filename and propagate the error consistently across ranks.

Comment on lines +88 to +95
LCAO_Orbitals lcao_orb;
two_center_bundle.to_LCAO_Orbitals(lcao_orb,
inp.lcao_ecut,
inp.lcao_dk,
inp.lcao_dr,
inp.lcao_rmax,
inp.out_element_info,
inp.cal_force);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking: reuse the initialized orb argument instead of converting the same TwoCenterBundle again here. Both callers already populate that descriptor, but this function ignores it and repeats the orbital allocations and conversion on every enabled output step.

const MPI_Comm comm = pv.para_2d().comm();
if (comm != MPI_COMM_NULL)
{
MPI_Comm_rank(comm, &rank);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking: pass the output-rank decision from the caller, or use an internally guarded parallel abstraction. This new direct MPI_Comm_rank call violates the repository's MPI-wrapper rule even though it is protected by __MPI.

note,
0.0, // efermi_eV: not applicable
false); // has_efermi
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking: record each successfully written momentum filename in the running log, as the H/S and angular-momentum writers do. write_hcontainer_csr does not emit that notice; pass the log stream explicitly and reuse write_matrix_notice with the full path.

Comment on lines +145 to +149
const int g_row = flattened ? dist->irglb(row_begin + irow) : (row_begin + irow);
for (int icol = 0; icol < col_size; ++icol)
{
sparse_matrix.insert(irow, icol, *tmp_data);
const int g_col = flattened ? dist->icglb(col_begin + icol) : (col_begin + icol);
sparse_matrix.insert(g_row, g_col, *tmp_data);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking: add a focused writer test with nonidentity block-cyclic row/column maps. The new momentum case uses set_serial, so it cannot catch a swapped or omitted local-to-global conversion here. Supplement the stored momentum references with an independent analytic or finite-difference check of the operator sign and Hartree conversion.

## Build and test

```bash
cmake -S . -B build

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking: add -DBUILD_TESTING=ON to this configure command. It defaults to OFF at the repository root, so a fresh build does not generate the two test targets requested on the next line.

if (comp == nullptr)
{
ModuleBase::WARNING_QUIT("Momentum_op::calculate",
"Velocity_op returned a null HContainer for component " + std::to_string(c));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking: assign this constructed diagnostic to a named local before passing it to WARNING_QUIT, as required by the repository's rule for computed function arguments.

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

Features Needed The features are indeed needed, and developers should have sophisticated knowledge Input&Output Suitable for coders without knowing too many DFT details Refactor Refactor ABACUS codes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

the Output of the Momentum operator matrix in LCAO

2 participants