From 842593154dbf838589f694406d9b2a2e2ef07c5a Mon Sep 17 00:00:00 2001 From: Zanthoxylum <105619360+Zanthoxylum@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:38:57 +0800 Subject: [PATCH 1/4] fix(dfpt): stop unconverged responses before result assembly Summary Stop ordinary displacement and electric-field outer solves with WARNING_QUIT when their response budget is exhausted. Report the failed task, physical q, iteration budget and residual before any completed-response cache is populated. Design Use the existing fatal exit path. A failing producer can no longer return to the legacy driver's identical repeated passes. Successful solves keep the same arithmetic and output. Inner-solver reports and stale-output ownership remain separate follow-ups. Verification Rebuilt the main executable and all eleven DFPT unit-test targets. The four new real-process negative cases reject the old executable (exit 0 with a dyn file) and accept the candidate (exit 1 without formal output). A three-step budget stops after three traces rather than the old 54. Three successful controls retain byte-identical dyn files; all six default Gamma frequencies are unchanged. INPUT help and --check-input pass. Tests CTest: 17/17; default Gamma Autotest: 8/8 attributes; governance: no findings. The finite-q fixture uses an explicit one-point Direct list to retain the ordinary solve path when the uniform-mesh planner is present; the physical k point and weight are unchanged. All four process checks were rerun on the preserved independent binary after this fixture refinement. DFPT C++ and CMake formatting pass. Only new description statements outside DFPT were formatted. Expected nonzero exits cannot be expressed by Autotest, so focused process drivers check the exit, converged GS, exact failed task, finite residual, iteration count and absence of fresh formal output. --- .../elec_properties/dfpt_convergence.md | 29 ++++++ docs/advanced/elec_properties/index.rst | 1 + .../module_parameter/read_inp_dfpt.cpp | 5 + source/source_pw/module_dfpt/dfpt_pw_q0.cpp | 16 +-- .../source_pw/module_dfpt/dfpt_pw_solve.cpp | 11 ++- tests/integrate/CMakeLists.txt | 20 ++++ .../integrate/fixtures/dfpt_failure/README.md | 23 +++++ .../fixtures/dfpt_failure/displacement/INPUT | 24 +++++ .../fixtures/dfpt_failure/displacement/KPT | 4 + .../fixtures/dfpt_failure/displacement/QFILE | 4 + .../fixtures/dfpt_failure/displacement/STRU | 19 ++++ .../dfpt_failure/displacement/expected.json | 14 +++ .../dfpt_failure/displacement_budget/INPUT | 24 +++++ .../dfpt_failure/displacement_budget/KPT | 4 + .../dfpt_failure/displacement_budget/QFILE | 4 + .../dfpt_failure/displacement_budget/STRU | 19 ++++ .../displacement_budget/expected.json | 14 +++ .../fixtures/dfpt_failure/efield/INPUT | 24 +++++ .../fixtures/dfpt_failure/efield/KPT | 4 + .../fixtures/dfpt_failure/efield/QFILE | 4 + .../fixtures/dfpt_failure/efield/STRU | 19 ++++ .../dfpt_failure/efield/expected.json | 14 +++ .../fixtures/dfpt_failure/finite_q/INPUT | 24 +++++ .../fixtures/dfpt_failure/finite_q/KPT | 4 + .../fixtures/dfpt_failure/finite_q/QFILE | 4 + .../fixtures/dfpt_failure/finite_q/STRU | 19 ++++ .../dfpt_failure/finite_q/expected.json | 14 +++ .../validation_tools/check_dfpt_failure.py | 99 +++++++++++++++++++ .../test_check_dfpt_failure.py | 61 ++++++++++++ 29 files changed, 513 insertions(+), 12 deletions(-) create mode 100644 docs/advanced/elec_properties/dfpt_convergence.md create mode 100644 tests/integrate/fixtures/dfpt_failure/README.md create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement/expected.json create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement_budget/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement_budget/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement_budget/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement_budget/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/displacement_budget/expected.json create mode 100644 tests/integrate/fixtures/dfpt_failure/efield/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/efield/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/efield/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/efield/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/efield/expected.json create mode 100644 tests/integrate/fixtures/dfpt_failure/finite_q/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/finite_q/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/finite_q/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/finite_q/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/finite_q/expected.json create mode 100644 tests/integrate/validation_tools/check_dfpt_failure.py create mode 100644 tests/integrate/validation_tools/test_check_dfpt_failure.py diff --git a/docs/advanced/elec_properties/dfpt_convergence.md b/docs/advanced/elec_properties/dfpt_convergence.md new file mode 100644 index 00000000000..50f4ea44c49 --- /dev/null +++ b/docs/advanced/elec_properties/dfpt_convergence.md @@ -0,0 +1,29 @@ +# DFPT response convergence + +A converged ground state is followed by separate response calculations. +`dfpt_conv_thr` controls the outer density or screening-potential fixed-point +residual; `dfpt_max_iter` caps that response iteration. The Sternheimer +controls `dfpt_lin_conv_thr` and `dfpt_lin_max_iter` specify the inner linear +solve and should be set explicitly when diagnosing either level separately. + +An atomic-displacement or ordinary electric-field response that still fails +its outer criterion at the limit terminates ABACUS with exit status 1, before +that incomplete response is cached or used for force constants, dielectric +response or LO-TO results. A response that first satisfies the criterion on +the final allowed iteration succeeds. Failed solves are not restarted as +another identical full displacement pass. + +The failure diagnostic records the response stage, q index and fractional +coordinates, direction, atom for displacement responses, actual iterations, +limit, final residual and threshold. It is available in stdout and +`OUT./warning.log`. q indices retain the existing zero-based output +convention; the diagnostic atom index is one-based. + +The checks described here concern outer response self-consistency. They do +not establish convergence with respect to basis cutoffs or sampling. A +converged imaginary phonon frequency can describe structural instability and +is not itself a response-convergence failure. + +Use a fresh output directory when checking failure products. Earlier files +can remain after reusing a suffix; their presence is not evidence that the +latest calculation succeeded. Inspect the current exit status and logs. diff --git a/docs/advanced/elec_properties/index.rst b/docs/advanced/elec_properties/index.rst index b7efcfe731b..e89650c2f69 100644 --- a/docs/advanced/elec_properties/index.rst +++ b/docs/advanced/elec_properties/index.rst @@ -8,6 +8,7 @@ Electronic Properties and Outputs dos Mulliken potential + dfpt_convergence wfc charge hs_matrix diff --git a/source/source_io/module_parameter/read_inp_dfpt.cpp b/source/source_io/module_parameter/read_inp_dfpt.cpp index 73038abce64..e7ca72abb41 100644 --- a/source/source_io/module_parameter/read_inp_dfpt.cpp +++ b/source/source_io/module_parameter/read_inp_dfpt.cpp @@ -158,6 +158,8 @@ void ReadInput::item_dfpt() "is always the density residual."; item.default_value = "1.0e-8"; read_sync_double(input.dfpt_conv_thr); + item.description += " An unconverged displacement or electric-field response stops " + "the calculation before its results are cached or assembled."; item.check_value = [](const Input_Item &item, const Parameter ¶) { if (para.input.dfpt_conv_thr <= 0.0) @@ -177,6 +179,9 @@ void ReadInput::item_dfpt() "each atomic displacement."; item.default_value = "100"; read_sync_int(input.dfpt_max_iter); + item.description += " The same cap applies to each ordinary electric-field direction. " + "An unconverged response stops with a nonzero exit status; " + "convergence on the final allowed iteration is successful."; this->add_item(item); } { diff --git a/source/source_pw/module_dfpt/dfpt_pw_q0.cpp b/source/source_pw/module_dfpt/dfpt_pw_q0.cpp index a2f4a50977c..8b4fc486706 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_q0.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_q0.cpp @@ -359,14 +359,16 @@ void DFPT_PW::Impl::solve_efield_resp(int q_idx) } if (!converged) { - // same explicit non-convergence report as solve_displacement: - // a silently truncated E-field solve corrupts Z* / LO-TO + // Stop before this incomplete response can enter the E-field + // cache and subsequent dielectric/LO-TO calculations. + const ModuleBase::Vector3 q_frac = data_.get_qvec(q_idx); std::ostringstream oss; - oss << "the E-field response (dir " << static_cast('x' + a) - << ") did not converge within dfpt_max_iter=" << max_iter_ << ": final residual " << std::scientific - << std::setprecision(3) << residual_last << " vs threshold " << std::setprecision(1) << conv_thr_ - << std::defaultfloat << ". Z* / LO-TO splitting from this solve is unreliable"; - ModuleBase::WARNING("DFPT_PW::solve_efield_resp", oss.str()); + oss << "DFPT response failure: stage=efield q_index=" << q_idx + << " direction=" << static_cast('x' + a) << " iterations=" << n_iter_done + << " limit=" << max_iter_ << " residual=" << std::scientific << std::setprecision(6) << residual_last + << " threshold=" << conv_thr_ << " q_direct=(" << q_frac.x << "," << q_frac.y << "," << q_frac.z + << "). The response did not converge; stopping before caching or assembly."; + ModuleBase::WARNING_QUIT("DFPT_PW::solve_efield_resp", oss.str()); } stash_dpsi_efield(q_idx, a, nk, nbands); } diff --git a/source/source_pw/module_dfpt/dfpt_pw_solve.cpp b/source/source_pw/module_dfpt/dfpt_pw_solve.cpp index f767bc96555..3bd90f85cc6 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_solve.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_solve.cpp @@ -472,11 +472,12 @@ double DFPT_PW::Impl::solve_displacement(int q_idx, int iat, int idir) if (!converged) { std::ostringstream oss; - oss << "the displacement response (atom " << iat + 1 << " dir " << static_cast('x' + idir) - << ") did not converge within dfpt_max_iter=" << max_iter_ << ": final residual " << std::scientific - << std::setprecision(3) << residual << " vs threshold " << std::setprecision(1) << conv_thr_ - << std::defaultfloat << ". Phonon frequencies involving this displacement are unreliable"; - ModuleBase::WARNING("DFPT_PW::solve_displacement", oss.str()); + oss << "DFPT response failure: stage=displacement q_index=" << q_idx << " atom=" << iat + 1 + << " direction=" << static_cast('x' + idir) << " iterations=" << n_iter_done << " limit=" << max_iter_ + << " residual=" << std::scientific << std::setprecision(6) << residual << " threshold=" << conv_thr_ + << " q_direct=(" << q_frac.x << "," << q_frac.y << "," << q_frac.z + << "). The response did not converge; stopping before caching or assembly."; + ModuleBase::WARNING_QUIT("DFPT_PW::solve_displacement", oss.str()); } stash_converged_disp_response(q_idx, iat, idir, v_sc_r_last, nk, nbands); diff --git a/tests/integrate/CMakeLists.txt b/tests/integrate/CMakeLists.txt index e347800babf..f1f6668198d 100644 --- a/tests/integrate/CMakeLists.txt +++ b/tests/integrate/CMakeLists.txt @@ -36,6 +36,26 @@ endif() # Cheap collector regressions; no ABACUS calculation or finite differences. find_program(LR_FORCE_TEST_PYTHON python3) if(LR_FORCE_TEST_PYTHON) + # Expected nonzero exits cannot pass the ordinary Autotest contract. + add_test( + NAME dfpt_failure_validator + COMMAND + ${LR_FORCE_TEST_PYTHON} -m unittest discover -s + ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools -p + test_check_dfpt_failure.py) + set_tests_properties(dfpt_failure_validator PROPERTIES TIMEOUT 30) + foreach(failure_case displacement efield finite_q displacement_budget) + add_test( + NAME dfpt_failure_${failure_case} + COMMAND + ${LR_FORCE_TEST_PYTHON} + ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools/check_dfpt_failure.py + --abacus ${ABACUS_BIN_PATH} --fixture + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/dfpt_failure/${failure_case} + --pseudo-dir ${ABACUS_TEST_DIR}/PP_ORB) + set_tests_properties(dfpt_failure_${failure_case} PROPERTIES TIMEOUT 150 + PROCESSORS 1) + endforeach() add_test( NAME lr_force_collector COMMAND diff --git a/tests/integrate/fixtures/dfpt_failure/README.md b/tests/integrate/fixtures/dfpt_failure/README.md new file mode 100644 index 00000000000..e582e6639f6 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/README.md @@ -0,0 +1,23 @@ +# Expected response failures + +These fixed fixtures use the same small insulating Si cell and pseudopotential +as the existing Gamma regression. Their GS converges before response failure. +The explicit linear budget (120 steps, threshold 1e-10) is independent of the +one- or three-step outer budget. The three-step case detects redundant passes. + +`displacement` and `displacement_budget` fail the first Gamma displacement; +`efield` fails the first ordinary electric-field direction; `finite_q` fails +the first displacement at fractional q=(1/2,0,0). All use symmetry -1. +The finite-q fixture specifies its single Gamma k point as an explicit Direct +list. This preserves the ordinary displacement path when the uniform-mesh +response planner is enabled, without changing the sampled point or weight. + +The expected-failure driver copies each dedicated fixture unchanged into a +fresh temporary directory and stages its named pseudopotential under PP_ORB. +It requires exit 1, converged GS evidence, the exact failure task/budget in +stdout and warning.log, and no newly generated formal tensor/frequency or dyn +output. A crash, timeout or unrelated error is a test failure. + +These cases are registered separately because Autotest treats a nonzero exit +as failure. Normal numerical regressions remain Autotest cases. They do not +test reuse of old outputs; output-generation validation is separate work. diff --git a/tests/integrate/fixtures/dfpt_failure/displacement/INPUT b/tests/integrate/fixtures/dfpt_failure/displacement/INPUT new file mode 100644 index 00000000000..e8fd8624941 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 1 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 120 +dfpt_compute_q0 false +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/displacement/KPT b/tests/integrate/fixtures/dfpt_failure/displacement/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/displacement/QFILE b/tests/integrate/fixtures/dfpt_failure/displacement/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/displacement/STRU b/tests/integrate/fixtures/dfpt_failure/displacement/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/displacement/expected.json b/tests/integrate/fixtures/dfpt_failure/displacement/expected.json new file mode 100644 index 00000000000..b80230b4cdc --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement/expected.json @@ -0,0 +1,14 @@ +{ + "stage": "displacement", + "q_index": 0, + "iterations": 1, + "limit": 1, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.0, + 0.0, + 0.0 + ] +} diff --git a/tests/integrate/fixtures/dfpt_failure/displacement_budget/INPUT b/tests/integrate/fixtures/dfpt_failure/displacement_budget/INPUT new file mode 100644 index 00000000000..d8a2b8aa506 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement_budget/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 3 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 120 +dfpt_compute_q0 false +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/displacement_budget/KPT b/tests/integrate/fixtures/dfpt_failure/displacement_budget/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement_budget/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/displacement_budget/QFILE b/tests/integrate/fixtures/dfpt_failure/displacement_budget/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement_budget/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/displacement_budget/STRU b/tests/integrate/fixtures/dfpt_failure/displacement_budget/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement_budget/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/displacement_budget/expected.json b/tests/integrate/fixtures/dfpt_failure/displacement_budget/expected.json new file mode 100644 index 00000000000..3fbdb575409 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/displacement_budget/expected.json @@ -0,0 +1,14 @@ +{ + "stage": "displacement", + "q_index": 0, + "iterations": 3, + "limit": 3, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.0, + 0.0, + 0.0 + ] +} diff --git a/tests/integrate/fixtures/dfpt_failure/efield/INPUT b/tests/integrate/fixtures/dfpt_failure/efield/INPUT new file mode 100644 index 00000000000..9effda68a35 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/efield/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 1 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 120 +dfpt_compute_q0 true +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/efield/KPT b/tests/integrate/fixtures/dfpt_failure/efield/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/efield/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/efield/QFILE b/tests/integrate/fixtures/dfpt_failure/efield/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/efield/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/efield/STRU b/tests/integrate/fixtures/dfpt_failure/efield/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/efield/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/efield/expected.json b/tests/integrate/fixtures/dfpt_failure/efield/expected.json new file mode 100644 index 00000000000..57d8fc33628 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/efield/expected.json @@ -0,0 +1,14 @@ +{ + "stage": "efield", + "q_index": 0, + "iterations": 1, + "limit": 1, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.0, + 0.0, + 0.0 + ] +} diff --git a/tests/integrate/fixtures/dfpt_failure/finite_q/INPUT b/tests/integrate/fixtures/dfpt_failure/finite_q/INPUT new file mode 100644 index 00000000000..e8fd8624941 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/finite_q/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 1 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 120 +dfpt_compute_q0 false +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/finite_q/KPT b/tests/integrate/fixtures/dfpt_failure/finite_q/KPT new file mode 100644 index 00000000000..795cfeadd7e --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/finite_q/KPT @@ -0,0 +1,4 @@ +K_POINTS +1 +Direct +0 0 0 1.0 diff --git a/tests/integrate/fixtures/dfpt_failure/finite_q/QFILE b/tests/integrate/fixtures/dfpt_failure/finite_q/QFILE new file mode 100644 index 00000000000..aa9a2a2065f --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/finite_q/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0.5 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/finite_q/STRU b/tests/integrate/fixtures/dfpt_failure/finite_q/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/finite_q/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/finite_q/expected.json b/tests/integrate/fixtures/dfpt_failure/finite_q/expected.json new file mode 100644 index 00000000000..8e1af32bb6c --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/finite_q/expected.json @@ -0,0 +1,14 @@ +{ + "stage": "displacement", + "q_index": 0, + "iterations": 1, + "limit": 1, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.5, + 0.0, + 0.0 + ] +} diff --git a/tests/integrate/validation_tools/check_dfpt_failure.py b/tests/integrate/validation_tools/check_dfpt_failure.py new file mode 100644 index 00000000000..8441e5f4e08 --- /dev/null +++ b/tests/integrate/validation_tools/check_dfpt_failure.py @@ -0,0 +1,99 @@ +"""Verify expected DFPT outer failures using the real executable. + +Autotest treats any nonzero exit as a regression. This driver instead checks +the expected exit, converged GS, precise response diagnostic and fresh output. +""" + +import argparse +import json +import math +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +FAILURE = re.compile( + r"DFPT response failure: stage=(\w+) q_index=(\d+)" + r"(?: atom=(\d+))? direction=([xyz]) iterations=(\d+) limit=(\d+)" + r" residual=(\S+) threshold=(\S+) q_direct=\(([^)]+)\)" +) + + +def validate_failure(returncode, stdout, warning, running, products, expected): + """Reject unrelated exits, successful results and ambiguous diagnostics.""" + if returncode != 1: + raise AssertionError("Expected exit 1, got {}".format(returncode)) + if "#SCF IS CONVERGED#" not in running: + raise AssertionError("Ground-state SCF did not converge") + for label, text in (("stdout", stdout), ("warning.log", warning)): + matches = FAILURE.findall(text) + if len(matches) != 1: + raise AssertionError("Expected exactly one response failure in " + label) + stage, qi, atom, direction, iterations, limit, residual, threshold, q = matches[0] + if stage != expected["stage"] or int(qi) != expected["q_index"]: + raise AssertionError("Failure occurred in the wrong response task") + if direction != "x" or (stage == "displacement" and atom != "1"): + raise AssertionError("The first failed response was not stopped") + if int(iterations) != expected["iterations"] or int(limit) != expected["limit"]: + raise AssertionError("Unexpected iteration budget") + value, tolerance = float(residual), float(threshold) + if not math.isfinite(value) or not math.isfinite(tolerance): + raise AssertionError("Expected a finite iteration-limit residual") + if tolerance <= 0 or value < tolerance: + raise AssertionError("The reported response already met its threshold") + if [float(component) for component in q.split(",")] != expected["q_direct"]: + raise AssertionError("Wrong physical q in failure diagnostic") + trace = r"DFPT mix iter=" if expected["stage"] == "displacement" else None + if trace and len(re.findall(trace, stdout)) != expected["iterations"]: + raise AssertionError("Response solves were repeated after exhausting the budget") + for marker in ("DFPT phonon frequencies at q #", "DFPT dielectric tensor (epsilon_inf):", + "DFPT Born effective charge atom", "DFPT LO-TO corrected frequencies"): + if marker in stdout: + raise AssertionError("Formal results were printed after response failure") + if products: + raise AssertionError("Dynamical matrices were written: " + str(products)) + + +def run_case(executable, fixture, pseudo_dir, timeout): + expected = json.loads((fixture / "expected.json").read_text()) + with tempfile.TemporaryDirectory(prefix="abacus-dfpt-failure-") as scratch: + work = Path(scratch) + for name in ("INPUT", "STRU", "KPT", "QFILE"): + shutil.copy2(fixture / name, work / name) + (work / "PP_ORB").mkdir() + for name in expected["pseudopotentials"]: + if Path(name).name != name: + raise ValueError("Pseudopotential must be a basename") + shutil.copy2(pseudo_dir / name, work / "PP_ORB" / name) + env = dict(os.environ, OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1") + result = subprocess.run( + [str(executable)], cwd=str(work), env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, universal_newlines=True, timeout=timeout, + check=False, + ) + out = work / "OUT.autotest" + warning = (out / "warning.log").read_text() + running = (out / "running_scf.log").read_text() + try: + validate_failure(result.returncode, result.stdout, warning, running, + sorted(path.name for path in out.glob("dyn.q*")), expected) + except AssertionError as error: + raise AssertionError(str(error) + "\n" + result.stdout + "\n" + warning) + print("Verified expected DFPT failure: " + fixture.name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--abacus", required=True, type=Path) + parser.add_argument("--fixture", required=True, type=Path) + parser.add_argument("--pseudo-dir", required=True, type=Path) + parser.add_argument("--timeout", type=float, default=120) + args = parser.parse_args() + run_case(args.abacus.resolve(), args.fixture.resolve(), args.pseudo_dir.resolve(), args.timeout) + + +if __name__ == "__main__": + main() diff --git a/tests/integrate/validation_tools/test_check_dfpt_failure.py b/tests/integrate/validation_tools/test_check_dfpt_failure.py new file mode 100644 index 00000000000..48d0498905e --- /dev/null +++ b/tests/integrate/validation_tools/test_check_dfpt_failure.py @@ -0,0 +1,61 @@ +"""Guard against false positives in the expected-response-failure driver.""" + +import unittest + +from check_dfpt_failure import validate_failure + + +class FailureAuditTest(unittest.TestCase): + def setUp(self): + self.expected = {"stage": "displacement", "q_index": 0, "iterations": 1, + "limit": 1, "q_direct": [0, 0, 0]} + self.message = ("DFPT response failure: stage=displacement q_index=0 atom=1 " + "direction=x iterations=1 limit=1 residual=1.000000e+00 " + "threshold=1.000000e-08 q_direct=(0,0,0)") + self.stdout = "DFPT mix iter= 1/1\n" + self.message + self.running = "#SCF IS CONVERGED#" + + def check(self, **changes): + args = dict(returncode=1, stdout=self.stdout, warning=self.message, + running=self.running, products=[], expected=self.expected) + args.update(changes) + validate_failure(**args) + + def test_expected_failure(self): + self.check() + + def test_success_and_crashes_are_not_expected_failure(self): + for code in (0, -11, 2): + with self.subTest(code=code), self.assertRaises(AssertionError): + self.check(returncode=code) + + def test_unconverged_ground_state_is_rejected(self): + with self.assertRaises(AssertionError): + self.check(running="SCF NOT CONVERGED") + + def test_wrong_stage_and_physical_q_are_rejected(self): + for text in (self.message.replace("stage=displacement", "stage=efield"), + self.message.replace("q_direct=(0,0,0)", "q_direct=(0.5,0,0)")): + with self.subTest(text=text), self.assertRaises(AssertionError): + self.check(warning=text) + + def test_stale_matrix_and_formal_output_are_rejected(self): + with self.assertRaises(AssertionError): + self.check(products=["dyn.q0"]) + with self.assertRaises(AssertionError): + self.check(stdout=self.stdout + "\nDFPT phonon frequencies at q #0") + + def test_repeated_solves_and_diagnostics_are_rejected(self): + with self.assertRaises(AssertionError): + self.check(stdout=self.stdout + "\nDFPT mix iter= 1/1") + with self.assertRaises(AssertionError): + self.check(warning=self.message + "\n" + self.message) + + def test_acceptable_and_nonfinite_residuals_are_rejected(self): + for residual in ("1e-12", "nan", "inf"): + with self.subTest(residual=residual), self.assertRaises(AssertionError): + self.check(warning=self.message.replace("1.000000e+00", residual)) + + +if __name__ == "__main__": + unittest.main() From ff2b5002600440129026b8421c3a865236af31f4 Mon Sep 17 00:00:00 2001 From: Zanthoxylum <105619360+Zanthoxylum@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:36:36 +0800 Subject: [PATCH 2/4] fix(dfpt): validate required inner response solves Summary Return explicit projected linear-solve status and verify the true residual of the returned solution. Distinguish homogeneous zero-step success from invalid sizes, non-finite values, iteration limits, breakdown and norm underflow. Design Every required displacement, position and electric-field solve is checked before response consumption. The legacy adapter also rejects failures instead of losing status. Missing response legs/projectors cannot be silently skipped. Keep nonpositive finite threshold inheritance; non-finite settings remain invalid. Missing mixing residuals cannot imply convergence. No retry is added. Verification Rebuilt main and all eleven DFPT unit targets. CTest 20/20, default Gamma Autotest 8/8, all six exact anchor strings unchanged. Three independent successful control dyn files remain byte-identical to the C1 archive. Seven real failure cases stop at their expected inner/outer stage without formal products. CLI help and --check-input pass. DFPT/CMake formatting passes; only changed INPUT description snippets outside DFPT were formatted. Tests Analytic final-step success, zero projected RHS, insufficient budget, malformed dimensions/parameters, nonfinite data, negative curvature, adapter propagation and norm underflow. Governance has no ERROR; four standard-header warnings are required by the public string API and inline finite/norm checks. --- .../elec_properties/dfpt_convergence.md | 8 + .../module_parameter/read_inp_dfpt.cpp | 49 ++-- source/source_pw/module_dfpt/CMakeLists.txt | 1 + .../source_pw/module_dfpt/dfpt_convergence.h | 24 ++ source/source_pw/module_dfpt/dfpt_pw.cpp | 47 ++++ source/source_pw/module_dfpt/dfpt_pw_data.h | 10 +- source/source_pw/module_dfpt/dfpt_pw_impl.h | 15 ++ source/source_pw/module_dfpt/dfpt_pw_q0.cpp | 18 +- .../source_pw/module_dfpt/dfpt_pw_solve.cpp | 42 +--- source/source_pw/module_dfpt/dfpt_rho_mix.cpp | 33 +-- source/source_pw/module_dfpt/dfpt_stern.cpp | 220 +++++++++++++++--- source/source_pw/module_dfpt/dfpt_stern.h | 44 +++- .../module_dfpt/unittests/CMakeLists.txt | 6 +- .../unittests/test_dfpt_convergence.cpp | 20 ++ .../unittests/test_dfpt_stern_status.cpp | 140 +++++++++++ tests/integrate/CMakeLists.txt | 10 +- .../integrate/fixtures/dfpt_failure/README.md | 8 +- .../dfpt_failure/inner_displacement/INPUT | 24 ++ .../dfpt_failure/inner_displacement/KPT | 4 + .../dfpt_failure/inner_displacement/QFILE | 4 + .../dfpt_failure/inner_displacement/STRU | 19 ++ .../inner_displacement/expected.json | 15 ++ .../dfpt_failure/inner_finite_q/INPUT | 24 ++ .../fixtures/dfpt_failure/inner_finite_q/KPT | 4 + .../dfpt_failure/inner_finite_q/QFILE | 4 + .../fixtures/dfpt_failure/inner_finite_q/STRU | 19 ++ .../dfpt_failure/inner_finite_q/expected.json | 15 ++ .../dfpt_failure/inner_position/INPUT | 24 ++ .../fixtures/dfpt_failure/inner_position/KPT | 4 + .../dfpt_failure/inner_position/QFILE | 4 + .../fixtures/dfpt_failure/inner_position/STRU | 19 ++ .../dfpt_failure/inner_position/expected.json | 15 ++ .../validation_tools/check_dfpt_failure.py | 73 ++++-- .../test_check_dfpt_failure.py | 30 +++ 34 files changed, 840 insertions(+), 156 deletions(-) create mode 100644 source/source_pw/module_dfpt/dfpt_convergence.h create mode 100644 source/source_pw/module_dfpt/unittests/test_dfpt_convergence.cpp create mode 100644 source/source_pw/module_dfpt/unittests/test_dfpt_stern_status.cpp create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_displacement/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_displacement/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_displacement/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_displacement/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_displacement/expected.json create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_finite_q/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_finite_q/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_finite_q/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_finite_q/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_finite_q/expected.json create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_position/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_position/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_position/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_position/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/inner_position/expected.json diff --git a/docs/advanced/elec_properties/dfpt_convergence.md b/docs/advanced/elec_properties/dfpt_convergence.md index 50f4ea44c49..e9c2af1b25f 100644 --- a/docs/advanced/elec_properties/dfpt_convergence.md +++ b/docs/advanced/elec_properties/dfpt_convergence.md @@ -19,6 +19,14 @@ limit, final residual and threshold. It is available in stdout and `OUT./warning.log`. q indices retain the existing zero-based output convention; the diagnostic atom index is one-based. +Every required inner solve must also satisfy its effective linear threshold. +The returned projected solution is checked against the true residual +`||P_c(b - A*dpsi)|| / ||P_c b||`. An iteration limit, invalid dimensions or +effective parameters, non-finite numerical data, or operator breakdown stops +the response before consumption. A valid homogeneous projected system may +converge in zero steps. Position responses use the same checks before the +related dielectric tensor and Born charges are computed. + The checks described here concern outer response self-consistency. They do not establish convergence with respect to basis cutoffs or sampling. A converged imaginary phonon frequency can describe structural instability and diff --git a/source/source_io/module_parameter/read_inp_dfpt.cpp b/source/source_io/module_parameter/read_inp_dfpt.cpp index e7ca72abb41..3df55913b20 100644 --- a/source/source_io/module_parameter/read_inp_dfpt.cpp +++ b/source/source_io/module_parameter/read_inp_dfpt.cpp @@ -189,25 +189,16 @@ void ReadInput::item_dfpt() item.annotation = "convergence threshold of the inner Sternheimer linear solve"; item.category = category; item.type = "Real"; - item.description = "Dedicated convergence threshold of the projected CG solve of the " - "Sternheimer equation inside every DFPT response iteration, as the " - "relative residual ||P_c r|| / ||P_c b|| of the projected system " - "(r: CG residual, b: projected right-hand side, P_c: complement of " - "the occupied subspace at k+q). Non-positive values (the default) " - "inherit dfpt_conv_thr, which reproduces the historical " - "single-knob behavior. Accuracy tradeoff of truncating the inner " - "solve: the outer mixing residual does NOT check the achieved " - "Sternheimer residual, so a loose inner threshold or a small " - "dfpt_lin_max_iter can shift converged observables; the same " - "controls also affect the one-shot Gamma position response (the " - "bare q = 0 operator legs inherit them as well). When the knobs " - "are tightened for a hard response, validate the phonons, " - "dielectric tensor and Born charges against tighter inner " - "settings to quantify the truncation error. Decouple them when a " - "flat semicore band system needs a loose inner solve to keep the " - "outer mixing stable: the shifted operator is then near-singular " - "and a very deep inner solve amplifies the response beyond what " - "the outer mixing can damp."; + item.description = "Required relative residual threshold of the projected Sternheimer " + "linear solve, ||P_c(b-A*dpsi)|| / ||P_c b||, checked on the final " + "projected solution. Finite non-positive values (the default) " + "inherit dfpt_conv_thr. Every required displacement, electric-field " + "and Gamma position response must satisfy its effective threshold; " + "an unsuccessful inner solve terminates before its response is " + "consumed, even if the outer density or potential changes little. " + "Convergence of observables with respect to this threshold remains " + "a separate accuracy check. No automatic threshold relaxation or " + "retry is performed."; item.default_value = "-1.0 (inherit dfpt_conv_thr)"; read_sync_double(input.dfpt_lin_conv_thr); this->add_item(item); @@ -217,18 +208,14 @@ void ReadInput::item_dfpt() item.annotation = "iteration cap of the inner Sternheimer linear solve"; item.category = category; item.type = "Integer"; - item.description = "Dedicated iteration cap of the projected CG solve of the " - "Sternheimer equation inside every DFPT response iteration. " - "Non-positive values (the default) inherit dfpt_max_iter, which " - "reproduces the historical single-knob behavior. Lower it to " - "truncate the CG before it drives into near-singular directions of " - "a flat-band system; raise it for otherwise unconverged inner " - "solves without enlarging the outer mixing budget. The cap has the " - "same accuracy tradeoff as dfpt_lin_conv_thr: the outer mixing " - "residual does not check the achieved Sternheimer residual, the " - "one-shot Gamma position response shares the cap, and truncated " - "inner solves should be validated against tighter settings on the " - "phonons, dielectric tensor and Born charges."; + item.description = "Iteration budget of each projected Sternheimer linear solve, " + "including the Gamma position response. Non-positive values (the " + "default) inherit dfpt_max_iter. A required inner solve that does " + "not satisfy dfpt_lin_conv_thr within this budget terminates with " + "a nonzero exit status before response consumption. Success on " + "the final allowed iteration is valid; the iteration count alone " + "does not determine failure. This budget is distinct from outer " + "response iterations and is not multiplied by implicit retries."; item.default_value = "0 (inherit dfpt_max_iter)"; read_sync_int(input.dfpt_lin_max_iter); this->add_item(item); diff --git a/source/source_pw/module_dfpt/CMakeLists.txt b/source/source_pw/module_dfpt/CMakeLists.txt index e46557bf9f1..d978905a3f9 100644 --- a/source/source_pw/module_dfpt/CMakeLists.txt +++ b/source/source_pw/module_dfpt/CMakeLists.txt @@ -32,6 +32,7 @@ set(HEADERS dfpt_pw_data.h dfpt_kq_basis.h dfpt_pert.h + dfpt_convergence.h dfpt_stern.h dfpt_nscf.h dfpt_rho.h diff --git a/source/source_pw/module_dfpt/dfpt_convergence.h b/source/source_pw/module_dfpt/dfpt_convergence.h new file mode 100644 index 00000000000..1a2f1ad60fd --- /dev/null +++ b/source/source_pw/module_dfpt/dfpt_convergence.h @@ -0,0 +1,24 @@ +#ifndef DFPT_CONVERGENCE_H +#define DFPT_CONVERGENCE_H + +#include +#include + +namespace ModuleDFPT +{ +/// Relative fixed-point defect; absent or invalid norms never mean success. +inline double response_relative_residual(double defect_squared, double output_squared) +{ + if (!std::isfinite(defect_squared) || !std::isfinite(output_squared) || defect_squared < 0.0 || + output_squared < 0.0) + { + return std::numeric_limits::infinity(); + } + if (output_squared == 0.0) + { + return defect_squared == 0.0 ? 0.0 : std::numeric_limits::infinity(); + } + return std::sqrt(defect_squared / output_squared); +} +} // namespace ModuleDFPT +#endif diff --git a/source/source_pw/module_dfpt/dfpt_pw.cpp b/source/source_pw/module_dfpt/dfpt_pw.cpp index a643ed3d369..871c3b933ff 100644 --- a/source/source_pw/module_dfpt/dfpt_pw.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw.cpp @@ -13,6 +13,7 @@ #include "source_base/constants.h" #include "source_base/global_function.h" #include "source_base/timer.h" +#include "source_base/tool_quit.h" #include "source_base/tool_title.h" #include "source_cell/qlist.h" #include "source_cell/stru_fac.h" @@ -36,6 +37,52 @@ DFPT_PW::Impl::~Impl() {} bool DFPT_PW::Impl::wired() const { return pw_rho_ != nullptr && pw_wfc_ != nullptr; } +std::string DFPT_PW::Impl::response_context( + const char *stage, + int ik, + int ib, + int direction) const +{ + const ModuleBase::Vector3 q = data_.get_qvec(last_q_); + std::ostringstream context; + context << "stage=" << stage << " q_index=" << last_q_ << " q_direct=(" << q.x << "," << q.y << "," << q.z + << ") direction=" << static_cast('x' + direction) << " k_index=" << ik << " band_index=" << ib; + if (std::string(stage) == "displacement_inner") + { + context << " atom=" << data_.get_pert_atom() + 1; + } + return context.str(); +} + +void DFPT_PW::Impl::require_projector(int q_idx, int ik) const +{ + const int required = occupied_band_count(ik); + if (required > 0 && (ik >= static_cast(occ_kq_.size()) || static_cast(occ_kq_[ik].size()) != required)) + { + std::ostringstream message; + message << "DFPT response failure: stage=projector q_index=" << q_idx << " k_index=" << ik + << " reason=InvalidInput missing occupied states"; + ModuleBase::WARNING_QUIT("DFPT_PW", message.str()); + } +} + +double DFPT_PW::Impl::solve_linear_response( + const char *stage, + int ik, + int ib, + int direction, + int lin_max, + double lin_thr, + const std::vector> &rhs, + std::vector> &solution) +{ + hamilt_->set_shift(eig_(ik, ib)); + const DFPT_Stern::Result result = stern_.solve_report(*hamilt_, occ_kq_[ik], rhs, lin_max, lin_thr, solution); + const std::string context = response_context(stage, ik, ib, direction); + DFPT_Stern::require_converged(result, context); + return result.residual; +} + DFPT_PW::DFPT_PW() : pimpl_(std::unique_ptr(new Impl())) {} DFPT_PW::~DFPT_PW() {} diff --git a/source/source_pw/module_dfpt/dfpt_pw_data.h b/source/source_pw/module_dfpt/dfpt_pw_data.h index 9bc7352ab8e..e9bf1c6e328 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_data.h +++ b/source/source_pw/module_dfpt/dfpt_pw_data.h @@ -7,6 +7,7 @@ #include "source_cell/qlist.h" #include "source_psi/psi.h" +#include #include #include #include @@ -161,7 +162,14 @@ class DFPT_PW_Data void set_lin_max_iter(int iter) { lin_max_iter_ = iter; } int get_lin_max_iter() const { return lin_max_iter_ > 0 ? lin_max_iter_ : max_iter_; } void set_lin_conv_thr(double thr) { lin_conv_thr_ = thr; } - double get_lin_conv_thr() const { return lin_conv_thr_ > 0.0 ? lin_conv_thr_ : conv_thr_; } + double get_lin_conv_thr() const + { + if (std::isfinite(lin_conv_thr_) && lin_conv_thr_ <= 0.0) + { + return conv_thr_; + } + return lin_conv_thr_; + } /// Per-(q, irrep) SCF convergence ledger (B4: sunk from the retired /// DFPT_IrrepData adapter). The irrep dimension is a stage-A slot: diff --git a/source/source_pw/module_dfpt/dfpt_pw_impl.h b/source/source_pw/module_dfpt/dfpt_pw_impl.h index 360e751a1f4..7541d8525e5 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_impl.h +++ b/source/source_pw/module_dfpt/dfpt_pw_impl.h @@ -106,6 +106,21 @@ class DFPT_PW::Impl void run_assemble(int q_idx); // ----- solve_displacement helpers (dfpt_pw_solve.cpp) ----- + void require_projector(int q_idx, int ik) const; + std::string response_context( + const char *stage, + int ik, + int ib, + int direction) const; + double solve_linear_response( + const char *stage, + int ik, + int ib, + int direction, + int lin_max, + double lin_thr, + const std::vector> &rhs, + std::vector> &solution); double sternheimer_per_band( int ik, int ib, diff --git a/source/source_pw/module_dfpt/dfpt_pw_q0.cpp b/source/source_pw/module_dfpt/dfpt_pw_q0.cpp index 8b4fc486706..0965882e061 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_q0.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_q0.cpp @@ -176,9 +176,7 @@ void DFPT_PW::Impl::pos_per_band_solve( { rhs[ig] = fac * vel[ib][ig]; } - hamilt_->set_shift(eig_(ik, ib)); - double res = 0.0; - stern_.solve(*hamilt_, occ_kq_[ik], rhs, lin_max, lin_thr, yvec[ik][ib], res); + const double res = solve_linear_response("position", ik, ib, a, lin_max, lin_thr, rhs, yvec[ik][ib]); if (dbg) { std::cout << "DBG posresp a=" << a << " ik=" << ik << " ib=" << ib << " eps=" << eig_(ik, ib) @@ -196,7 +194,6 @@ void DFPT_PW::Impl::efield_per_band_solve( const std::vector>>> &yr, const std::vector>> &dv_sc) { - (void)a; // used only by caller-index semantics, kept future-proof for (int ib = 0; ib < nbands; ++ib) { if (!dfpt_band_occupied(wg_, ik, ib)) @@ -205,19 +202,18 @@ void DFPT_PW::Impl::efield_per_band_solve( } if (yr[ik][ib].empty() || static_cast(dv_sc.size()) != nbands || yr[ik][ib].size() != dv_sc[ib].size()) { - continue; + const std::string context = response_context("efield_inner", ik, ib, a); + ModuleBase::WARNING_QUIT( + "DFPT_PW", "DFPT response failure: " + context + " reason=InvalidInput missing response leg"); } std::vector> rhs(yr[ik][ib].size()); for (size_t i = 0; i < rhs.size(); ++i) { rhs[i] = -(yr[ik][ib][i] + dv_sc[ib][i]); } - hamilt_->set_shift(eig_(ik, ib)); std::vector> dpsi_out; - double res = 0.0; - stern_.solve(*hamilt_, occ_kq_[ik], rhs, lin_max, lin_thr, dpsi_out, res); + solve_linear_response("efield_inner", ik, ib, a, lin_max, lin_thr, rhs, dpsi_out); data_.set_dpsi(last_q_, ik, ib, dpsi_out); - (void)res; // convergence is aggregated via drho residual, not per-band stern_ } } @@ -271,7 +267,8 @@ void DFPT_PW::Impl::solve_pos_resp(int q_idx) nk, std::vector>>(nbands)); for (int ik = 0; ik < nk; ++ik) { - if (occ_kq_[ik].empty()) + require_projector(q_idx, ik); + if (ik >= static_cast(occ_kq_.size()) || occ_kq_[ik].empty()) { continue; // matches the displacement solve guard } @@ -331,6 +328,7 @@ void DFPT_PW::Impl::solve_efield_resp(int q_idx) assemble_v_sc(q_idx, q_cart, drho_in_g, v_sc_r); for (int ik = 0; ik < nk; ++ik) { + require_projector(q_idx, ik); if (static_cast(occ_kq_.size()) <= ik || occ_kq_[ik].empty()) { continue; diff --git a/source/source_pw/module_dfpt/dfpt_pw_solve.cpp b/source/source_pw/module_dfpt/dfpt_pw_solve.cpp index 3bd90f85cc6..75d5cda4e0e 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_solve.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_solve.cpp @@ -10,6 +10,7 @@ #include "dfpt_pw_impl.h" +#include "dfpt_convergence.h" #include "dfpt_pw_data.h" #include "source_base/parallel_reduce.h" #include "source_base/timer.h" @@ -28,26 +29,6 @@ namespace ModuleDFPT { -namespace -{ -/// relative defect ||out - in|| / ||out|| with convergence-safe guards -/// (shared definition with dfpt_rho_mix.cpp; see the note there): a zero -/// output norm only reports convergence when the defect itself is zero, -/// and non-finite norms never report convergence -double safe_relative_defect(double dn2, double o2) -{ - if (!std::isfinite(dn2) || !std::isfinite(o2)) - { - return std::numeric_limits::max(); - } - if (o2 <= 0.0) - { - return (dn2 <= 0.0) ? 0.0 : std::numeric_limits::max(); - } - return std::sqrt(dn2 / o2); -} -} // namespace - void DFPT_PW::Impl::assemble_v_sc( int q_idx, const ModuleBase::Vector3 &q_cart, @@ -125,23 +106,17 @@ double DFPT_PW::Impl::sternheimer_per_band( const bool dbg = (getenv("DFPT_DEBUG") != nullptr); if (rhs.empty() || static_cast(dv_sc.size()) != nbands || rhs.size() != dv_sc[ib].size()) { - if (dbg) - { - std::cout << "DBG skip solve ik=" << ik << " ib=" << ib << " rhs.size=" << rhs.size() - << " dv_sc.size=" << dv_sc.size() - << " dv_sc[ib].size=" << (dv_sc.size() > static_cast(ib) ? dv_sc[ib].size() : 999999) - << std::endl; - } - return 0.0; + const std::string context = response_context("displacement_inner", ik, ib, data_.get_pert_dir()); + ModuleBase::WARNING_QUIT( + "DFPT_PW", "DFPT response failure: " + context + " reason=InvalidInput missing response leg"); } for (size_t i = 0; i < rhs.size(); ++i) { rhs[i] = -(rhs[i] + dv_sc[ib][i]); } - hamilt_->set_shift(eig_(ik, ib)); std::vector> dpsi_out; - double res = 0.0; - stern_.solve(*hamilt_, occ_kq_[ik], rhs, lin_max, lin_thr, dpsi_out, res); + const int direction = data_.get_pert_dir(); + const double res = solve_linear_response("displacement_inner", ik, ib, direction, lin_max, lin_thr, rhs, dpsi_out); if (dbg) { double nr = 0.0; @@ -323,6 +298,7 @@ double DFPT_PW::Impl::solve_displacement(int q_idx, int iat, int idir) for (int ik = 0; ik < nk; ++ik) { + require_projector(q_idx, ik); if (static_cast(occ_kq_.size()) <= ik || occ_kq_[ik].empty()) { if (dbg) @@ -406,7 +382,7 @@ double DFPT_PW::Impl::solve_displacement(int q_idx, int iat, int idir) Parallel_Reduce::reduce_pool(dn2); Parallel_Reduce::reduce_pool(o2); #endif - residual = safe_relative_defect(dn2, o2); + residual = response_relative_residual(dn2, o2); vsc_broyden_->mix_data(*vsc_broyden_mdata_, v_sc_in_r.data()); } else @@ -426,7 +402,7 @@ double DFPT_PW::Impl::solve_displacement(int q_idx, int iat, int idir) Parallel_Reduce::reduce_pool(dn2); Parallel_Reduce::reduce_pool(o2); #endif - residual = safe_relative_defect(dn2, o2); + residual = response_relative_residual(dn2, o2); } // the 2n+1 accumulation path reads the density from data_: // unlike the density-mixing branch, the v_sc loop never calls diff --git a/source/source_pw/module_dfpt/dfpt_rho_mix.cpp b/source/source_pw/module_dfpt/dfpt_rho_mix.cpp index 5f7c291ca48..4294b048d7c 100644 --- a/source/source_pw/module_dfpt/dfpt_rho_mix.cpp +++ b/source/source_pw/module_dfpt/dfpt_rho_mix.cpp @@ -6,6 +6,7 @@ // (compute_drho / drhoc / v_hartree_q) stay in dfpt_rho.cpp. // ============================================================ +#include "dfpt_convergence.h" #include "dfpt_pw_data.h" #include "dfpt_rho.h" @@ -24,26 +25,6 @@ namespace ModuleDFPT { -namespace -{ -/// relative defect ||out - in|| / ||out|| with convergence-safe guards: -/// a zero output norm only reports convergence when the defect itself is -/// zero (v_out = 1 - c v_in maps a nonzero input to zero far from -/// its fixed point), and non-finite norms never report convergence -double safe_relative_defect(double dn2, double o2) -{ - if (!std::isfinite(dn2) || !std::isfinite(o2)) - { - return std::numeric_limits::max(); - } - if (o2 <= 0.0) - { - return (dn2 <= 0.0) ? 0.0 : std::numeric_limits::max(); - } - return std::sqrt(dn2 / o2); -} -} // namespace - void DFPT_Rho::reset_mixing(int q_idx) { ModuleBase::TITLE("DFPT_Rho", "reset_mixing"); @@ -59,7 +40,7 @@ void DFPT_Rho::reset_mixing(int q_idx) } if (q_idx < static_cast(residual_.size())) { - residual_[q_idx] = 0.0; + residual_[q_idx] = std::numeric_limits::infinity(); } // Broyden history is per (q, displacement-cycle): drop it so the next // displacement starts fresh @@ -83,6 +64,10 @@ void DFPT_Rho::mix_drho(int q_idx, DFPT_PW_Data &data) { ModuleBase::TITLE("DFPT_Rho", "mix_drho"); ModuleBase::timer::start("DFPT_Rho", "mix_drho"); + if (q_idx >= 0 && q_idx < static_cast(residual_.size())) + { + residual_[q_idx] = std::numeric_limits::infinity(); + } if (mixer_ == nullptr || pw_rho_ == nullptr) { ModuleBase::timer::end("DFPT_Rho", "mix_drho"); @@ -98,7 +83,7 @@ void DFPT_Rho::mix_drho(int q_idx, DFPT_PW_Data &data) if (q_idx >= static_cast(drho_in_.size())) { drho_in_.resize(q_idx + 1); - residual_.resize(q_idx + 1, 0.0); + residual_.resize(q_idx + 1, std::numeric_limits::infinity()); } // first iteration starts from a zero input density if (drho_in_[q_idx].empty()) @@ -208,7 +193,7 @@ void DFPT_Rho::mix_drho(int q_idx, DFPT_PW_Data &data) Parallel_Reduce::reduce_pool(dn2); Parallel_Reduce::reduce_pool(o2); #endif - residual_[q_idx] = safe_relative_defect(dn2, o2); + residual_[q_idx] = response_relative_residual(dn2, o2); drho_in_[q_idx][0] = mixed; data.set_drho_g(q_idx, 0, mixed); @@ -229,7 +214,7 @@ double DFPT_Rho::get_residual(int q_idx, DFPT_PW_Data &data) const if (q_idx < 0 || q_idx >= static_cast(residual_.size())) { ModuleBase::timer::end("DFPT_Rho", "get_residual"); - return 0.0; + return std::numeric_limits::infinity(); } ModuleBase::timer::end("DFPT_Rho", "get_residual"); return residual_[q_idx]; diff --git a/source/source_pw/module_dfpt/dfpt_stern.cpp b/source/source_pw/module_dfpt/dfpt_stern.cpp index b309018d9e9..e7a68768e51 100644 --- a/source/source_pw/module_dfpt/dfpt_stern.cpp +++ b/source/source_pw/module_dfpt/dfpt_stern.cpp @@ -1,8 +1,12 @@ #include "dfpt_stern.h" #include "source_base/timer.h" +#include "source_base/tool_quit.h" #include "source_base/tool_title.h" #include +#include +#include +#include namespace ModuleDFPT { @@ -29,6 +33,18 @@ double real_vdot(const std::vector> &a, const std::vector> &values) +{ + for (const std::complex &value : values) + { + if (!std::isfinite(value.real()) || !std::isfinite(value.imag())) + { + return false; + } + } + return true; +} + } // namespace void DFPT_Stern::apply_pv( @@ -61,6 +77,61 @@ void DFPT_Stern::apply_pv( ModuleBase::timer::end("DFPT_Stern", "apply_pv"); } +const char *DFPT_Stern::status_name(Status status) +{ + switch (status) + { + case Status::Converged: + return "Converged"; + case Status::IterationLimit: + return "IterationLimit"; + case Status::InvalidInput: + return "InvalidInput"; + case Status::NonFinite: + return "NonFinite"; + case Status::Breakdown: + return "Breakdown"; + } + return "InvalidInput"; +} + +void DFPT_Stern::require_converged(const Result &result, const std::string &context) +{ + if (result.status == Status::Converged && result.residual_available && std::isfinite(result.residual) && + result.residual >= 0.0 && std::isfinite(result.threshold) && result.threshold > 0.0 && + result.residual < result.threshold) + { + return; + } + Status reason = result.status; + if (reason == Status::Converged) + { + reason = Status::InvalidInput; + } + std::ostringstream message; + message << "DFPT response failure: " << context << " reason=" << status_name(reason) + << " iterations=" << result.iterations << " limit=" << result.limit << " residual="; + if (result.residual_available && std::isfinite(result.residual)) + { + message << std::scientific << std::setprecision(6) << result.residual; + } + else + { + message << "unavailable"; + } + message << " threshold="; + if (std::isfinite(result.threshold)) + { + message << result.threshold; + } + else + { + message << "unavailable"; + } + message << ". Stopping before response consumption."; + ModuleBase::WARNING_QUIT("DFPT_Stern", message.str()); +} + int DFPT_Stern::solve( const LinearOperator &aop, const std::vector>> &occ_kq, @@ -70,92 +141,179 @@ int DFPT_Stern::solve( std::vector> &dpsi, double &residual) const { - ModuleBase::TITLE("DFPT_Stern", "solve"); - ModuleBase::timer::start("DFPT_Stern", "solve"); + const Result result = solve_report(aop, occ_kq, b, max_iter, conv_thr, dpsi); + require_converged(result, "stage=linear"); + residual = result.residual; + return result.iterations; +} + +DFPT_Stern::Result DFPT_Stern::solve_report( + const LinearOperator &aop, + const std::vector>> &occ_kq, + const std::vector> &b, + int max_iter, + double conv_thr, + std::vector> &dpsi) const +{ + ModuleBase::TITLE("DFPT_Stern", "solve_report"); + ModuleBase::timer::start("DFPT_Stern", "solve_report"); + const Result result = solve_impl(aop, occ_kq, b, max_iter, conv_thr, dpsi); + ModuleBase::timer::end("DFPT_Stern", "solve_report"); + return result; +} + +DFPT_Stern::Result DFPT_Stern::solve_impl( + const LinearOperator &aop, + const std::vector>> &occ_kq, + const std::vector> &b, + int max_iter, + double conv_thr, + std::vector> &dpsi) const +{ + Result result{Status::InvalidInput, 0, max_iter, conv_thr, false, std::numeric_limits::infinity()}; + dpsi.clear(); const int n = aop.dimension(); - dpsi.assign(n, std::complex(0.0, 0.0)); - if (n == 0 || static_cast(b.size()) != n || max_iter <= 0) + if (n <= 0 || b.size() != static_cast(n) || max_iter <= 0 || !std::isfinite(conv_thr) || conv_thr <= 0.0) { - residual = 0.0; - ModuleBase::timer::end("DFPT_Stern", "solve"); - return 0; + return result; } - for (size_t m = 0; m < occ_kq.size(); ++m) + for (const std::vector> &u : occ_kq) { - if (static_cast(occ_kq[m].size()) != n) + if (u.size() != b.size()) + { + return result; + } + if (!finite_vector(u)) { - residual = 0.0; - ModuleBase::timer::end("DFPT_Stern", "solve"); - return 0; + result.status = Status::NonFinite; + return result; } } - + result.status = Status::NonFinite; + if (!finite_vector(b)) + { + return result; + } + dpsi.assign(n, std::complex(0.0, 0.0)); std::vector> pb(n); apply_pv(occ_kq, b, pb); const double bnorm = std::sqrt(real_vdot(pb, pb)); - const double homog_bnorm_floor = 1.0e-300; ///< empirical parameter: rhs norm floor for the homogeneous case + if (!std::isfinite(bnorm)) + { + return result; + } + const double homog_bnorm_floor = 1.0e-300; if (bnorm < homog_bnorm_floor) { - // the right-hand side lies inside the occupied subspace: the - // projected system is homogeneous and dpsi = 0 solves it exactly - residual = 0.0; - ModuleBase::timer::end("DFPT_Stern", "solve"); - return 0; + double scaled_norm = 0.0; + for (const std::complex &value : pb) + { + scaled_norm = std::hypot(scaled_norm, value.real()); + scaled_norm = std::hypot(scaled_norm, value.imag()); + } + if (scaled_norm >= homog_bnorm_floor) + { + // Squaring underflowed: a nonzero projected RHS is not a zero + // solution. Refuse unsupported precision instead of false success. + result.status = Status::Breakdown; + result.residual_available = true; + result.residual = 1.0; + return result; + } + result.status = Status::Converged; + result.residual_available = true; + result.residual = 0.0; + return result; } - std::vector> r = pb; std::vector> p = pb; std::vector> ap(n); std::vector> pap(n); std::vector> tmp(n); double rnorm2 = real_vdot(r, r); - int used = 0; + bool breakdown = false; for (int iter = 0; iter < max_iter; ++iter) { - used = iter + 1; + result.iterations = iter + 1; aop.apply(p.data(), ap.data()); apply_pv(occ_kq, ap, pap); double pAp = real_vdot(p, pap); + if (!std::isfinite(pAp)) + { + return result; + } if (pAp <= 0.0) { - // loss of positive definiteness along p (roundoff drift out of - // the complement): restart the direction from the residual p = r; aop.apply(p.data(), ap.data()); apply_pv(occ_kq, ap, pap); pAp = real_vdot(p, pap); + if (!std::isfinite(pAp)) + { + return result; + } if (pAp <= 0.0) { - rnorm2 = real_vdot(r, r); + breakdown = true; break; } } const double alpha = rnorm2 / pAp; + if (!std::isfinite(alpha)) + { + return result; + } for (int i = 0; i < n; ++i) { dpsi[i] += alpha * p[i]; r[i] -= alpha * pap[i]; } const double rnew2 = real_vdot(r, r); + if (!std::isfinite(rnew2) || !finite_vector(dpsi)) + { + return result; + } if (std::sqrt(rnew2) / bnorm < conv_thr) { - rnorm2 = rnew2; break; } const double beta = rnew2 / rnorm2; + if (!std::isfinite(beta)) + { + return result; + } for (int i = 0; i < n; ++i) { p[i] = r[i] + beta * p[i]; } - apply_pv(occ_kq, p, p); // in-place re-projection of the search direction + apply_pv(occ_kq, p, p); rnorm2 = rnew2; } - // final hygiene: remove any occupied-subspace leakage of the solution apply_pv(occ_kq, dpsi, tmp); dpsi.swap(tmp); - residual = std::sqrt(rnorm2) / bnorm; - ModuleBase::timer::end("DFPT_Stern", "solve"); - return used; + // Verify the actual returned projected solution, not only CG recurrence. + aop.apply(dpsi.data(), ap.data()); + apply_pv(occ_kq, ap, pap); + for (int i = 0; i < n; ++i) + { + r[i] = pb[i] - pap[i]; + } + result.residual = std::sqrt(real_vdot(r, r)) / bnorm; + result.residual_available = std::isfinite(result.residual); + if (!result.residual_available || !finite_vector(dpsi)) + { + return result; + } + result.status = Status::IterationLimit; + if (breakdown) + { + result.status = Status::Breakdown; + } + if (result.residual < conv_thr) + { + result.status = Status::Converged; + } + return result; } } // namespace ModuleDFPT diff --git a/source/source_pw/module_dfpt/dfpt_stern.h b/source/source_pw/module_dfpt/dfpt_stern.h index 731d2c133aa..b3411ee811a 100644 --- a/source/source_pw/module_dfpt/dfpt_stern.h +++ b/source/source_pw/module_dfpt/dfpt_stern.h @@ -2,6 +2,7 @@ #define DFPT_STERN_H #include +#include #include namespace ModuleDFPT @@ -39,6 +40,39 @@ class DFPT_Stern virtual void apply(const std::complex *x, std::complex *y) const = 0; }; + enum class Status + { + Converged, + IterationLimit, + InvalidInput, + NonFinite, + Breakdown + }; + + struct Result + { + Status status; + int iterations; + int limit; + double threshold; + bool residual_available; + double residual; + }; + + /// Return facts about the final projected solution, including its true + /// residual. Invalid input and legitimate homogeneous systems differ. + Result solve_report( + const LinearOperator &aop, + const std::vector>> &occ_kq, + const std::vector> &b, + int max_iter, + double conv_thr, + std::vector> &dpsi) const; + + /// The caller supplies task identity; failure never reaches a consumer. + static void require_converged(const Result &result, const std::string &context); + static const char *status_name(Status status); + /** * @brief Solve one projected Sternheimer system with conjugate gradients. * @@ -49,7 +83,8 @@ class DFPT_Stern * @param conv_thr relative residual threshold ||P_c r|| / ||P_c b|| * @param dpsi output P_c|dpsi_n> (zero inside the occ subspace) * @param residual achieved relative residual - * @return number of iterations used + * @return number of iterations used; unsuccessful solves terminate + * rather than losing their status through this adapter */ int solve( const LinearOperator &aop, @@ -61,6 +96,13 @@ class DFPT_Stern double &residual) const; private: + Result solve_impl( + const LinearOperator &aop, + const std::vector>> &occ_kq, + const std::vector> &b, + int max_iter, + double conv_thr, + std::vector> &dpsi) const; /// P_c x by modified Gram-Schmidt against the occupied states; safe for /// px to alias x (projection coefficients are collected before subtracting) void apply_pv( diff --git a/source/source_pw/module_dfpt/unittests/CMakeLists.txt b/source/source_pw/module_dfpt/unittests/CMakeLists.txt index a77928c9dc3..469f0d240f4 100644 --- a/source/source_pw/module_dfpt/unittests/CMakeLists.txt +++ b/source/source_pw/module_dfpt/unittests/CMakeLists.txt @@ -52,7 +52,8 @@ addtest( addtest( TARGET MODULE_DFPT_rho_serial LIBS parameter dfpt_planewave_serial device base symmetry - SOURCES test_dfpt_rho.cpp + SOURCES test_dfpt_convergence.cpp + test_dfpt_rho.cpp test_dfpt_rho_mix.cpp ../dfpt_rho.cpp ../dfpt_rho_mix.cpp @@ -203,7 +204,8 @@ if(ENABLE_MPI) TARGET MODULE_DFPT_stern_test KEEP_FEATURE_DEFINITIONS __MPI LIBS parameter base device symmetry - SOURCES test_dfpt_stern.cpp ../dfpt_stern.cpp test_dfpt_mocks.cpp) + SOURCES test_dfpt_stern.cpp test_dfpt_stern_status.cpp ../dfpt_stern.cpp + test_dfpt_mocks.cpp) addtest( TARGET MODULE_DFPT_pw_run_test diff --git a/source/source_pw/module_dfpt/unittests/test_dfpt_convergence.cpp b/source/source_pw/module_dfpt/unittests/test_dfpt_convergence.cpp new file mode 100644 index 00000000000..d877985cd24 --- /dev/null +++ b/source/source_pw/module_dfpt/unittests/test_dfpt_convergence.cpp @@ -0,0 +1,20 @@ +#include "source_pw/module_dfpt/dfpt_convergence.h" +#include "gtest/gtest.h" + +TEST(DFPTConvergence, ZeroOutputRequiresZeroDefect) +{ + EXPECT_DOUBLE_EQ(ModuleDFPT::response_relative_residual(0.0, 0.0), 0.0); + EXPECT_TRUE(std::isinf(ModuleDFPT::response_relative_residual(1.0, 0.0))); + EXPECT_DOUBLE_EQ(ModuleDFPT::response_relative_residual(1.0, 4.0), 0.5); +} + +TEST(DFPTConvergence, InvalidNormsCannotConverge) +{ + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + for (const double invalid : {nan, inf, -1.0}) + { + EXPECT_TRUE(std::isinf(ModuleDFPT::response_relative_residual(invalid, 1.0))); + EXPECT_TRUE(std::isinf(ModuleDFPT::response_relative_residual(1.0, invalid))); + } +} diff --git a/source/source_pw/module_dfpt/unittests/test_dfpt_stern_status.cpp b/source/source_pw/module_dfpt/unittests/test_dfpt_stern_status.cpp new file mode 100644 index 00000000000..492360ae201 --- /dev/null +++ b/source/source_pw/module_dfpt/unittests/test_dfpt_stern_status.cpp @@ -0,0 +1,140 @@ +#include "source_pw/module_dfpt/dfpt_stern.h" +#include "gtest/gtest.h" +#include +#include +#include + +namespace +{ +class StatusOperator : public ModuleDFPT::DFPT_Stern::LinearOperator +{ + public: + StatusOperator(int dimension, double first, double second) : dimension_(dimension), first_(first), second_(second) + { + } + int dimension() const override { return dimension_; } + void apply(const std::complex *x, std::complex *y) const override + { + for (int i = 0; i < dimension_; ++i) + { + const double coefficient = i == 0 ? first_ : second_; + y[i] = coefficient * x[i]; + } + } + + private: + int dimension_; + double first_; + double second_; +}; +using Status = ModuleDFPT::DFPT_Stern::Status; +} // namespace + +TEST(DFPTSternStatus, SuccessOnFinalAllowedIteration) +{ + StatusOperator op(2, 2.0, 2.0); + ModuleDFPT::DFPT_Stern solver; + std::vector> solution; + const std::vector> rhs{1.0, 2.0}; + const ModuleDFPT::DFPT_Stern::Result r = solver.solve_report(op, {}, rhs, 1, 1e-12, solution); + EXPECT_EQ(r.status, Status::Converged); + EXPECT_EQ(r.iterations, 1); + EXPECT_DOUBLE_EQ(r.residual, 0.0); + ASSERT_EQ(solution.size(), 2u); + EXPECT_DOUBLE_EQ(solution[0].real(), 0.5); + EXPECT_DOUBLE_EQ(solution[1].real(), 1.0); +} + +TEST(DFPTSternStatus, IterationLimitReportsTrueResidual) +{ + StatusOperator op(2, 1.0, 4.0); + ModuleDFPT::DFPT_Stern solver; + std::vector> solution; + const std::vector> rhs{1.0, 1.0}; + const ModuleDFPT::DFPT_Stern::Result r = solver.solve_report(op, {}, rhs, 1, 1e-12, solution); + EXPECT_EQ(r.status, Status::IterationLimit); + EXPECT_EQ(r.iterations, 1); + EXPECT_TRUE(r.residual_available); + EXPECT_NEAR(r.residual, 0.6, 1e-14); +} + +TEST(DFPTSternStatus, HomogeneousProjectionIsLegitimateZeroStepSuccess) +{ + StatusOperator op(2, 1.0, 4.0); + ModuleDFPT::DFPT_Stern solver; + std::vector> solution; + const std::vector>> occupied{{1.0, 0.0}}; + const std::vector> rhs{2.0, 0.0}; + const ModuleDFPT::DFPT_Stern::Result r = solver.solve_report(op, occupied, rhs, 1, 1e-12, solution); + EXPECT_EQ(r.status, Status::Converged); + EXPECT_EQ(r.iterations, 0); + EXPECT_TRUE(r.residual_available); + EXPECT_DOUBLE_EQ(r.residual, 0.0); +} + +TEST(DFPTSternStatus, RejectsDimensionsAndEffectiveParametersBeforeAllocation) +{ + ModuleDFPT::DFPT_Stern solver; + std::vector> solution{42.0}; + const std::vector> rhs{1.0, 1.0}; + for (const int dimension : {-1, 0, 3}) + { + StatusOperator op(dimension, 1.0, 2.0); + const ModuleDFPT::DFPT_Stern::Result r = solver.solve_report(op, {}, rhs, 1, 1e-8, solution); + EXPECT_EQ(r.status, Status::InvalidInput); + EXPECT_FALSE(r.residual_available); + EXPECT_TRUE(solution.empty()); + } + StatusOperator op(2, 1.0, 2.0); + EXPECT_EQ(solver.solve_report(op, {}, rhs, 0, 1e-8, solution).status, Status::InvalidInput); + for (const double threshold : {0.0, -1.0, std::numeric_limits::infinity()}) + { + EXPECT_EQ(solver.solve_report(op, {}, rhs, 2, threshold, solution).status, Status::InvalidInput); + } + const std::vector>> wrong{{1.0}}; + EXPECT_EQ(solver.solve_report(op, wrong, rhs, 2, 1e-8, solution).status, Status::InvalidInput); +} + +TEST(DFPTSternStatus, DistinguishesBreakdownAndNonFinite) +{ + ModuleDFPT::DFPT_Stern solver; + std::vector> solution; + const std::vector> rhs{1.0, 1.0}; + StatusOperator negative(2, -1.0, -1.0); + const ModuleDFPT::DFPT_Stern::Result broken = solver.solve_report(negative, {}, rhs, 2, 1e-8, solution); + EXPECT_EQ(broken.status, Status::Breakdown); + EXPECT_DOUBLE_EQ(broken.residual, 1.0); + const double nan = std::numeric_limits::quiet_NaN(); + StatusOperator invalid(2, nan, 1.0); + EXPECT_EQ(solver.solve_report(invalid, {}, rhs, 2, 1e-8, solution).status, Status::NonFinite); + StatusOperator normal(2, 1.0, 2.0); + const std::vector> bad_rhs{nan, 1.0}; + EXPECT_EQ(solver.solve_report(normal, {}, bad_rhs, 2, 1e-8, solution).status, Status::NonFinite); +} + +TEST(DFPTSternStatus, AdapterCannotLoseFailureStatus) +{ + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + StatusOperator op(2, 1.0, 4.0); + ModuleDFPT::DFPT_Stern solver; + std::vector> solution; + double residual = 0.0; + const std::vector> rhs(2, 1.0); + solver.solve(op, {}, rhs, 1, 1e-12, solution, residual); + }, + ::testing::ExitedWithCode(1), "reason=IterationLimit"); +} + +TEST(DFPTSternStatus, SquaredNormUnderflowIsNotHomogeneousSuccess) +{ + StatusOperator op(2, 1.0, 1.0); + ModuleDFPT::DFPT_Stern solver; + std::vector> solution; + const std::vector> rhs{1e-200, 0.0}; + const ModuleDFPT::DFPT_Stern::Result result = solver.solve_report(op, {}, rhs, 1, 1e-8, solution); + EXPECT_EQ(result.status, Status::Breakdown); + EXPECT_DOUBLE_EQ(result.residual, 1.0); +} diff --git a/tests/integrate/CMakeLists.txt b/tests/integrate/CMakeLists.txt index f1f6668198d..2387f60664f 100644 --- a/tests/integrate/CMakeLists.txt +++ b/tests/integrate/CMakeLists.txt @@ -44,7 +44,15 @@ if(LR_FORCE_TEST_PYTHON) ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools -p test_check_dfpt_failure.py) set_tests_properties(dfpt_failure_validator PROPERTIES TIMEOUT 30) - foreach(failure_case displacement efield finite_q displacement_budget) + foreach( + failure_case + displacement + efield + finite_q + displacement_budget + inner_displacement + inner_position + inner_finite_q) add_test( NAME dfpt_failure_${failure_case} COMMAND diff --git a/tests/integrate/fixtures/dfpt_failure/README.md b/tests/integrate/fixtures/dfpt_failure/README.md index e582e6639f6..9906752ba50 100644 --- a/tests/integrate/fixtures/dfpt_failure/README.md +++ b/tests/integrate/fixtures/dfpt_failure/README.md @@ -2,7 +2,8 @@ These fixed fixtures use the same small insulating Si cell and pseudopotential as the existing Gamma regression. Their GS converges before response failure. -The explicit linear budget (120 steps, threshold 1e-10) is independent of the +The outer-failure fixtures use an explicit linear budget (120 steps, threshold +1e-10), independent of the one- or three-step outer budget. The three-step case detects redundant passes. `displacement` and `displacement_budget` fail the first Gamma displacement; @@ -21,3 +22,8 @@ output. A crash, timeout or unrelated error is a test failure. These cases are registered separately because Autotest treats a nonzero exit as failure. Normal numerical regressions remain Autotest cases. They do not test reuse of old outputs; output-generation validation is separate work. + +The `inner_*` fixtures instead set one linear step and 60 outer steps. They +require an IterationLimit diagnostic from the first occupied band before any +outer iteration finishes. `inner_position` checks the position-response gate +before dielectric or Born consumers; finite q retains the explicit k list. diff --git a/tests/integrate/fixtures/dfpt_failure/inner_displacement/INPUT b/tests/integrate/fixtures/dfpt_failure/inner_displacement/INPUT new file mode 100644 index 00000000000..67c0ef38eaf --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_displacement/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 60 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 1 +dfpt_compute_q0 false +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/inner_displacement/KPT b/tests/integrate/fixtures/dfpt_failure/inner_displacement/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_displacement/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_displacement/QFILE b/tests/integrate/fixtures/dfpt_failure/inner_displacement/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_displacement/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_displacement/STRU b/tests/integrate/fixtures/dfpt_failure/inner_displacement/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_displacement/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_displacement/expected.json b/tests/integrate/fixtures/dfpt_failure/inner_displacement/expected.json new file mode 100644 index 00000000000..041874987f6 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_displacement/expected.json @@ -0,0 +1,15 @@ +{ + "stage": "displacement_inner", + "q_index": 0, + "iterations": 1, + "limit": 1, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.0, + 0.0, + 0.0 + ], + "kind": "linear" +} diff --git a/tests/integrate/fixtures/dfpt_failure/inner_finite_q/INPUT b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/INPUT new file mode 100644 index 00000000000..67c0ef38eaf --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 60 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 1 +dfpt_compute_q0 false +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/inner_finite_q/KPT b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/KPT new file mode 100644 index 00000000000..795cfeadd7e --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/KPT @@ -0,0 +1,4 @@ +K_POINTS +1 +Direct +0 0 0 1.0 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_finite_q/QFILE b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/QFILE new file mode 100644 index 00000000000..aa9a2a2065f --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0.5 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_finite_q/STRU b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_finite_q/expected.json b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/expected.json new file mode 100644 index 00000000000..2b36466f189 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_finite_q/expected.json @@ -0,0 +1,15 @@ +{ + "stage": "displacement_inner", + "q_index": 0, + "iterations": 1, + "limit": 1, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.5, + 0.0, + 0.0 + ], + "kind": "linear" +} diff --git a/tests/integrate/fixtures/dfpt_failure/inner_position/INPUT b/tests/integrate/fixtures/dfpt_failure/inner_position/INPUT new file mode 100644 index 00000000000..93951e27461 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_position/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 60 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 1 +dfpt_compute_q0 true +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/inner_position/KPT b/tests/integrate/fixtures/dfpt_failure/inner_position/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_position/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_position/QFILE b/tests/integrate/fixtures/dfpt_failure/inner_position/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_position/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_position/STRU b/tests/integrate/fixtures/dfpt_failure/inner_position/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_position/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/inner_position/expected.json b/tests/integrate/fixtures/dfpt_failure/inner_position/expected.json new file mode 100644 index 00000000000..4bc0bac94b9 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/inner_position/expected.json @@ -0,0 +1,15 @@ +{ + "stage": "position", + "q_index": 0, + "iterations": 1, + "limit": 1, + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ], + "q_direct": [ + 0.0, + 0.0, + 0.0 + ], + "kind": "linear" +} diff --git a/tests/integrate/validation_tools/check_dfpt_failure.py b/tests/integrate/validation_tools/check_dfpt_failure.py index 8441e5f4e08..8bf543d8c08 100644 --- a/tests/integrate/validation_tools/check_dfpt_failure.py +++ b/tests/integrate/validation_tools/check_dfpt_failure.py @@ -22,33 +22,64 @@ ) +INNER_FAILURE = re.compile( + r"DFPT response failure: stage=(\w+) q_index=(\d+) q_direct=\(([^)]+)\)" + r" direction=([xyz]) k_index=(\d+) band_index=(\d+)(?: atom=(\d+))?" + r" reason=(\w+) iterations=(\d+) limit=(\d+) residual=(\S+) threshold=(\S+)\. Stopping" +) + + +def validate_inner_text(stdout, warning, expected): + for label, text in (("stdout", stdout), ("warning.log", warning)): + matches = INNER_FAILURE.findall(text) + if len(matches) != 1: + raise AssertionError("Expected exactly one inner failure in " + label) + stage, qi, q, direction, ik, ib, atom, reason, iterations, limit, residual, threshold = matches[0] + if stage != expected["stage"] or int(qi) != expected["q_index"]: + raise AssertionError("Wrong inner response task") + if [float(component) for component in q.split(",")] != expected["q_direct"]: + raise AssertionError("Wrong physical q in inner failure") + if direction != "x" or ik != "0" or ib != "0": + raise AssertionError("Did not stop at the first failed inner task") + if reason != "IterationLimit" or int(iterations) != 1 or int(limit) != 1: + raise AssertionError("Wrong inner failure reason or budget") + value, tolerance = float(residual), float(threshold) + if not math.isfinite(value) or not math.isfinite(tolerance) or tolerance <= 0 or value < tolerance: + raise AssertionError("Invalid inner residual evidence") + if "DFPT mix iter=" in stdout: + raise AssertionError("Outer iteration continued after inner failure") + + def validate_failure(returncode, stdout, warning, running, products, expected): """Reject unrelated exits, successful results and ambiguous diagnostics.""" if returncode != 1: raise AssertionError("Expected exit 1, got {}".format(returncode)) if "#SCF IS CONVERGED#" not in running: raise AssertionError("Ground-state SCF did not converge") - for label, text in (("stdout", stdout), ("warning.log", warning)): - matches = FAILURE.findall(text) - if len(matches) != 1: - raise AssertionError("Expected exactly one response failure in " + label) - stage, qi, atom, direction, iterations, limit, residual, threshold, q = matches[0] - if stage != expected["stage"] or int(qi) != expected["q_index"]: - raise AssertionError("Failure occurred in the wrong response task") - if direction != "x" or (stage == "displacement" and atom != "1"): - raise AssertionError("The first failed response was not stopped") - if int(iterations) != expected["iterations"] or int(limit) != expected["limit"]: - raise AssertionError("Unexpected iteration budget") - value, tolerance = float(residual), float(threshold) - if not math.isfinite(value) or not math.isfinite(tolerance): - raise AssertionError("Expected a finite iteration-limit residual") - if tolerance <= 0 or value < tolerance: - raise AssertionError("The reported response already met its threshold") - if [float(component) for component in q.split(",")] != expected["q_direct"]: - raise AssertionError("Wrong physical q in failure diagnostic") - trace = r"DFPT mix iter=" if expected["stage"] == "displacement" else None - if trace and len(re.findall(trace, stdout)) != expected["iterations"]: - raise AssertionError("Response solves were repeated after exhausting the budget") + if expected.get("kind") == "linear": + validate_inner_text(stdout, warning, expected) + else: + for label, text in (("stdout", stdout), ("warning.log", warning)): + matches = FAILURE.findall(text) + if len(matches) != 1: + raise AssertionError("Expected exactly one response failure in " + label) + stage, qi, atom, direction, iterations, limit, residual, threshold, q = matches[0] + if stage != expected["stage"] or int(qi) != expected["q_index"]: + raise AssertionError("Failure occurred in the wrong response task") + if direction != "x" or (stage == "displacement" and atom != "1"): + raise AssertionError("The first failed response was not stopped") + if int(iterations) != expected["iterations"] or int(limit) != expected["limit"]: + raise AssertionError("Unexpected iteration budget") + value, tolerance = float(residual), float(threshold) + if not math.isfinite(value) or not math.isfinite(tolerance): + raise AssertionError("Expected a finite iteration-limit residual") + if tolerance <= 0 or value < tolerance: + raise AssertionError("The reported response already met its threshold") + if [float(component) for component in q.split(",")] != expected["q_direct"]: + raise AssertionError("Wrong physical q in failure diagnostic") + trace = r"DFPT mix iter=" if expected["stage"] == "displacement" else None + if trace and len(re.findall(trace, stdout)) != expected["iterations"]: + raise AssertionError("Response solves were repeated after exhausting the budget") for marker in ("DFPT phonon frequencies at q #", "DFPT dielectric tensor (epsilon_inf):", "DFPT Born effective charge atom", "DFPT LO-TO corrected frequencies"): if marker in stdout: diff --git a/tests/integrate/validation_tools/test_check_dfpt_failure.py b/tests/integrate/validation_tools/test_check_dfpt_failure.py index 48d0498905e..286554c554c 100644 --- a/tests/integrate/validation_tools/test_check_dfpt_failure.py +++ b/tests/integrate/validation_tools/test_check_dfpt_failure.py @@ -57,5 +57,35 @@ def test_acceptable_and_nonfinite_residuals_are_rejected(self): self.check(warning=self.message.replace("1.000000e+00", residual)) +class InnerFailureAuditTest(unittest.TestCase): + def setUp(self): + self.expected = dict(kind="linear", stage="displacement_inner", q_index=0, q_direct=[0, 0, 0]) + self.message = ("DFPT response failure: stage=displacement_inner q_index=0 q_direct=(0,0,0) " + "direction=x k_index=0 band_index=0 atom=1 reason=IterationLimit " + "iterations=1 limit=1 residual=6.000000e-01 threshold=1.000000e-10. Stopping") + + def check(self, **changes): + args = dict(returncode=1, stdout=self.message, warning=self.message, + running="#SCF IS CONVERGED#", products=[], expected=self.expected) + args.update(changes) + validate_failure(**args) + + def test_expected_inner_failure(self): + self.check() + + def test_unrelated_failure_cannot_pass(self): + for old, new in (("reason=IterationLimit", "reason=Breakdown"), + ("stage=displacement_inner", "stage=position"), + ("k_index=0", "k_index=1"), + ("q_direct=(0,0,0)", "q_direct=(0.5,0,0)"), + ("6.000000e-01", "nan")): + with self.subTest(new=new), self.assertRaises(AssertionError): + self.check(warning=self.message.replace(old, new)) + + def test_outer_continuation_cannot_pass(self): + with self.assertRaises(AssertionError): + self.check(stdout=self.message + "\nDFPT mix iter=1") + + if __name__ == "__main__": unittest.main() From c66fd9c22af2834d448f5bc0a092bfcd7932b8dc Mon Sep 17 00:00:00 2001 From: Zanthoxylum <105619360+Zanthoxylum@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:57:11 +0800 Subject: [PATCH 3/4] fix(dfpt): qualify results and commit output generations Summary Begin a unique DFPT output generation before ground-state setup. Reject unconverged GS and unverified response/matrix/tensor consumers. Record ordinary response failures, preserve owned previous dyn files and publish staged files before committing a matching Complete manifest. Design A Failed/Running/Verified generation is not complete. Preserve old owned products and previous status under a private generation directory. Reject unknown or symlinked numbered dyn paths; leave unrelated files intact. Check dyn writer success and publish without overwriting new foreign files. A partial publication never commits Complete. The session is not a checkpoint. The running-log dependency moves from the writer to session initialization; new GlobalV references are offset by removed references (net zero). Verification Main executable and all twelve DFPT unit targets rebuilt. CTest 26/26; default Gamma Autotest 8/8 and all six exact frequencies unchanged. Three converged control dyn files remain byte-identical to C2. Seven inner/outer failure cases and real success-then-outer/inner/GS-failure runs pass, preserving old output bytes and unrelated files. Foreign-file protection passes. All seven frozen branch combinations merge without textual conflict. Tests Nine session unit tests cover lifecycle, legacy ownership, symlinks, partial publication, interrupted generations and foreign destination collisions; the dyn writer reports missing matrices. Manifest auditing rejects stale identities and incomplete/mismatched product sets. DFPT/CMake and only new outside-DFPT snippets are format-clean. Governance has no ERROR; header dependencies serve actual session ownership and public types. No retry or warm start is added. --- .../elec_properties/dfpt_convergence.md | 24 +- source/Makefile.Objects | 1 + source/source_esolver/esolver_dfpt_pw.cpp | 22 +- source/source_esolver/esolver_dfpt_pw.h | 3 + source/source_pw/module_dfpt/CMakeLists.txt | 2 + source/source_pw/module_dfpt/dfpt_pw.cpp | 117 ++++++- source/source_pw/module_dfpt/dfpt_pw.h | 5 +- source/source_pw/module_dfpt/dfpt_pw_impl.h | 4 + source/source_pw/module_dfpt/dfpt_pw_init.cpp | 2 +- source/source_pw/module_dfpt/dfpt_pw_q0.cpp | 12 +- source/source_pw/module_dfpt/dfpt_pw_run.cpp | 4 + .../source_pw/module_dfpt/dfpt_pw_solve.cpp | 12 +- .../module_dfpt/dfpt_run_session.cpp | 312 ++++++++++++++++++ .../source_pw/module_dfpt/dfpt_run_session.h | 46 +++ source/source_pw/module_dfpt/dfpt_stern.cpp | 32 +- source/source_pw/module_dfpt/dfpt_stern.h | 2 + .../source_pw/module_dfpt/dfpt_write_dyn.cpp | 38 +-- source/source_pw/module_dfpt/dfpt_write_dyn.h | 4 +- .../module_dfpt/unittests/CMakeLists.txt | 6 + .../unittests/test_dfpt_run_session.cpp | 223 +++++++++++++ .../unittests/test_dfpt_write_dyn.cpp | 8 + tests/integrate/CMakeLists.txt | 18 + .../integrate/fixtures/dfpt_failure/README.md | 10 +- .../fixtures/dfpt_failure/ground_state/INPUT | 24 ++ .../fixtures/dfpt_failure/ground_state/KPT | 4 + .../fixtures/dfpt_failure/ground_state/QFILE | 4 + .../fixtures/dfpt_failure/ground_state/STRU | 19 ++ .../dfpt_failure/ground_state/expected.json | 6 + .../dfpt_failure/session_success/INPUT | 24 ++ .../fixtures/dfpt_failure/session_success/KPT | 4 + .../dfpt_failure/session_success/QFILE | 4 + .../dfpt_failure/session_success/STRU | 19 ++ .../session_success/expected.json | 6 + .../validation_tools/check_dfpt_session.py | 123 +++++++ .../test_check_dfpt_session.py | 36 ++ 35 files changed, 1130 insertions(+), 50 deletions(-) create mode 100644 source/source_pw/module_dfpt/dfpt_run_session.cpp create mode 100644 source/source_pw/module_dfpt/dfpt_run_session.h create mode 100644 source/source_pw/module_dfpt/unittests/test_dfpt_run_session.cpp create mode 100644 tests/integrate/fixtures/dfpt_failure/ground_state/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/ground_state/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/ground_state/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/ground_state/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/ground_state/expected.json create mode 100644 tests/integrate/fixtures/dfpt_failure/session_success/INPUT create mode 100644 tests/integrate/fixtures/dfpt_failure/session_success/KPT create mode 100644 tests/integrate/fixtures/dfpt_failure/session_success/QFILE create mode 100644 tests/integrate/fixtures/dfpt_failure/session_success/STRU create mode 100644 tests/integrate/fixtures/dfpt_failure/session_success/expected.json create mode 100644 tests/integrate/validation_tools/check_dfpt_session.py create mode 100644 tests/integrate/validation_tools/test_check_dfpt_session.py diff --git a/docs/advanced/elec_properties/dfpt_convergence.md b/docs/advanced/elec_properties/dfpt_convergence.md index e9c2af1b25f..30f5bad9f40 100644 --- a/docs/advanced/elec_properties/dfpt_convergence.md +++ b/docs/advanced/elec_properties/dfpt_convergence.md @@ -32,6 +32,24 @@ not establish convergence with respect to basis cutoffs or sampling. A converged imaginary phonon frequency can describe structural instability and is not itself a response-convergence failure. -Use a fresh output directory when checking failure products. Earlier files -can remain after reusing a suffix; their presence is not evidence that the -latest calculation succeeded. Inspect the current exit status and logs. +Each production invocation establishes a new `run_id` and +`OUT./dfpt.status` before ground-state setup. Only `Complete` for +that invocation qualifies its product list. `Running`, `Verified` and +`Failed` do not establish completed output. The ordinary response failures +record `Failed`; an abrupt exit can leave an incomplete marker. + +New dyn files are written inside a private `.dfpt-run-*` generation directory +and published to their existing `dyn.q` names only after results have been +verified. The completion marker is committed last. Per-file publication is +not an atomic commit of the entire product set: an interrupted publication +may leave partial files, which must be rejected without a matching `Complete`. + +When reusing a suffix, numbered dyn files with the ABACUS DFPT ownership +header are preserved in the new generation's `previous/` directory, together +with the previous status. Other files remain untouched. Unknown or symlinked +numbered dyn paths, and an earlier active/incomplete generation, are rejected; +use a fresh output suffix in those cases. Do not run concurrent calculations +in the same output directory. These records provide output validity, not +checkpoint/restart support. Input or process failures before the DFPT solver +entry still require checking the invocation's exit status; an older run_id +must never be treated as a new invocation. diff --git a/source/Makefile.Objects b/source/Makefile.Objects index fa8f050a220..d8773ff23b5 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -475,6 +475,7 @@ OBJS_DFPT=dfpt_symm.o\ dfpt_q0_pos.o\ dfpt_rho.o\ dfpt_rho_mix.o\ + dfpt_run_session.o\ dfpt_stern.o\ dfpt_write_dyn.o\ dfpt_xc_analytic.o diff --git a/source/source_esolver/esolver_dfpt_pw.cpp b/source/source_esolver/esolver_dfpt_pw.cpp index ce79d1bf6f5..af3c00a4e11 100644 --- a/source/source_esolver/esolver_dfpt_pw.cpp +++ b/source/source_esolver/esolver_dfpt_pw.cpp @@ -208,6 +208,10 @@ void ESolver_DFPT_PW::before_all_runners(BaseCell &basecell, const Input_para &i ModuleBase::TITLE("ESolver_DFPT_PW", "before_all_runners"); + const std::string output_directory = "OUT." + inp.suffix; + const int output_rank = ModuleBase::world_comm_domain().rank(); + dfpt_session_.begin(output_directory, output_rank, &GlobalV::ofs_running); + ESolver_KS_PW, base_device::DEVICE_CPU>::before_all_runners(ucell, inp); // capture the (possibly autoset) ground-state scalars once; inp aliases @@ -230,6 +234,7 @@ void ESolver_DFPT_PW::before_all_runners(BaseCell &basecell, const Input_para &i // static DFPT configuration from INPUT (explicit passing, rule 1); the // ground-state data wiring happens in init_dfpt after the SCF converges dfpt_ = new ModuleDFPT::DFPT_PW(); + dfpt_->set_run_session(dfpt_session_); dfpt_->set_qmesh(inp.dfpt_qmesh[0], inp.dfpt_qmesh[1], inp.dfpt_qmesh[2]); dfpt_->set_qfile(inp.dfpt_qfile); dfpt_->set_conv_thr(inp.dfpt_conv_thr); @@ -255,6 +260,10 @@ void ESolver_DFPT_PW::runner(BaseCell &basecell, const int istep) if (!gs_done_) { run_gs(ucell); + if (!this->conv_esolver) + { + dfpt_session_.fail("DFPT response requires a converged ground state"); + } gs_done_ = true; } @@ -487,6 +496,9 @@ void ESolver_DFPT_PW::run_post_process(UnitCell &ucell) { return; } + dfpt_->require_results(); + dfpt_session_.verify(); + // multi-q frequency report (one block per q of the list, plus the LO-TO // corrected Gamma block along the data-layer direction when enabled); // the tensor blocks below stay design-phase std::cout until the io @@ -540,9 +552,15 @@ void ESolver_DFPT_PW::run_post_process(UnitCell &ucell) // is offset by the two global-record domag reads removed above). if (this->inp_->dfpt_out_dyn) { - const std::string out_dir = "OUT." + this->inp_->suffix + "/"; - ModuleDFPT::DFPT_Write_Dyn(ucell, dfpt_->get_data(), nq, out_dir, dfpt_->get_myrank(), &GlobalV::ofs_running); + const std::string out_dir = dfpt_session_.staging_directory(); + const bool written = ModuleDFPT::DFPT_Write_Dyn( + ucell, dfpt_->get_data(), nq, out_dir, dfpt_->get_myrank(), dfpt_session_.running_log()); + if (!written) + { + dfpt_session_.fail("DFPT dynamical-matrix staging failed"); + } } + dfpt_session_.commit(nq, this->inp_->dfpt_out_dyn); } } // namespace ModuleESolver diff --git a/source/source_esolver/esolver_dfpt_pw.h b/source/source_esolver/esolver_dfpt_pw.h index 6a0618785ad..eb019f48bfc 100644 --- a/source/source_esolver/esolver_dfpt_pw.h +++ b/source/source_esolver/esolver_dfpt_pw.h @@ -11,6 +11,7 @@ #include "esolver_ks_pw.h" #include "source_pw/module_dfpt/dfpt_pw.h" +#include "source_pw/module_dfpt/dfpt_run_session.h" namespace ModuleDFPT { @@ -33,6 +34,8 @@ class ESolver_DFPT_PW : public ESolver_KS_PW, base_device:: protected: ModuleDFPT::DFPT_PW *dfpt_ = nullptr; + ModuleDFPT::DFPT_RunSession dfpt_session_; + ///< first-order XC kernel adapter over elecstate::PotXC_FDM (C7), ///< owned here so module_dfpt stays free of pot_xc_fdm.h dependencies ModuleDFPT::XC_First_Order *xc_adapter_ = nullptr; diff --git a/source/source_pw/module_dfpt/CMakeLists.txt b/source/source_pw/module_dfpt/CMakeLists.txt index d978905a3f9..7ad1a77d2da 100644 --- a/source/source_pw/module_dfpt/CMakeLists.txt +++ b/source/source_pw/module_dfpt/CMakeLists.txt @@ -12,6 +12,7 @@ set(SOURCES dfpt_pert.cpp dfpt_pert_vkb.cpp dfpt_pert_nl.cpp + dfpt_run_session.cpp dfpt_stern.cpp dfpt_symm.cpp dfpt_nscf.cpp @@ -33,6 +34,7 @@ set(HEADERS dfpt_kq_basis.h dfpt_pert.h dfpt_convergence.h + dfpt_run_session.h dfpt_stern.h dfpt_nscf.h dfpt_rho.h diff --git a/source/source_pw/module_dfpt/dfpt_pw.cpp b/source/source_pw/module_dfpt/dfpt_pw.cpp index 871c3b933ff..eeb11560448 100644 --- a/source/source_pw/module_dfpt/dfpt_pw.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw.cpp @@ -62,7 +62,7 @@ void DFPT_PW::Impl::require_projector(int q_idx, int ik) const std::ostringstream message; message << "DFPT response failure: stage=projector q_index=" << q_idx << " k_index=" << ik << " reason=InvalidInput missing occupied states"; - ModuleBase::WARNING_QUIT("DFPT_PW", message.str()); + fail_response("DFPT_PW", message.str()); } } @@ -79,10 +79,123 @@ double DFPT_PW::Impl::solve_linear_response( hamilt_->set_shift(eig_(ik, ib)); const DFPT_Stern::Result result = stern_.solve_report(*hamilt_, occ_kq_[ik], rhs, lin_max, lin_thr, solution); const std::string context = response_context(stage, ik, ib, direction); - DFPT_Stern::require_converged(result, context); + if (!DFPT_Stern::is_converged(result)) + { + const std::string message = DFPT_Stern::failure_message(result, context); + fail_response("DFPT_PW", message); + } return result.residual; } +void DFPT_PW::Impl::fail_response(const std::string &scope, const std::string &message) const +{ + if (run_session_ != nullptr) + { + run_session_->fail(message); + } + ModuleBase::WARNING_QUIT(scope, message); +} + +void DFPT_PW::Impl::require_q_converged(int q_idx) const +{ + const int count = data_.get_nirr(q_idx); + if (count <= 0) + { + fail_response("DFPT_PW", "Missing required response blocks before consumption"); + } + for (int irrep = 0; irrep < count; ++irrep) + { + if (!data_.get_converged(q_idx, irrep)) + { + const std::string message = "Unverified DFPT response source at q_index=" + std::to_string(q_idx); + fail_response("DFPT_PW", message); + } + } +} + +void DFPT_PW::set_run_session(DFPT_RunSession &session) { pimpl_->run_session_ = &session; } + +void DFPT_PW::require_results() const +{ + if (!pimpl_->wired()) + { + pimpl_->fail_response("DFPT_PW", "Unwired DFPT skeleton has no publishable response results"); + } + const int modes = 3 * pimpl_->ucell_->nat; + for (int q = 0; q < get_nq(); ++q) + { + pimpl_->require_q_converged(q); + const std::vector frequencies = pimpl_->data_.get_phon_freq(q); + if (frequencies.size() != static_cast(modes)) + { + pimpl_->fail_response("DFPT_PW", "Missing complete phonon spectrum before publication"); + } + for (const double frequency : frequencies) + { + if (!std::isfinite(frequency)) + { + pimpl_->fail_response("DFPT_PW", "Nonfinite phonon spectrum before publication"); + } + } + const ModuleBase::ComplexMatrix matrix = pimpl_->data_.get_dynmat_raw(q); + if (matrix.nr != modes || matrix.nc != modes) + { + pimpl_->fail_response("DFPT_PW", "Missing complete raw DFPT matrix before publication"); + } + for (int i = 0; i < modes; ++i) + { + for (int j = 0; j < modes; ++j) + { + if (!std::isfinite(matrix(i, j).real()) || !std::isfinite(matrix(i, j).imag())) + { + pimpl_->fail_response("DFPT_PW", "Nonfinite raw DFPT matrix before publication"); + } + } + } + } + if (pimpl_->data_.get_compute_q0()) + { + const ModuleBase::matrix eps = pimpl_->data_.get_dielectric(); + if (eps.nr != 3 || eps.nc != 3) + { + pimpl_->fail_response("DFPT_PW", "Missing verified dielectric response before publication"); + } + for (int atom = 0; atom < pimpl_->ucell_->nat; ++atom) + { + const ModuleBase::matrix born = pimpl_->data_.get_born(atom); + if (born.nr != 3 || born.nc != 3) + { + pimpl_->fail_response("DFPT_PW", "Missing verified Born response before publication"); + } + for (int i = 0; i < 3; ++i) + { + for (int j = 0; j < 3; ++j) + { + if (!std::isfinite(eps(i, j)) || !std::isfinite(born(i, j))) + { + pimpl_->fail_response("DFPT_PW", "Nonfinite polar response before publication"); + } + } + } + } + } + if (pimpl_->data_.get_loto()) + { + const std::vector frequencies = pimpl_->data_.get_phon_freq_loto(); + if (!pimpl_->data_.get_compute_q0() || frequencies.size() != static_cast(modes)) + { + pimpl_->fail_response("DFPT_PW", "LO-TO publication requires verified polar responses"); + } + for (const double frequency : frequencies) + { + if (!std::isfinite(frequency)) + { + pimpl_->fail_response("DFPT_PW", "Nonfinite LO-TO spectrum before publication"); + } + } + } +} + DFPT_PW::DFPT_PW() : pimpl_(std::unique_ptr(new Impl())) {} DFPT_PW::~DFPT_PW() {} diff --git a/source/source_pw/module_dfpt/dfpt_pw.h b/source/source_pw/module_dfpt/dfpt_pw.h index 6d9422cdb1e..5c6c54f02a2 100644 --- a/source/source_pw/module_dfpt/dfpt_pw.h +++ b/source/source_pw/module_dfpt/dfpt_pw.h @@ -21,8 +21,9 @@ class PW_Basis_K; namespace ModuleDFPT { +class DFPT_RunSession; class DFPT_PW_Data; -} +} // namespace ModuleDFPT namespace ModuleDFPT { @@ -119,6 +120,8 @@ class DFPT_PW void init(const DFPT_PW_InitContext &ctx); void run(); + void set_run_session(DFPT_RunSession &session); + void require_results() const; /// DFT+U reservation accessors (U0): with_u() reports whether a DFT+U /// provider is wired (dft_plus_u enabled upstream); u_active() further diff --git a/source/source_pw/module_dfpt/dfpt_pw_impl.h b/source/source_pw/module_dfpt/dfpt_pw_impl.h index 7541d8525e5..3d0a29dc2e6 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_impl.h +++ b/source/source_pw/module_dfpt/dfpt_pw_impl.h @@ -10,6 +10,7 @@ #include "dfpt_pw_data.h" #include "dfpt_q0.h" #include "dfpt_rho.h" +#include "dfpt_run_session.h" #include "dfpt_stern.h" #include "source_base/matrix.h" #include "source_base/module_mixing/broyden_mixing.h" @@ -106,6 +107,8 @@ class DFPT_PW::Impl void run_assemble(int q_idx); // ----- solve_displacement helpers (dfpt_pw_solve.cpp) ----- + void fail_response(const std::string &scope, const std::string &message) const; + void require_q_converged(int q_idx) const; void require_projector(int q_idx, int ik) const; std::string response_context( const char *stage, @@ -173,6 +176,7 @@ class DFPT_PW::Impl bool wired() const; + DFPT_RunSession *run_session_ = nullptr; DFPT_PW_Data data_; DFPT_Pert pert_; DFPT_Stern stern_; diff --git a/source/source_pw/module_dfpt/dfpt_pw_init.cpp b/source/source_pw/module_dfpt/dfpt_pw_init.cpp index 43213aa8aee..f2de65566be 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_init.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_init.cpp @@ -321,7 +321,7 @@ void DFPT_PW::Impl::build_occ_kq(int q_idx) oss << "the nscf diagonalization at k index " << ik << " did not reach the eigenvalue " << "residual target within " << lin_max << " outer iterations (last pass " << it << "); raise dfpt_conv_thr precision handling or inspect the spectrum"; - ModuleBase::WARNING_QUIT("DFPT_PW::build_occ_kq", oss.str()); + fail_response("DFPT_PW::build_occ_kq", oss.str()); } occ_kq_[ik] = std::move(occ_ik); eig_kq_[ik] = std::move(eig_ik); diff --git a/source/source_pw/module_dfpt/dfpt_pw_q0.cpp b/source/source_pw/module_dfpt/dfpt_pw_q0.cpp index 0965882e061..f45cd5b9a4d 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_q0.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_q0.cpp @@ -203,8 +203,7 @@ void DFPT_PW::Impl::efield_per_band_solve( if (yr[ik][ib].empty() || static_cast(dv_sc.size()) != nbands || yr[ik][ib].size() != dv_sc[ib].size()) { const std::string context = response_context("efield_inner", ik, ib, a); - ModuleBase::WARNING_QUIT( - "DFPT_PW", "DFPT response failure: " + context + " reason=InvalidInput missing response leg"); + fail_response("DFPT_PW", "DFPT response failure: " + context + " reason=InvalidInput missing response leg"); } std::vector> rhs(yr[ik][ib].size()); for (size_t i = 0; i < rhs.size(); ++i) @@ -347,6 +346,13 @@ void DFPT_PW::Impl::solve_efield_resp(int q_idx) rho_.mix_drho(q_idx, data_); const double residual = rho_.get_residual(q_idx, data_); residual_last = residual; + if (!std::isfinite(residual)) + { + std::ostringstream message; + message << "DFPT response failure: stage=efield q_index=" << q_idx + << " reason=NonFinite residual=unavailable"; + fail_response("DFPT_PW", message.str()); + } converged = (residual < conv_thr_); ++n_iter_done; if (converged) @@ -366,7 +372,7 @@ void DFPT_PW::Impl::solve_efield_resp(int q_idx) << " limit=" << max_iter_ << " residual=" << std::scientific << std::setprecision(6) << residual_last << " threshold=" << conv_thr_ << " q_direct=(" << q_frac.x << "," << q_frac.y << "," << q_frac.z << "). The response did not converge; stopping before caching or assembly."; - ModuleBase::WARNING_QUIT("DFPT_PW::solve_efield_resp", oss.str()); + fail_response("DFPT_PW::solve_efield_resp", oss.str()); } stash_dpsi_efield(q_idx, a, nk, nbands); } diff --git a/source/source_pw/module_dfpt/dfpt_pw_run.cpp b/source/source_pw/module_dfpt/dfpt_pw_run.cpp index f0f2f4f4c00..2cfd64b8587 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_run.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_run.cpp @@ -254,6 +254,10 @@ void DFPT_PW::Impl::symmetrize_q0_tensors() void DFPT_PW::Impl::run_assemble(int q_idx) { + if (wired()) + { + require_q_converged(q_idx); + } phon_.assemble(q_idx, data_); // translational sum-rule audit of the raw Gamma matrix (acoustic-branch // diagnostics; the loto-corrected matrix is audited separately below). diff --git a/source/source_pw/module_dfpt/dfpt_pw_solve.cpp b/source/source_pw/module_dfpt/dfpt_pw_solve.cpp index 75d5cda4e0e..1383da8654b 100644 --- a/source/source_pw/module_dfpt/dfpt_pw_solve.cpp +++ b/source/source_pw/module_dfpt/dfpt_pw_solve.cpp @@ -107,8 +107,7 @@ double DFPT_PW::Impl::sternheimer_per_band( if (rhs.empty() || static_cast(dv_sc.size()) != nbands || rhs.size() != dv_sc[ib].size()) { const std::string context = response_context("displacement_inner", ik, ib, data_.get_pert_dir()); - ModuleBase::WARNING_QUIT( - "DFPT_PW", "DFPT response failure: " + context + " reason=InvalidInput missing response leg"); + fail_response("DFPT_PW", "DFPT response failure: " + context + " reason=InvalidInput missing response leg"); } for (size_t i = 0; i < rhs.size(); ++i) { @@ -431,6 +430,13 @@ double DFPT_PW::Impl::solve_displacement(int q_idx, int iat, int idir) { std::cout << "DBG iter=" << iter << " residual=" << residual << " conv_thr=" << conv_thr_ << std::endl; } + if (!std::isfinite(residual)) + { + std::ostringstream message; + message << "DFPT response failure: stage=displacement q_index=" << q_idx + << " reason=NonFinite residual=unavailable"; + fail_response("DFPT_PW", message.str()); + } converged = (residual < conv_thr_); ++n_iter_done; } @@ -453,7 +459,7 @@ double DFPT_PW::Impl::solve_displacement(int q_idx, int iat, int idir) << " residual=" << std::scientific << std::setprecision(6) << residual << " threshold=" << conv_thr_ << " q_direct=(" << q_frac.x << "," << q_frac.y << "," << q_frac.z << "). The response did not converge; stopping before caching or assembly."; - ModuleBase::WARNING_QUIT("DFPT_PW::solve_displacement", oss.str()); + fail_response("DFPT_PW::solve_displacement", oss.str()); } stash_converged_disp_response(q_idx, iat, idir, v_sc_r_last, nk, nbands); diff --git a/source/source_pw/module_dfpt/dfpt_run_session.cpp b/source/source_pw/module_dfpt/dfpt_run_session.cpp new file mode 100644 index 00000000000..260c1a3c623 --- /dev/null +++ b/source/source_pw/module_dfpt/dfpt_run_session.cpp @@ -0,0 +1,312 @@ +#include "dfpt_run_session.h" +#include "source_base/tool_quit.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ModuleDFPT +{ +namespace +{ +bool dyn_name(const std::string &name) +{ + if (name.size() <= 5 || name.substr(0, 5) != "dyn.q") + { + return false; + } + for (size_t i = 5; i < name.size(); ++i) + { + if (name[i] < '0' || name[i] > '9') + { + return false; + } + } + return true; +} + +bool regular_file(const std::string &path) +{ + struct stat info; + return lstat(path.c_str(), &info) == 0 && S_ISREG(info.st_mode); +} + +bool owned_dyn(const std::string &path) +{ + if (!regular_file(path)) + { + return false; + } + std::ifstream file(path); + std::string first; + std::string second; + return static_cast(std::getline(file, first)) && static_cast(std::getline(file, second)) && + first == "Dynamical matrix file" && second.find("ABACUS DFPT output") == 0; +} +} // namespace + +void DFPT_RunSession::record_read(const std::string &path) const +{ + std::cout << " DFPT session: read " << path << std::endl; + if (running_log_ != nullptr) + { + (*running_log_) << " DFPT session: read " << path << std::endl; + } +} + +void DFPT_RunSession::record_file(const std::string &path) const +{ + if (running_log_ != nullptr) + { + (*running_log_) << " DFPT session: wrote " << path << std::endl; + } +} + +bool DFPT_RunSession::write_state(const char *state, const std::vector &products) +{ + const std::string temporary = run_directory_ + "/state.next"; + std::ofstream file(temporary); + file << "ABACUS DFPT session 1\nrun_id " << run_id_ << "\nstate " << state << "\nproduct_count " << products.size() + << "\n"; + for (const std::string &product : products) + { + file << "product " << product << "\n"; + } + file.close(); + const std::string destination = output_directory_ + "/dfpt.status"; + if (file.fail() || std::rename(temporary.c_str(), destination.c_str()) != 0) + { + return false; + } + record_file(destination); + return true; +} + +void DFPT_RunSession::fail(const std::string &reason) +{ + state_ = State::Failed; + if (rank_ == 0 && !run_directory_.empty()) + { + // Best effort: an earlier Running/Verified marker is also incomplete + // if the filesystem cannot record Failed. Never create Complete here. + const std::string diagnostic = run_directory_ + "/failure.txt"; + std::ofstream details(diagnostic); + details << reason << std::endl; + details.close(); + record_file(diagnostic); + write_state("Failed", {}); + } + ModuleBase::WARNING_QUIT("DFPT_RunSession", reason); +} + +void DFPT_RunSession::begin(const std::string &output_directory, int rank, std::ostream *running_log) +{ + if (state_ != State::Idle) + { + fail("DFPT session is already initialized"); + } + rank_ = rank; + running_log_ = running_log; + state_ = State::Running; + if (rank_ != 0) + { + return; + } + char resolved[PATH_MAX]; + if (realpath(output_directory.c_str(), resolved) == nullptr) + { + fail("Cannot resolve the DFPT output directory: " + output_directory); + } + output_directory_ = resolved; + const std::string status_path = output_directory_ + "/dfpt.status"; + std::string previous; + struct stat info; + if (lstat(status_path.c_str(), &info) == 0) + { + if (!S_ISREG(info.st_mode)) + { + fail("Refusing a non-regular DFPT status path; use a fresh output suffix: " + status_path); + } + std::ifstream old(status_path); + std::string header; + std::string id_key; + std::string id; + std::string state_key; + std::string state; + std::getline(old, header); + old >> id_key >> id >> state_key >> state; + if (!old || header != "ABACUS DFPT session 1" || id_key != "run_id" || state_key != "state") + { + fail("Cannot establish ownership of the old status file; use a fresh output suffix: " + status_path); + } + if (state != "Complete" && state != "Failed") + { + fail("An earlier DFPT session is incomplete or active; use a fresh output suffix: " + status_path); + } + old.clear(); + old.seekg(0); + std::ostringstream saved; + saved << old.rdbuf(); + if (old.bad()) + { + fail("Cannot preserve the previous DFPT status: " + status_path); + } + previous = saved.str(); + std::cout << " DFPT session: read " << status_path << std::endl; + if (running_log_ != nullptr) + { + (*running_log_) << " DFPT session: read " << status_path << std::endl; + } + } + else if (errno != ENOENT) + { + fail("Cannot inspect the DFPT status path: " + status_path); + } + const std::string pattern = output_directory_ + "/.dfpt-run-XXXXXX"; + std::vector scratch(pattern.begin(), pattern.end()); + scratch.push_back('\0'); + char *created = mkdtemp(scratch.data()); + if (created == nullptr) + { + fail("Cannot create a private DFPT generation directory: " + output_directory_); + } + run_directory_ = created; + const size_t slash = run_directory_.find_last_of('/'); + run_id_ = run_directory_.substr(slash + 1); + // Invalidate the previous Complete before archiving or GS setup. + if (!write_state("Running", {})) + { + const std::string invalidated = run_directory_ + "/uncommitted_previous.status"; + std::rename(status_path.c_str(), invalidated.c_str()); + fail("Cannot establish the current DFPT Running status"); + } + if (!previous.empty()) + { + const std::string saved_path = run_directory_ + "/previous.status"; + std::ofstream saved(saved_path); + saved << previous; + saved.close(); + if (saved.fail()) + { + fail("Cannot preserve the previous DFPT status: " + saved_path); + } + record_file(saved_path); + } + staging_directory_ = run_directory_ + "/products"; + if (mkdir(staging_directory_.c_str(), 0700) != 0) + { + fail("Cannot create DFPT staging directory: " + staging_directory_); + } + archive_previous_products(); + std::cout << " DFPT run_id=" << run_id_ << " state=Running" << std::endl; +} + +void DFPT_RunSession::archive_previous_products() +{ + DIR *directory = opendir(output_directory_.c_str()); + if (directory == nullptr) + { + fail("Cannot inspect old DFPT products: " + output_directory_); + } + std::vector names; + errno = 0; + for (dirent *entry = readdir(directory); entry != nullptr; entry = readdir(directory)) + { + const std::string name = entry->d_name; + if (dyn_name(name)) + { + names.push_back(name); + } + } + const int read_error = errno; + const int close_error = closedir(directory); + if (read_error != 0 || close_error != 0) + { + fail("Cannot finish reading the DFPT output directory"); + } + for (const std::string &name : names) + { + const std::string old_path = output_directory_ + "/" + name; + record_read(old_path); + if (!owned_dyn(old_path)) + { + fail("Cannot establish ownership of an old dyn path; use a fresh output suffix: " + old_path); + } + } + const std::string history = run_directory_ + "/previous"; + if (!names.empty() && mkdir(history.c_str(), 0700) != 0) + { + fail("Cannot create DFPT history directory: " + history); + } + for (const std::string &name : names) + { + const std::string old_path = output_directory_ + "/" + name; + const std::string archived_path = history + "/" + name; + if (std::rename(old_path.c_str(), archived_path.c_str()) != 0) + { + fail("Cannot preserve the old DFPT product: " + old_path); + } + record_file(archived_path); + } +} + +void DFPT_RunSession::verify() +{ + if (state_ != State::Running) + { + fail("DFPT results cannot be verified in the current session state"); + } + state_ = State::Verified; + if (rank_ == 0 && !write_state("Verified", {})) + { + fail("Cannot record verified DFPT results"); + } +} + +void DFPT_RunSession::commit(int nq, bool write_dyn) +{ + if (state_ != State::Verified || nq <= 0) + { + fail("DFPT publication requires verified results and a valid q count"); + } + std::vector products; + if (rank_ == 0 && write_dyn) + { + for (int q = 0; q < nq; ++q) + { + const std::string name = "dyn.q" + std::to_string(q); + const std::string staged = staging_directory_ + "/" + name; + const std::string destination = output_directory_ + "/" + name; + record_read(staged); + if (!owned_dyn(staged)) + { + fail("Missing or invalid staged DFPT product: " + staged); + } + // link is an atomic no-overwrite publication on this filesystem; + // all generation files were staged beneath the same output root. + if (link(staged.c_str(), destination.c_str()) != 0) + { + fail("Cannot publish DFPT product without overwriting another file: " + destination); + } + if (unlink(staged.c_str()) != 0) + { + fail("Cannot finish staging the DFPT product: " + staged); + } + products.push_back(name); + record_file(destination); + } + } + if (rank_ == 0 && !write_state("Complete", products)) + { + fail("Cannot commit DFPT Complete status after product publication"); + } + state_ = State::Complete; +} +} // namespace ModuleDFPT diff --git a/source/source_pw/module_dfpt/dfpt_run_session.h b/source/source_pw/module_dfpt/dfpt_run_session.h new file mode 100644 index 00000000000..1968b1c515f --- /dev/null +++ b/source/source_pw/module_dfpt/dfpt_run_session.h @@ -0,0 +1,46 @@ +#ifndef DFPT_RUN_SESSION_H +#define DFPT_RUN_SESSION_H + +#include +#include +#include + +namespace ModuleDFPT +{ +/// One production invocation owns its output generation. An incomplete or +/// failed generation never inherits a previous Complete marker. +class DFPT_RunSession +{ + public: + DFPT_RunSession() = default; + void begin(const std::string &output_directory, int rank, std::ostream *running_log); + void verify(); + void commit(int nq, bool write_dyn); + void fail(const std::string &reason); + const std::string &staging_directory() const { return staging_directory_; } + const std::string &run_id() const { return run_id_; } + std::ostream *running_log() const { return running_log_; } + + private: + enum class State + { + Idle, + Running, + Verified, + Complete, + Failed + }; + bool write_state(const char *state, const std::vector &products); + void archive_previous_products(); + void record_read(const std::string &path) const; + void record_file(const std::string &path) const; + State state_ = State::Idle; + int rank_ = 0; + std::string output_directory_; + std::string run_directory_; + std::string staging_directory_; + std::string run_id_; + std::ostream *running_log_ = nullptr; +}; +} // namespace ModuleDFPT +#endif diff --git a/source/source_pw/module_dfpt/dfpt_stern.cpp b/source/source_pw/module_dfpt/dfpt_stern.cpp index e7a68768e51..b143eb8ce93 100644 --- a/source/source_pw/module_dfpt/dfpt_stern.cpp +++ b/source/source_pw/module_dfpt/dfpt_stern.cpp @@ -95,14 +95,15 @@ const char *DFPT_Stern::status_name(Status status) return "InvalidInput"; } -void DFPT_Stern::require_converged(const Result &result, const std::string &context) +bool DFPT_Stern::is_converged(const Result &result) +{ + return result.status == Status::Converged && result.residual_available && std::isfinite(result.residual) && + result.residual >= 0.0 && std::isfinite(result.threshold) && result.threshold > 0.0 && + result.residual < result.threshold; +} + +std::string DFPT_Stern::failure_message(const Result &result, const std::string &context) { - if (result.status == Status::Converged && result.residual_available && std::isfinite(result.residual) && - result.residual >= 0.0 && std::isfinite(result.threshold) && result.threshold > 0.0 && - result.residual < result.threshold) - { - return; - } Status reason = result.status; if (reason == Status::Converged) { @@ -129,7 +130,16 @@ void DFPT_Stern::require_converged(const Result &result, const std::string &cont message << "unavailable"; } message << ". Stopping before response consumption."; - ModuleBase::WARNING_QUIT("DFPT_Stern", message.str()); + return message.str(); +} + +void DFPT_Stern::require_converged(const Result &result, const std::string &context) +{ + if (!is_converged(result)) + { + const std::string message = failure_message(result, context); + ModuleBase::WARNING_QUIT("DFPT_Stern", message); + } } int DFPT_Stern::solve( @@ -304,10 +314,10 @@ DFPT_Stern::Result DFPT_Stern::solve_impl( { return result; } - result.status = Status::IterationLimit; - if (breakdown) + result.status = Status::Breakdown; + if (!breakdown && result.iterations == max_iter) { - result.status = Status::Breakdown; + result.status = Status::IterationLimit; } if (result.residual < conv_thr) { diff --git a/source/source_pw/module_dfpt/dfpt_stern.h b/source/source_pw/module_dfpt/dfpt_stern.h index b3411ee811a..37a0ad04791 100644 --- a/source/source_pw/module_dfpt/dfpt_stern.h +++ b/source/source_pw/module_dfpt/dfpt_stern.h @@ -70,6 +70,8 @@ class DFPT_Stern std::vector> &dpsi) const; /// The caller supplies task identity; failure never reaches a consumer. + static bool is_converged(const Result &result); + static std::string failure_message(const Result &result, const std::string &context); static void require_converged(const Result &result, const std::string &context); static const char *status_name(Status status); diff --git a/source/source_pw/module_dfpt/dfpt_write_dyn.cpp b/source/source_pw/module_dfpt/dfpt_write_dyn.cpp index ec1a8c65cb6..f579cc5698a 100644 --- a/source/source_pw/module_dfpt/dfpt_write_dyn.cpp +++ b/source/source_pw/module_dfpt/dfpt_write_dyn.cpp @@ -36,7 +36,7 @@ namespace ModuleDFPT /// where AMU_RY = AMU_AU / 2 = 911.444... (constants.f90 line 57) static double amu_to_ry(double mass_amu) { return mass_amu * 911.4442431045; } -void DFPT_Write_Dyn( +bool DFPT_Write_Dyn( const UnitCell &ucell, const DFPT_PW_Data &data, int nq, @@ -52,7 +52,7 @@ void DFPT_Write_Dyn( if (my_rank != 0) { ModuleBase::timer::end("ModuleDFPT", "DFPT_Write_Dyn"); - return; + return true; } const int nat = ucell.nat; @@ -62,9 +62,11 @@ void DFPT_Write_Dyn( for (int q = 0; q < nq; ++q) { const ModuleBase::ComplexMatrix dm = data.has_dynmat_raw(q) ? data.get_dynmat_raw(q) : data.get_dynmat(q); - if (dm.nr != nat3) + if (dm.nr != nat3 || dm.nc != nat3) { - continue; + ModuleBase::WARNING("DFPT_Write_Dyn", "missing complete dynamical matrix"); + ModuleBase::timer::end("ModuleDFPT", "DFPT_Write_Dyn"); + return false; } std::ostringstream name; @@ -72,11 +74,12 @@ void DFPT_Write_Dyn( std::ofstream out(name.str()); if (!out.is_open()) { - // report the full failed path and skip this q + // Report the failure; a caller must not commit this output set. std::ostringstream err; - err << "DFPT_Write_Dyn: cannot open " << name.str() << " for writing; skipping q=" << q; + err << "DFPT_Write_Dyn: cannot open " << name.str() << " for writing; q=" << q; ModuleBase::WARNING("DFPT_Write_Dyn", err.str()); - continue; + ModuleBase::timer::end("ModuleDFPT", "DFPT_Write_Dyn"); + return false; } out << std::setprecision(10) << std::scientific; @@ -210,24 +213,19 @@ void DFPT_Write_Dyn( std::ostringstream err; err << "DFPT_Write_Dyn: write error on " << name.str(); ModuleBase::WARNING("DFPT_Write_Dyn", err.str()); + ModuleBase::timer::end("ModuleDFPT", "DFPT_Write_Dyn"); + return false; } - else + std::ostringstream ok; + ok << "DFPT_Write_Dyn: wrote " << name.str() << std::endl; + if (running_log != nullptr) { - // log the created file path (AGENTS rule 16): the running log - // receives the record through the explicit running_log - // dependency (serial runs open a separate running log stream - // in global_file.cpp, so stdout alone does not reach it); - // stdout keeps a terminal echo - std::ostringstream ok; - ok << "DFPT_Write_Dyn: wrote " << name.str() << std::endl; - if (running_log != nullptr) - { - (*running_log) << " " << ok.str(); - } - std::cout << " " << ok.str(); + (*running_log) << " " << ok.str(); } + std::cout << " " << ok.str(); } ModuleBase::timer::end("ModuleDFPT", "DFPT_Write_Dyn"); + return true; } } // namespace ModuleDFPT diff --git a/source/source_pw/module_dfpt/dfpt_write_dyn.h b/source/source_pw/module_dfpt/dfpt_write_dyn.h index a653458e730..661fb4a13ac 100644 --- a/source/source_pw/module_dfpt/dfpt_write_dyn.h +++ b/source/source_pw/module_dfpt/dfpt_write_dyn.h @@ -19,8 +19,8 @@ namespace ModuleDFPT /// /// running_log (nullable): the running log stream for the created-file /// confirmations (AGENTS rule 16); when null the confirmation goes to -/// stdout only. -void DFPT_Write_Dyn( +/// stdout only. Returns false on a missing matrix or any write failure. +bool DFPT_Write_Dyn( const UnitCell &ucell, const DFPT_PW_Data &data, int nq, diff --git a/source/source_pw/module_dfpt/unittests/CMakeLists.txt b/source/source_pw/module_dfpt/unittests/CMakeLists.txt index 469f0d240f4..31ca75c3c66 100644 --- a/source/source_pw/module_dfpt/unittests/CMakeLists.txt +++ b/source/source_pw/module_dfpt/unittests/CMakeLists.txt @@ -30,6 +30,11 @@ add_library( ../../../source_basis/module_pw/pw_transform.cpp ../../../source_basis/module_pw/pw_transform_k.cpp) +addtest( + TARGET MODULE_DFPT_session_serial + LIBS parameter base device + SOURCES test_dfpt_run_session.cpp ../dfpt_run_session.cpp) + addtest( TARGET MODULE_DFPT_pert_serial LIBS parameter dfpt_planewave_serial device base symmetry @@ -212,6 +217,7 @@ if(ENABLE_MPI) KEEP_FEATURE_DEFINITIONS __MPI LIBS parameter base device symmetry planewave SOURCES test_dfpt_pw_run.cpp + ../dfpt_run_session.cpp ../dfpt_pw.cpp ../dfpt_pw_init.cpp ../dfpt_pw_run.cpp diff --git a/source/source_pw/module_dfpt/unittests/test_dfpt_run_session.cpp b/source/source_pw/module_dfpt/unittests/test_dfpt_run_session.cpp new file mode 100644 index 00000000000..9e965ac1b35 --- /dev/null +++ b/source/source_pw/module_dfpt/unittests/test_dfpt_run_session.cpp @@ -0,0 +1,223 @@ +#include "source_pw/module_dfpt/dfpt_run_session.h" +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +void write_text(const std::string &path, const std::string &text) +{ + std::ofstream out(path); + out << text; + out.close(); + ASSERT_FALSE(out.fail()); +} + +std::string read_text(const std::string &path) +{ + std::ifstream in(path); + std::ostringstream text; + text << in.rdbuf(); + return text.str(); +} + +void remove_scratch(const std::string &path) +{ + struct stat info; + if (lstat(path.c_str(), &info) != 0) + { + return; + } + if (S_ISDIR(info.st_mode)) + { + DIR *directory = opendir(path.c_str()); + if (directory == nullptr) + { + return; + } + for (dirent *entry = readdir(directory); entry != nullptr; entry = readdir(directory)) + { + const std::string name = entry->d_name; + if (name != "." && name != "..") + { + remove_scratch(path + "/" + name); + } + } + closedir(directory); + } + std::remove(path.c_str()); +} + +class DFPTSessionTest : public ::testing::Test +{ + protected: + std::string root; + std::ostringstream log; + const std::string dyn = "Dynamical matrix file\nABACUS DFPT output\nowned test payload\n"; + void SetUp() override + { + const std::string pattern = ::testing::TempDir() + "/dfpt-session-XXXXXX"; + std::vector name(pattern.begin(), pattern.end()); + name.push_back('\0'); + char *created = mkdtemp(name.data()); + ASSERT_NE(created, nullptr); + root = created; + // This target performs no OpenMP/FFT work. Fork preserves the same + // scratch path so the parent can audit the failed child's outputs. + ::testing::FLAGS_gtest_death_test_style = "fast"; + } + void TearDown() override { remove_scratch(root); } + std::string status() const { return read_text(root + "/dfpt.status"); } +}; +} // namespace + +TEST_F(DFPTSessionTest, ArchivesOnlyOwnedProductsBeforeComputation) +{ + write_text(root + "/dyn.q0", dyn); + write_text(root + "/keep.txt", "user file"); + write_text(root + "/dyn.qnotes", "not a numbered product"); + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + EXPECT_NE(status().find("state Running"), std::string::npos); + EXPECT_EQ(access((root + "/dyn.q0").c_str(), F_OK), -1); + EXPECT_EQ(read_text(root + "/" + session.run_id() + "/previous/dyn.q0"), dyn); + EXPECT_EQ(read_text(root + "/keep.txt"), "user file"); + EXPECT_EQ(read_text(root + "/dyn.qnotes"), "not a numbered product"); +} + +TEST_F(DFPTSessionTest, CompleteFollowsAllProductPublication) +{ + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + write_text(session.staging_directory() + "/dyn.q0", dyn); + write_text(session.staging_directory() + "/dyn.q1", dyn); + session.verify(); + EXPECT_NE(status().find("state Verified"), std::string::npos); + session.commit(2, true); + EXPECT_NE(status().find("state Complete"), std::string::npos); + EXPECT_NE(status().find("product_count 2"), std::string::npos); + EXPECT_EQ(read_text(root + "/dyn.q0"), dyn); + EXPECT_EQ(read_text(root + "/dyn.q1"), dyn); +} + +TEST_F(DFPTSessionTest, SuccessThenFailureCannotInheritComplete) +{ + ModuleDFPT::DFPT_RunSession first; + first.begin(root, 0, &log); + write_text(first.staging_directory() + "/dyn.q0", dyn); + first.verify(); + first.commit(1, true); + ModuleDFPT::DFPT_RunSession second; + second.begin(root, 0, &log); + EXPECT_NE(first.run_id(), second.run_id()); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + second.fail("test response failed"); + }, + ::testing::ExitedWithCode(1), "test response failed"); + EXPECT_NE(status().find("state Failed"), std::string::npos); + EXPECT_EQ(status().find("state Complete"), std::string::npos); + EXPECT_EQ(access((root + "/dyn.q0").c_str(), F_OK), -1); + EXPECT_EQ(read_text(root + "/" + second.run_id() + "/previous/dyn.q0"), dyn); +} + +TEST_F(DFPTSessionTest, UnknownProductIsPreservedAndRejected) +{ + write_text(root + "/dyn.q0", "user data"); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + }, + ::testing::ExitedWithCode(1), "ownership"); + EXPECT_EQ(read_text(root + "/dyn.q0"), "user data"); + EXPECT_NE(status().find("state Failed"), std::string::npos); +} + +TEST_F(DFPTSessionTest, SymlinkProductIsNotFollowed) +{ + write_text(root + "/keep.txt", dyn); + ASSERT_EQ(symlink("keep.txt", (root + "/dyn.q0").c_str()), 0); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + }, + ::testing::ExitedWithCode(1), "ownership"); + EXPECT_EQ(read_text(root + "/keep.txt"), dyn); + struct stat info; + ASSERT_EQ(lstat((root + "/dyn.q0").c_str(), &info), 0); + EXPECT_TRUE(S_ISLNK(info.st_mode)); +} + +TEST_F(DFPTSessionTest, MissingSecondProductPreventsCompleteAfterPartialPublication) +{ + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + write_text(session.staging_directory() + "/dyn.q0", dyn); + session.verify(); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + session.commit(2, true); + }, + ::testing::ExitedWithCode(1), "Missing or invalid staged"); + EXPECT_NE(status().find("state Failed"), std::string::npos); + EXPECT_EQ(status().find("state Complete"), std::string::npos); +} + +TEST_F(DFPTSessionTest, CannotPublishBeforeVerification) +{ + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + write_text(session.staging_directory() + "/dyn.q0", dyn); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + session.commit(1, true); + }, + ::testing::ExitedWithCode(1), "requires verified"); + EXPECT_EQ(access((root + "/dyn.q0").c_str(), F_OK), -1); + EXPECT_NE(status().find("state Failed"), std::string::npos); +} + +TEST_F(DFPTSessionTest, PublicationDoesNotOverwriteANewForeignFile) +{ + ModuleDFPT::DFPT_RunSession session; + session.begin(root, 0, &log); + write_text(session.staging_directory() + "/dyn.q0", dyn); + write_text(root + "/dyn.q0", "new user file"); + session.verify(); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + session.commit(1, true); + }, + ::testing::ExitedWithCode(1), "without overwriting"); + EXPECT_EQ(read_text(root + "/dyn.q0"), "new user file"); + EXPECT_EQ(status().find("state Complete"), std::string::npos); +} + +TEST_F(DFPTSessionTest, InterruptedGenerationCannotBeReusedAsComplete) +{ + ModuleDFPT::DFPT_RunSession first; + first.begin(root, 0, &log); + EXPECT_EXIT( + { + std::cout.rdbuf(std::cerr.rdbuf()); + ModuleDFPT::DFPT_RunSession second; + second.begin(root, 0, &log); + }, + ::testing::ExitedWithCode(1), "incomplete or active"); + EXPECT_NE(status().find("state Running"), std::string::npos); + EXPECT_EQ(status().find("state Complete"), std::string::npos); +} diff --git a/source/source_pw/module_dfpt/unittests/test_dfpt_write_dyn.cpp b/source/source_pw/module_dfpt/unittests/test_dfpt_write_dyn.cpp index 1e2b866f40e..5604065653a 100644 --- a/source/source_pw/module_dfpt/unittests/test_dfpt_write_dyn.cpp +++ b/source/source_pw/module_dfpt/unittests/test_dfpt_write_dyn.cpp @@ -202,3 +202,11 @@ TEST_F(DFPTWriteDynTest, ArbitraryOrderingAllowedWhenComputeQ0Off) ModuleBase::Vector3(0.0, 0.0, 0.0)}); EXPECT_NO_THROW(ModuleDFPT::validate_q_ordering(qlist_, false)); } + +TEST_F(DFPTWriteDynTest, MissingMatrixReportsFailure) +{ + set_qvecs({ModuleBase::Vector3(0.0, 0.0, 0.0)}); + std::ostringstream running_log; + const bool written = DFPT_Write_Dyn(ucell_, data_, 1, testing::TempDir(), 0, &running_log); + EXPECT_FALSE(written); +} diff --git a/tests/integrate/CMakeLists.txt b/tests/integrate/CMakeLists.txt index 2387f60664f..cf8ed3f8e5b 100644 --- a/tests/integrate/CMakeLists.txt +++ b/tests/integrate/CMakeLists.txt @@ -36,6 +36,24 @@ endif() # Cheap collector regressions; no ABACUS calculation or finite differences. find_program(LR_FORCE_TEST_PYTHON python3) if(LR_FORCE_TEST_PYTHON) + add_test( + NAME dfpt_session_validator + COMMAND + ${LR_FORCE_TEST_PYTHON} -m unittest discover -s + ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools -p + test_check_dfpt_session.py) + foreach(session_case outer inner ground_state foreign) + add_test( + NAME dfpt_session_${session_case} + COMMAND + ${LR_FORCE_TEST_PYTHON} + ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools/check_dfpt_session.py + --abacus ${ABACUS_BIN_PATH} --fixtures + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/dfpt_failure --pseudo-dir + ${ABACUS_TEST_DIR}/PP_ORB --mode ${session_case}) + set_tests_properties(dfpt_session_${session_case} PROPERTIES TIMEOUT 180 + PROCESSORS 1) + endforeach() # Expected nonzero exits cannot pass the ordinary Autotest contract. add_test( NAME dfpt_failure_validator diff --git a/tests/integrate/fixtures/dfpt_failure/README.md b/tests/integrate/fixtures/dfpt_failure/README.md index 9906752ba50..f7352d8a688 100644 --- a/tests/integrate/fixtures/dfpt_failure/README.md +++ b/tests/integrate/fixtures/dfpt_failure/README.md @@ -20,10 +20,16 @@ stdout and warning.log, and no newly generated formal tensor/frequency or dyn output. A crash, timeout or unrelated error is a test failure. These cases are registered separately because Autotest treats a nonzero exit -as failure. Normal numerical regressions remain Autotest cases. They do not -test reuse of old outputs; output-generation validation is separate work. +as failure. Normal numerical regressions remain Autotest cases. The additional session driver tests reuse of old outputs with the dedicated +`session_success` and `ground_state` fixtures. The `inner_*` fixtures instead set one linear step and 60 outer steps. They require an IterationLimit diagnostic from the first occupied band before any outer iteration finishes. `inner_position` checks the position-response gate before dielectric or Born consumers; finite q retains the explicit k list. + +The session driver first completes the fixed success input, then copies one +of the dedicated failure fixtures unchanged into the same working directory. +It checks a new Failed identity, preserved prior dyn bytes, no current dyn +products, and unchanged unrelated files. A separate mode rejects a foreign +numbered dyn file before GS setup. diff --git a/tests/integrate/fixtures/dfpt_failure/ground_state/INPUT b/tests/integrate/fixtures/dfpt_failure/ground_state/INPUT new file mode 100644 index 00000000000..ba34e6264d2 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/ground_state/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 1 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 60 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 120 +dfpt_compute_q0 true +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/ground_state/KPT b/tests/integrate/fixtures/dfpt_failure/ground_state/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/ground_state/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/ground_state/QFILE b/tests/integrate/fixtures/dfpt_failure/ground_state/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/ground_state/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/ground_state/STRU b/tests/integrate/fixtures/dfpt_failure/ground_state/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/ground_state/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/ground_state/expected.json b/tests/integrate/fixtures/dfpt_failure/ground_state/expected.json new file mode 100644 index 00000000000..1256587c0ad --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/ground_state/expected.json @@ -0,0 +1,6 @@ +{ + "kind": "ground_state", + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ] +} diff --git a/tests/integrate/fixtures/dfpt_failure/session_success/INPUT b/tests/integrate/fixtures/dfpt_failure/session_success/INPUT new file mode 100644 index 00000000000..ae07c6f6a93 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/session_success/INPUT @@ -0,0 +1,24 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +basis_type pw +nbands 8 +symmetry -1 +pseudo_dir ./PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-14 +scf_nmax 100 +smearing_method fixed +ks_solver dav +pw_diag_thr 1e-14 +dfpt_qfile QFILE +dfpt_conv_thr 1e-8 +dfpt_max_iter 60 +dfpt_lin_conv_thr 1e-10 +dfpt_lin_max_iter 120 +dfpt_compute_q0 true +dfpt_asr no +dfpt_loto false +dfpt_out_dyn true diff --git a/tests/integrate/fixtures/dfpt_failure/session_success/KPT b/tests/integrate/fixtures/dfpt_failure/session_success/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/session_success/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/integrate/fixtures/dfpt_failure/session_success/QFILE b/tests/integrate/fixtures/dfpt_failure/session_success/QFILE new file mode 100644 index 00000000000..6055821cd29 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/session_success/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0 0 0 1 diff --git a/tests/integrate/fixtures/dfpt_failure/session_success/STRU b/tests/integrate/fixtures/dfpt_failure/session_success/STRU new file mode 100644 index 00000000000..29b11e209ba --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/session_success/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/integrate/fixtures/dfpt_failure/session_success/expected.json b/tests/integrate/fixtures/dfpt_failure/session_success/expected.json new file mode 100644 index 00000000000..94388e9e905 --- /dev/null +++ b/tests/integrate/fixtures/dfpt_failure/session_success/expected.json @@ -0,0 +1,6 @@ +{ + "kind": "session_success", + "pseudopotentials": [ + "Si_ONCV_PBE-1.0.upf" + ] +} diff --git a/tests/integrate/validation_tools/check_dfpt_session.py b/tests/integrate/validation_tools/check_dfpt_session.py new file mode 100644 index 00000000000..099d9d5e2d7 --- /dev/null +++ b/tests/integrate/validation_tools/check_dfpt_session.py @@ -0,0 +1,123 @@ +"""Audit a successful DFPT run followed by failure in the same output suffix.""" + +import argparse +import hashlib +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + +from check_dfpt_failure import validate_failure + + +def parse_status(text): + lines = text.splitlines() + if len(lines) < 4 or lines[0] != "ABACUS DFPT session 1": + raise AssertionError("Missing or unsupported DFPT status header") + fields = [line.split() for line in lines[1:]] + if (fields[0][:1] != ["run_id"] or len(fields[0]) != 2 or + not re.fullmatch(r"\.dfpt-run-[A-Za-z0-9]+", fields[0][1])): + raise AssertionError("Invalid run identity") + if fields[1] not in [["state", state] for state in ("Running", "Verified", "Failed", "Complete")]: + raise AssertionError("Invalid run state") + if fields[2][:1] != ["product_count"] or len(fields[2]) != 2: + raise AssertionError("Missing product count") + count = int(fields[2][1]) + products = fields[3:] + if count < 0 or len(products) != count: + raise AssertionError("Incomplete product list") + names = [] + for row in products: + if len(row) != 2 or row[0] != "product" or not re.fullmatch(r"dyn\.q[0-9]+", row[1]): + raise AssertionError("Invalid product path") + names.append(row[1]) + if len(set(names)) != len(names) or (fields[1][1] != "Complete" and names): + raise AssertionError("Invalid product ownership") + return dict(run_id=fields[0][1], state=fields[1][1], products=names) + + +def require_complete(text, current_run_id, actual_products): + status = parse_status(text) + if status["state"] != "Complete" or status["run_id"] != current_run_id: + raise AssertionError("No completion for the current invocation") + if sorted(status["products"]) != sorted(actual_products): + raise AssertionError("Current product set differs from completion manifest") + return status + + +def run_case(executable, fixtures, pseudo_dir, mode): + import json + env = dict(os.environ, OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1") + with tempfile.TemporaryDirectory(prefix="abacus-dfpt-session-") as scratch: + work = Path(scratch) + (work / "PP_ORB").mkdir() + expected = json.loads((fixtures / "session_success/expected.json").read_text()) + for name in expected["pseudopotentials"]: + if Path(name).name != name: + raise AssertionError("Unsafe pseudopotential name") + shutil.copy2(pseudo_dir / name, work / "PP_ORB" / name) + + def calculate(name): + for filename in ("INPUT", "KPT", "STRU", "QFILE"): + shutil.copy2(fixtures / name / filename, work / filename) + return subprocess.run([str(executable)], cwd=str(work), env=env, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=120) + + out = work / "OUT.autotest" + if mode == "foreign": + out.mkdir() + foreign = out / "dyn.q0" + foreign.write_text("user-owned data\n") + result = calculate("session_success") + assert result.returncode == 1, result.stdout + assert "ownership" in result.stdout, result.stdout + assert foreign.read_text() == "user-owned data\n" + assert parse_status((out / "dfpt.status").read_text())["state"] == "Failed" + print("Verified foreign-file protection") + return + + success = calculate("session_success") + assert success.returncode == 0, success.stdout + match = re.search(r"DFPT run_id=(\S+) state=Running", success.stdout) + assert match, success.stdout + old_id = match[1] + old = require_complete((out / "dfpt.status").read_text(), old_id, + [p.name for p in out.glob("dyn.q*")]) + assert old["products"] == ["dyn.q0"] + saved = {name: hashlib.sha256((out / name).read_bytes()).hexdigest() for name in old["products"]} + (out / "keep-user.txt").write_text("preserve this unrelated file\n") + failed_name = {"outer": "displacement", "inner": "inner_position", "ground_state": "ground_state"}[mode] + failed = calculate(failed_name) + assert failed.returncode == 1, failed.stdout + status = parse_status((out / "dfpt.status").read_text()) + assert status["state"] == "Failed" and status["run_id"] != old_id, status + assert not list(out.glob("dyn.q*")), failed.stdout + assert (out / "keep-user.txt").read_text() == "preserve this unrelated file\n" + history = out / status["run_id"] / "previous" + for name, digest in saved.items(): + assert hashlib.sha256((history / name).read_bytes()).hexdigest() == digest + assert (out / status["run_id"] / "previous.status").read_text().find("run_id " + old_id) >= 0 + if mode == "ground_state": + assert "requires a converged ground state" in failed.stdout, failed.stdout + assert "DFPT phonon frequencies" not in failed.stdout + else: + expected = json.loads((fixtures / failed_name / "expected.json").read_text()) + validate_failure(failed.returncode, failed.stdout, (out / "warning.log").read_text(), + (out / "running_scf.log").read_text(), [], expected) + print("Verified success then " + mode + " failure: old products preserved; current session Failed") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--abacus", type=Path, required=True) + parser.add_argument("--fixtures", type=Path, required=True) + parser.add_argument("--pseudo-dir", type=Path, required=True) + parser.add_argument("--mode", choices=("outer", "inner", "ground_state", "foreign"), required=True) + args = parser.parse_args() + run_case(args.abacus.resolve(), args.fixtures.resolve(), args.pseudo_dir.resolve(), args.mode) + + +if __name__ == "__main__": + main() diff --git a/tests/integrate/validation_tools/test_check_dfpt_session.py b/tests/integrate/validation_tools/test_check_dfpt_session.py new file mode 100644 index 00000000000..dbef7263819 --- /dev/null +++ b/tests/integrate/validation_tools/test_check_dfpt_session.py @@ -0,0 +1,36 @@ +"""A completion marker must belong to the current invocation and product set.""" +import unittest + +from check_dfpt_session import parse_status, require_complete + + +class SessionAuditTest(unittest.TestCase): + def setUp(self): + self.text = ("ABACUS DFPT session 1\nrun_id .dfpt-run-ABC123\n" + "state Complete\nproduct_count 1\nproduct dyn.q0\n") + + def test_complete_for_current_run(self): + require_complete(self.text, ".dfpt-run-ABC123", ["dyn.q0"]) + + def test_stale_or_incomplete_status_cannot_pass(self): + with self.assertRaises(AssertionError): + require_complete(self.text, ".dfpt-run-NEW123", ["dyn.q0"]) + for state in ("Failed", "Running", "Verified"): + text = self.text.replace("state Complete", "state " + state).replace( + "product_count 1\nproduct dyn.q0", "product_count 0") + with self.subTest(state=state), self.assertRaises(AssertionError): + require_complete(text, ".dfpt-run-ABC123", []) + + def test_partial_or_foreign_products_cannot_pass(self): + for names in ([], ["dyn.q0", "dyn.q1"]): + with self.subTest(names=names), self.assertRaises(AssertionError): + require_complete(self.text, ".dfpt-run-ABC123", names) + for text in (self.text.replace("dyn.q0", "../dyn.q0"), + self.text.replace("product_count 1", "product_count 2"), + self.text + "product dyn.q0\n"): + with self.subTest(text=text), self.assertRaises(AssertionError): + parse_status(text) + + +if __name__ == "__main__": + unittest.main() From 4e08ac5184b1f28fae4bc40f282e16b5fce4008f Mon Sep 17 00:00:00 2001 From: Zanthoxylum <105619360+Zanthoxylum@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:10:00 +0800 Subject: [PATCH 4/4] fix(dfpt): route the ground-state convergence rejection through the session Merging develop brought the direct validate_scf_convergence call into run_gs; it WARNING_QUITs before runner()'s session-fail bookkeeping runs, leaving the session state stale at 'Running' when the ground state fails (the ground_state failure fixture catches this after the sync). The session-fail path performs the same rejection with state recording and exit code 1, so the direct call is removed and the guard deliberately routes through the session. The validator itself and its unit test are unchanged. 25/25 ctest targets (module + session + failure fixtures) and the dfpt_si_g anchor frequencies are unchanged after the fix. --- source/source_esolver/esolver_dfpt_pw.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/source_esolver/esolver_dfpt_pw.cpp b/source/source_esolver/esolver_dfpt_pw.cpp index 85bab28fd8f..f9cac50e024 100644 --- a/source/source_esolver/esolver_dfpt_pw.cpp +++ b/source/source_esolver/esolver_dfpt_pw.cpp @@ -296,7 +296,8 @@ void ESolver_DFPT_PW::run_gs(UnitCell &ucell) ModuleBase::TITLE("ESolver_DFPT_PW", "run_gs"); ESolver_KS_PW, base_device::DEVICE_CPU>::runner(ucell, 0); - ModuleDFPT::validate_scf_convergence(this->conv_esolver); + // An unconverged ground state is rejected via the session-fail path in + // runner(); a direct guard here would exit before the session records it. } void ESolver_DFPT_PW::init_dfpt(UnitCell &ucell)