From 21eb99559017ebd2ce10fae9deecd54b3aa1d67a Mon Sep 17 00:00:00 2001 From: lanshuyue <2000011337@stu.pku.edu.cn> Date: Fri, 27 Nov 2026 20:39:01 +0800 Subject: [PATCH 1/2] feat(scf): preserve per-iteration onsite Hubbard diagnostics --- docs/developers_guide/scf_diagnostics.md | 166 ++++++++++++++++++ source/Makefile.Objects | 1 + source/source_esolver/esolver_ks_lcao.cpp | 65 ++++++- source/source_esolver/esolver_ks_pw.cpp | 67 ++++++- source/source_estate/CMakeLists.txt | 1 + .../source_estate/module_charge/chg_drho.cpp | 52 ++++++ source/source_estate/module_charge/chg_drho.h | 17 ++ .../module_charge/unittests/test_chg_drho.cpp | 43 +++++ source/source_estate/scf_diagnostics.cpp | 106 +++++++++++ source/source_estate/scf_diagnostics.h | 60 +++++++ source/source_lcao/module_dftu/dftu_nao_ijr.h | 22 ++- .../source_lcao/module_dftu/dftu_nao_op.cpp | 65 +++++++ source/source_lcao/module_dftu/dftu_nao_op.h | 8 + .../module_dftu/unittests/CMakeLists.txt | 41 +++-- .../unittests/test_dftu_scf_diagnostics.cpp | 56 ++++++ source/source_pw/module_pwdft/dftu_pw.cpp | 52 ++++++ source/source_pw/module_pwdft/dftu_pw.h | 8 + 17 files changed, 801 insertions(+), 29 deletions(-) create mode 100644 docs/developers_guide/scf_diagnostics.md create mode 100644 source/source_estate/scf_diagnostics.cpp create mode 100644 source/source_estate/scf_diagnostics.h create mode 100644 source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp diff --git a/docs/developers_guide/scf_diagnostics.md b/docs/developers_guide/scf_diagnostics.md new file mode 100644 index 00000000000..abf962469f1 --- /dev/null +++ b/docs/developers_guide/scf_diagnostics.md @@ -0,0 +1,166 @@ +# Onsite LCAO SCF observer (local diagnostic build) + +Set `ABACUS_SCF_DIAGNOSTICS=1` in the runtime environment to enable the +observer. It writes one double-precision JSON record per completed electronic +iteration to `OUT./scf_diagnostics.jsonl`. No INPUT defaults, SCF +updates, thresholds, or mixing coefficients are changed. All MPI ranks +participate in the extra projection reductions; only rank zero writes the +file. Each record is flushed immediately. + +Supported scope: `dft_plus_u=1`, `nspin=2`, `symmetry=0`, `mixing_dftu=0`, +`mixing_dmr=0`. Unsupported layouts raise an error rather than being +reinterpreted as real collinear matrices. The analysis accepts any number of +atoms and iterations, and can preserve complex Hermitian matrices if supplied; +the source observer itself does not implement spinor or occupation-mixing +output. This is a local diagnostic extension, not an upstream feature. + +## Matrix definitions and timing + +`n_in` is a copy of the exact per-atom, per-spin buffer passed to +`DFTU_LCAO::cal_pot_onsite` in `DFTU_onsite::contribute_hubbard_atoms`. +When the first iteration has no DMR and constructs no Hubbard potential, +`n_in` is `null`. It must not be replaced with a zero matrix. + +`n_raw_out` projects the newly solved DMR using the same neighbor list, +two-center overlap table, contraction order, and MPI reduction as the original +operator. The pure projection helper does not write into `Plus_U_Base`, DMR, +the potential, or mixing buffers. It is observed after the base solver computes +DRHO, magnetism, gap, and energy, and before optional DMR mixing. Charge-density +mixing changes rho, not this solved DMR. + +`n_after_occupation_mixing` is `null`: no occupation mixer runs in this supported +onsite path. It is not a synonym for raw output or charge-mixed density. + +The representation is the real onsite projector basis, not the nonorthogonal +NAO coefficient matrix or a Mulliken/Lowdin population matrix. Projectors use +the first radial NAO channel, smoothed and normalized inside `onsite_radius`; +same-site angular channels form an orthogonal shell. There is no global +orthogonalization between different atomic sites. The contraction is +`n_mm' = `, evaluated with the original NAO real-space +density matrix and `` overlaps. Flattened matrices are row-major; +atoms are one-based and spin is zero-based. The signed real d-harmonic order is +`dz2, -dxz, -dyz, dx2-y2, dxy` (`m=0,+1,-1,+2,-2`). See `ylm.cpp`, +`dftu_nao_adj.cpp`, `atomic_radials.cpp`, and `smoothgen.cpp` for the angular +convention and radial normalization. + +## Energies and gap + +The source energy actually added as `E_plusU` is separately preserved as +`source_band_correction_eV`. For the supported collinear onsite path, +`cal_pot_onsite` accumulates **U/2 Tr(n_in^2)**. This is a band-energy +replacement correction, not the Dudarev functional. The latter is +`E_Dud = U/2 Tr(n - n^2)`. With `V_U = U(1/2 - n)`, the source expression +equals `E_Dud - Tr(V_U n)`. The analysis computes fractionality and the +Dudarev functional for both observed stages, and independently checks the +source correction against the input matrix. It does not modify the source +energy expression or total energy. In iteration one the source correction is +genuinely zero while the absent input remains `null`. + +`logged_E_gap_k_eV` is the unchanged `ElecState::bandgap`. Despite the log +label `E_gap(k)`, `cal_bandgap` searches all sampled k points and bands around +`ef + 1e-5 Ry`; this is not an array of gaps at individual k points or a minimum +direct gap. A metallic sampled spectrum can have a positive level spacing by +this definition. `fundamental_gap_eV` is explicitly `null`: this observer does +not independently establish the fundamental gap or metallic character. + +`total_energy_eV` is the original electronic free energy `f_en.etot` per cell. +Cell magnetism is calculated from rho before charge mixing. Local d-shell +moments derived from raw occupation traces are partial projected moments, +not complete atomic Mulliken moments. + +## Validation + +Focused writer tests cover precision, absent input, append behavior, writer +rank, and preservation of observational copies. A same-input VO2/U6 comparison +with diagnostics disabled checks the numerical trajectory at stdout/log +precision. Derived-data tests check complex Hermitian norms and missing first +differences. No missing matrix, step, gap, or residual is interpolated. + +## Charge and spin density channels (schema 2) + +Immediately before `ESolver_KS::iter_finish` calls charge mixing, the LCAO +observer reads `chr.rho` (raw output) and `chr.rho_save` (input saved before +sum_band). The stateless `module_charge::cal_spin_channel_residuals` computes + +``` +Rc = omega / (nxyz * nelec) * sum_grid |delta_rho_up + delta_rho_down| +Rm = omega / (nxyz * nelec) * sum_grid |delta_rho_up - delta_rho_down| +``` + +Each sum uses `Parallel_Reduce::reduce_pool`, exactly as the native real-space +DRHO (`scf_thr_type=2`). These dimensionless per-electron L1 residuals use the +same local grid, cell volume and electron count. No mixed density is read and +no density or mixer buffer is changed. They are channel norms, not an additive +split of DRHO: `max(Rc,Rm) <= DRHO <= Rc+Rm`. Pointwise the spin-resolved +DRHO integrand is `max(abs(delta_rho_c), abs(delta_rho_m))`. The observer rejects +other spin layouts or convergence metrics rather than silently reinterpreting +them. There is no need to substitute an L2 metric for this real-space L1 run. + +The actual `mixing_restart_count` is copied after iter_finish. The +`mixing_restart_executed` flag requires a positive restart threshold, the +current iteration equal to the scheduled step, and an already incremented +counter. Analysis additionally verifies the flag against counter increments. +For the fixed-U, no-DMR-mixing cases in this experiment the scheduled step +cannot move during execution. The unchanged source does the following: + +1. After a step with DRHO <= mixing_restart, schedule iteration k+1. +2. Skip density mixing on step k, retaining raw output (then normalize rho). +3. In the next iter_init, call init_mixing and increment restart_count. +4. Do not declare convergence on that restart step. Without U ramping the + scheduled step is not rearmed, so this is a single threshold-triggered event. + +Thus this experiment tests the program's combined raw-density handoff and +history reset, not an isolated algebraic deletion of historical vectors. +Source locations: `chg_routine.cpp::chgmixing_ks` and +`chgmixing_ks_lcao`; `chg_mix.cpp::init_mixing/reset_scf_history`. + +`scf_wall_seconds_before_occupation_observer` measures elapsed time since the +native iter_init timestamp, read just after base iter_finish and before the +extra occupation projection/writer. It includes the density observer and +native per-step output; it excludes the extra occupation observer. Summing it +is SCF iteration wall time, not process launch/initialization/finalization or +complete elapsed job wall time. `scf_converged` is the actual solver flag. +Local projected d moments in analysis are Tr(n_up_raw)-Tr(n_down_raw) in +muB per Hubbard atom; they are partial shell moments, not total atomic moments. + +## Shared PW observer (schema 3) + +The record model and writer now live in `source_estate/scf_diagnostics.*`, +under `ScfDiagnostics`, and are built unconditionally. LCAO still observes its +actual onsite input buffer; its established binary remains pinned for the +LCAO rerun campaign. + +For CPU PW, `DFTU_BASE::observe_occ_pw` projects the freshly solved wavefunctions +into a separate `OccupationMatrix`, using exactly the native onsite projector, +k-point occupations, scalar contraction and inter-pool reduction. It never calls +the occupation mixer or writes a potential, energy or production occupation +matrix. It restores the wavefunction k cursor and projector cache to that k. +The native `dftu.occmat()` retained after iter_init is the actual Hamiltonian +input; without a loaded seed the first input is absent. The raw output is not +the one-step-lagged native occ_mat.txt. Supported scope is collinear nspin=2, +double precision and mixing_dftu=0; no independent occupation mixer is claimed. + +PW projectors are the original smoothed onsite atomic projectors represented +in plane waves, with overlaps contracted over bands and weighted by the native +k-point occupations. They are not LCAO Mulliken populations. Each matrix is a +real scalar-spin matrix as in the native PW DFT+U implementation. Atom, spin, +orbital channel, actual U and full matrices are retained without averaging. +The same U/2 Tr(n_input^2) source correction convention applies in this scalar +PW path; Dudarev functionals remain derived quantities with a distinct name. + +The original PW `scf_thr_type=1` is retained. Its native residual combines a +Coulomb-weighted reciprocal charge term (G!=0) and an unweighted reciprocal +magnetic term (including G=0), rather than the LCAO per-electron L1 norm. To +compare charge/spin using identical norms, the PW observer additionally writes + +``` +Rc_L2 = omega/nelec * sqrt(sum_grid(delta_rho_c^2)/nxyz) +Rm_L2 = omega/nelec * sqrt(sum_grid(delta_rho_m^2)/nxyz) +``` + +Both are dimensionless L2 norms relative to the mean density nelec/omega, use +raw output minus saved input before mixing, and use the same pool reduction. +L1 channels are also retained as explicitly named additional measurements. +`scf_thr_type` identifies the native convergence metric. No equality between +these L2/L1 channels and the native PW DRHO is implied. L2 fields are null +where not observed; missing values are not replaced with zero. diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 8d0f34a6af5..292bc733955 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -282,6 +282,7 @@ OBJS_DEEPKS=lcao_deepks.o\ OBJS_ELECSTAT=elecstate.o\ + scf_diagnostics.o\ init_scf.o\ param_update.o\ estate_e_terms.o\ diff --git a/source/source_esolver/esolver_ks_lcao.cpp b/source/source_esolver/esolver_ks_lcao.cpp index 5ca47f36c5f..e899a53f2d7 100644 --- a/source/source_esolver/esolver_ks_lcao.cpp +++ b/source/source_esolver/esolver_ks_lcao.cpp @@ -10,6 +10,7 @@ #include "source_estate/elecstate_lcao.h" #include "source_estate/elecstate_tools.h" #include "source_estate/module_charge/chg_dmr.h" +#include "source_estate/module_charge/chg_drho.h" #include "source_estate/module_charge/chg_symm.h" #include "source_hamilt/hamilt_hs_adapter.h" #include "source_hamilt/hs_matrix_k.h" @@ -21,6 +22,7 @@ #include "source_lcao/module_deltaspin/deltaspin_lcao.h" #include "source_lcao/module_deltaspin/spin_constrain.h" #include "source_lcao/setup_dftu_lcao.h" +#include "source_lcao/module_dftu/dftu_nao_op.h" #include "source_pw/module_pwdft/dftu_base.h" // Plus_U_Base (PW and LCAO share it) #include "source_pw/module_pwdft/dftu_base_io.h" // append_ion_step_snapshot #ifdef __EXX @@ -382,6 +384,7 @@ template void ESolver_KS_LCAO::iter_init(UnitCell &ucell, const int istep, const int iter) { ModuleBase::TITLE("ESolver_KS_LCAO", "iter_init"); + std::ostream& running_log = GlobalV::ofs_running; // call iter_init() of ESolver_KS ESolver_KS::iter_init(ucell, istep, iter); @@ -397,13 +400,13 @@ void ESolver_KS_LCAO::iter_init(UnitCell &ucell, const int istep, const this->gint_info_->set_exec_precision(this->gint_precision_controller_.current_precision()); if (this->inp_->gint_precision == "mix") { - GlobalV::ofs_running << "\n >> Gint mixed-precision mode: starting SCF with fp32" + running_log << "\n >> Gint mixed-precision mode: starting SCF with fp32" << " (will switch to fp64 when drho is small enough)" << std::endl; std::cout << " >> NOTICE: Gint grid-integration starts with fp32 (mixed-precision mode)" << std::endl; } else if (this->inp_->gint_precision == "single") { - GlobalV::ofs_running << "\n >> Gint single-precision mode: using fp32 throughout SCF" << std::endl; + running_log << "\n >> Gint single-precision mode: using fp32 throughout SCF" << std::endl; std::cout << " >> NOTICE: Gint grid-integration uses fp32 throughout SCF (single-precision mode)" << std::endl; } @@ -583,6 +586,7 @@ void ESolver_KS_LCAO::iter_finish( bool &conv_esolver) { ModuleBase::TITLE("ESolver_KS_LCAO", "iter_finish"); + std::ostream& running_log = GlobalV::ofs_running; auto *hamilt_lcao = dynamic_cast *>(this->p_hamilt); @@ -625,6 +629,19 @@ void ESolver_KS_LCAO::iter_finish( this->pelec->set_spin_constrain_energy(escon); } + const bool observe_scf = ScfDiagnostics::scf_diagnostics_enabled() && this->inp_->dft_plus_u == 1; + double charge_residual = 0.0; + double magnetic_residual = 0.0; + if (observe_scf) + { + if (this->inp_->nspin != 2 || this->inp_->scf_thr_type != 2) + { + ModuleBase::WARNING_QUIT("SCF diagnostics", "Density channels require nspin=2 and scf_thr_type=2"); + } + module_charge::cal_spin_channel_residuals( + this->chr, this->inp_->nelec, *this->chr.rhopw, ucell.omega, charge_residual, magnetic_residual); + } + // call iter_finish() of ESolver_KS, where the band gap is calculated, // eig and occ are printed, magnetization is calculated, // charge mixing is performed, potential is updated, @@ -632,6 +649,48 @@ void ESolver_KS_LCAO::iter_finish( // JSON output and density restart files are handled ESolver_KS::iter_finish(ucell, istep, iter, conv_esolver); + if (observe_scf) + { + ScfDiagnostics::ScfDiagnosticStep diagnostic_step; + diagnostic_step.output_dir = global_out_dir; + diagnostic_step.rank = GlobalV::MY_RANK; + diagnostic_step.ionic_step = istep + 1; + diagnostic_step.iteration = iter; + diagnostic_step.threshold = this->scf_thr; + diagnostic_step.drho = this->drho; + diagnostic_step.charge_residual = charge_residual; + diagnostic_step.magnetic_residual = magnetic_residual; + const ModuleBase::TimePoint observer_time = ModuleBase::get_time(); + diagnostic_step.wall_seconds = ModuleBase::get_duration(this->iter_time, observer_time); + diagnostic_step.restart_count = this->p_chgmix->mixing_restart_count; + diagnostic_step.restart_scheduled_step = this->p_chgmix->mixing_restart_step; + diagnostic_step.restart_executed = this->inp_->mixing_restart > 0.0 + && iter == this->p_chgmix->mixing_restart_step && this->p_chgmix->mixing_restart_count > 0; + diagnostic_step.converged = conv_esolver; + diagnostic_step.gap_eV = this->pelec->bandgap * ModuleBase::Ry_to_eV; + diagnostic_step.total_magnetism = ucell.magnet.tot_mag; + diagnostic_step.absolute_magnetism = ucell.magnet.abs_mag; + diagnostic_step.total_energy_eV = this->pelec->f_en.etot * ModuleBase::Ry_to_eV; + diagnostic_step.source_band_correction_eV = this->dftu_->get_energy() * ModuleBase::Ry_to_eV; + diagnostic_step.mixing_type = this->inp_->mixing_mode; + diagnostic_step.beta = this->p_chgmix->get_mixing_beta(); + diagnostic_step.beta_mag = this->inp_->mixing_beta_mag; + diagnostic_step.mixing_dftu = this->inp_->mixing_dftu; + diagnostic_step.mixing_dmr = this->inp_->mixing_dmr; + diagnostic_step.mixing_restart = this->inp_->mixing_restart; + for (hamilt::Operator* op = hamilt_lcao->getOperator(); op != nullptr; op = op->next_op) + { + // The onsite Hubbard operator has its own lcao_dftu main-chain + // calculation type; no other operator shares this node type. + typedef hamilt::DFTU_onsite> OnsiteOperator; + OnsiteOperator* onsite = dynamic_cast(op); + if (onsite != nullptr) + { + onsite->write_scf_diagnostics(diagnostic_step, running_log); + } + } + } + // overwrite occ_mat.txt with the latest occupation matrix and the // actual charge-density residual; ESolver_KS::iter_finish() above has // computed drho for this electronic step. @@ -649,7 +708,7 @@ void ESolver_KS_LCAO::iter_finish( this->gint_info_->set_exec_precision(this->gint_precision_controller_.current_precision()); if (precision_switched) { - GlobalV::ofs_running << "\n >> Gint precision switched: fp32 -> fp64 (drho = " << this->drho << ")" + running_log << "\n >> Gint precision switched: fp32 -> fp64 (drho = " << this->drho << ")" << std::endl; std::cout << " >> NOTICE: Gint grid-integration precision switched from fp32 to fp64" << std::endl; } diff --git a/source/source_esolver/esolver_ks_pw.cpp b/source/source_esolver/esolver_ks_pw.cpp index 1215cde62df..d43039d5a2d 100644 --- a/source/source_esolver/esolver_ks_pw.cpp +++ b/source/source_esolver/esolver_ks_pw.cpp @@ -1,4 +1,6 @@ #include "esolver_ks_pw.h" +#include "source_estate/module_charge/chg_drho.h" +#include "source_pw/module_pwdft/dftu_pw.h" #include "source_pw/module_pwdft/pw_hybrid_nscf.h" #include "source_estate/elecstate_pw.h" @@ -294,6 +296,8 @@ void ESolver_KS_PW::iter_finish( int &iter, bool &conv_esolver) { + std::ofstream& running_log = GlobalV::ofs_running; + const System_para& system = PARAM.globalv; // Related to EXX bool cal_exx = general_exx_info_.cal_exx; double hybrid_alpha = general_exx_info_.hybrid_alpha; @@ -314,12 +318,69 @@ void ESolver_KS_PW::iter_finish( const double escon = sc.cal_escon(); this->pelec->set_spin_constrain_energy(escon); } + const bool observe_scf = ScfDiagnostics::scf_diagnostics_enabled() && this->inp_->dft_plus_u == 1; + double charge_residual = 0.0; + double magnetic_residual = 0.0; + double charge_l2 = 0.0; + double magnetic_l2 = 0.0; + if (observe_scf) + { + if (this->inp_->nspin != 2 || this->inp_->mixing_dftu != 0 || this->inp_->precision != "double") + { + ModuleBase::WARNING_QUIT("SCF diagnostics", "PW observer requires nspin=2, precision=double, mixing_dftu=0"); + } + module_charge::cal_spin_channel_residuals( + this->chr, this->inp_->nelec, *this->chr.rhopw, ucell.omega, charge_residual, magnetic_residual); + module_charge::cal_spin_channel_residuals_l2( + this->chr, this->inp_->nelec, *this->chr.rhopw, ucell.omega, charge_l2, magnetic_l2); + } ESolver_KS::iter_finish(ucell, istep, iter, conv_esolver); + if (observe_scf) + { + ScfDiagnostics::ScfDiagnosticStep diagnostic_step; + diagnostic_step.output_dir = system.global_out_dir; + diagnostic_step.basis_type = "pw"; + diagnostic_step.scf_thr_type = this->inp_->scf_thr_type; + diagnostic_step.has_l2_channels = true; + diagnostic_step.charge_residual_l2 = charge_l2; + diagnostic_step.magnetic_residual_l2 = magnetic_l2; + diagnostic_step.rank = GlobalV::MY_RANK; + diagnostic_step.ionic_step = istep + 1; + diagnostic_step.iteration = iter; + diagnostic_step.threshold = this->scf_thr; + diagnostic_step.drho = this->drho; + diagnostic_step.charge_residual = charge_residual; + diagnostic_step.magnetic_residual = magnetic_residual; + const ModuleBase::TimePoint observer_time = ModuleBase::get_time(); + diagnostic_step.wall_seconds = ModuleBase::get_duration(this->iter_time, observer_time); + diagnostic_step.restart_count = this->p_chgmix->mixing_restart_count; + diagnostic_step.restart_scheduled_step = this->p_chgmix->mixing_restart_step; + diagnostic_step.restart_executed = this->inp_->mixing_restart > 0.0 + && iter == this->p_chgmix->mixing_restart_step && this->p_chgmix->mixing_restart_count > 0; + diagnostic_step.converged = conv_esolver; + diagnostic_step.gap_eV = this->pelec->bandgap * ModuleBase::Ry_to_eV; + diagnostic_step.total_magnetism = ucell.magnet.tot_mag; + diagnostic_step.absolute_magnetism = ucell.magnet.abs_mag; + diagnostic_step.total_energy_eV = this->pelec->f_en.etot * ModuleBase::Ry_to_eV; + diagnostic_step.source_band_correction_eV = this->dftu_->get_energy() * ModuleBase::Ry_to_eV; + diagnostic_step.mixing_type = this->inp_->mixing_mode; + diagnostic_step.beta = this->p_chgmix->get_mixing_beta(); + diagnostic_step.beta_mag = this->inp_->mixing_beta_mag; + diagnostic_step.mixing_dftu = this->inp_->mixing_dftu; + diagnostic_step.mixing_dmr = this->inp_->mixing_dmr; + diagnostic_step.mixing_restart = this->inp_->mixing_restart; + const bool input_ready = iter > 1 || istep > 0 || this->dftu_->is_occmat_ready(); + const auto blocks = DFTU_BASE::observe_occ_pw( + this->stp.template get_psi_t(), this->pelec->wg, ucell, this->kv.isk.data(), + this->inp_->kpar, *this->dftu_, input_ready); + ScfDiagnostics::write_scf_diagnostics(diagnostic_step, blocks, running_log); + } + // D in USPP needs vloc, thus needs update when veff updated // calculate the effective coefficient matrix for non-local // pp projectors, liuyu 2023-10-24 - if (PARAM.globalv.use_uspp) + if (system.use_uspp) { ModuleBase::matrix veff = this->pelec->pot->get_eff_v(); this->ppcell.cal_effective_D(veff, this->pw_rhod, ucell); @@ -354,7 +415,7 @@ void ESolver_KS_PW::iter_finish( const DFTU_BASE::OccmatStepInfo occmat_step{istep, iter, this->scf_thr, this->drho}; // Read globalv values once into locals so the repeated DFT+U call sites // below do not each re-enter the global dependency surface. - const std::string &global_out_dir = PARAM.globalv.global_out_dir; + const std::string &global_out_dir = system.global_out_dir; const bool occmat_ready = (iter > 1 || istep > 0 || this->dftu_->is_occmat_ready()); if (occmat_ready) { @@ -374,7 +435,7 @@ void ESolver_KS_PW::iter_finish( if (!this->defer_iter_output(istep)) { ModuleIO::ctrl_iter_pw( - istep, iter, conv_esolver, this->stp, this->kv, this->pw_wfc, *this->inp_, false, GlobalV::ofs_running); + istep, iter, conv_esolver, this->stp, this->kv, this->pw_wfc, *this->inp_, false, running_log); } } diff --git a/source/source_estate/CMakeLists.txt b/source/source_estate/CMakeLists.txt index 9f83433a275..69c53e4aba6 100644 --- a/source/source_estate/CMakeLists.txt +++ b/source/source_estate/CMakeLists.txt @@ -2,6 +2,7 @@ list( APPEND objects elecstate.cpp + scf_diagnostics.cpp init_scf.cpp estate_e_terms.cpp elecstate_energy.cpp diff --git a/source/source_estate/module_charge/chg_drho.cpp b/source/source_estate/module_charge/chg_drho.cpp index abb68c3746a..5935f4c519d 100644 --- a/source/source_estate/module_charge/chg_drho.cpp +++ b/source/source_estate/module_charge/chg_drho.cpp @@ -85,6 +85,58 @@ double cal_drho(Charge* chr, return drho; } +void cal_spin_channel_residuals(const Charge& chr, + const double nelec, + const ModulePW::PW_Basis& rhopw, + const double omega, + double& charge_residual, + double& magnetic_residual) +{ + assert(nelec > 0.0 && omega > 0.0 && rhopw.nxyz > 0); + charge_residual = 0.0; + magnetic_residual = 0.0; + for (int ir = 0; ir < rhopw.nrxx; ++ir) + { + const double up = chr.rho[0][ir] - chr.rho_save[0][ir]; + const double down = chr.rho[1][ir] - chr.rho_save[1][ir]; + charge_residual += std::abs(up + down); + magnetic_residual += std::abs(up - down); + } +#ifdef __MPI + Parallel_Reduce::reduce_pool(charge_residual); + Parallel_Reduce::reduce_pool(magnetic_residual); +#endif + const double normalization = omega / static_cast(rhopw.nxyz) / nelec; + charge_residual *= normalization; + magnetic_residual *= normalization; +} + +void cal_spin_channel_residuals_l2(const Charge& chr, + const double nelec, + const ModulePW::PW_Basis& rhopw, + const double omega, + double& charge_residual, + double& magnetic_residual) +{ + assert(nelec > 0.0 && omega > 0.0 && rhopw.nxyz > 0); + double charge_sum = 0.0; + double magnetic_sum = 0.0; + for (int ir = 0; ir < rhopw.nrxx; ++ir) + { + const double up = chr.rho[0][ir] - chr.rho_save[0][ir]; + const double down = chr.rho[1][ir] - chr.rho_save[1][ir]; + charge_sum += (up+down)*(up+down); + magnetic_sum += (up-down)*(up-down); + } +#ifdef __MPI + Parallel_Reduce::reduce_pool(charge_sum); + Parallel_Reduce::reduce_pool(magnetic_sum); +#endif + const double normalization = omega/nelec; + charge_residual = normalization*std::sqrt(charge_sum/static_cast(rhopw.nxyz)); + magnetic_residual = normalization*std::sqrt(magnetic_sum/static_cast(rhopw.nxyz)); +} + // Kinetic-energy-density residual between chr->kin_r and chr->kin_r_save. double cal_dkin(Charge* chr, const double nelec, diff --git a/source/source_estate/module_charge/chg_drho.h b/source/source_estate/module_charge/chg_drho.h index cae85dbb5bc..b61f76910c1 100644 --- a/source/source_estate/module_charge/chg_drho.h +++ b/source/source_estate/module_charge/chg_drho.h @@ -37,6 +37,23 @@ double cal_drho(Charge* chr, const double omega, const double tpiba); +// Read-only collinear raw-output minus input channel residuals. L1 on the +// rho grid, normalized by omega/(nxyz*nelec), with pool reduction. +void cal_spin_channel_residuals(const Charge& chr, + const double nelec, + const ModulePW::PW_Basis& rhopw, + const double omega, + double& charge_residual, + double& magnetic_residual); + +// Dimensionless L2 channels: omega/nelec * sqrt(sum_grid(delta_rho^2)/nxyz). +void cal_spin_channel_residuals_l2(const Charge& chr, + const double nelec, + const ModulePW::PW_Basis& rhopw, + const double omega, + double& charge_residual, + double& magnetic_residual); + /** * @brief Kinetic-energy-density residual between chr->kin_r and chr->kin_r_save. * diff --git a/source/source_estate/module_charge/unittests/test_chg_drho.cpp b/source/source_estate/module_charge/unittests/test_chg_drho.cpp index 8093d834918..51f4c39e1e6 100644 --- a/source/source_estate/module_charge/unittests/test_chg_drho.cpp +++ b/source/source_estate/module_charge/unittests/test_chg_drho.cpp @@ -252,3 +252,46 @@ TEST_F(ChgDrhoTest, CalDkinMetaGgaTrueComputesResidual) * omega / static_cast(pw_basis.nxyz) / nelec; EXPECT_NEAR(dkin, ref, 1e-10); } + +TEST_F(ChgDrhoTest, SpinChannelsSeparateChargeAndMagneticChangesWithoutMutatingDensity) +{ + setup_charge(2); + for (int ir = 0; ir < pw_basis.nrxx; ++ir) + { + charge.rho_save[0][ir] = 10.0; + charge.rho_save[1][ir] = 10.0; + charge.rho[0][ir] = 12.0; + charge.rho[1][ir] = 9.0; + } + double rc = 0.0; + double rm = 0.0; + module_charge::cal_spin_channel_residuals(charge, 4.0, pw_basis, 2.0, rc, rm); + const double factor = 2.0 * pw_basis.nrxx / pw_basis.nxyz / 4.0; + EXPECT_NEAR(rc, factor, 1e-12); + EXPECT_NEAR(rm, 3.0 * factor, 1e-12); + EXPECT_DOUBLE_EQ(charge.rho[0][0], 12.0); + EXPECT_DOUBLE_EQ(charge.rho_save[1][0], 10.0); + charge.rho[1][0] = 12.0; + module_charge::cal_spin_channel_residuals(charge, 4.0, pw_basis, 2.0, rc, rm); + EXPECT_GT(rc, factor); + EXPECT_LT(rm, 3.0 * factor); +} + +TEST_F(ChgDrhoTest, SpinChannelsL2Normalization) +{ + setup_charge(2); + for (int ir = 0; ir < pw_basis.nrxx; ++ir) + { + charge.rho_save[0][ir] = 10.0; + charge.rho_save[1][ir] = 10.0; + charge.rho[0][ir] = 12.0; + charge.rho[1][ir] = 9.0; + } + double rc = 0.0; + double rm = 0.0; + module_charge::cal_spin_channel_residuals_l2(charge, 4.0, pw_basis, 2.0, rc, rm); + const double factor = 0.5*std::sqrt(static_cast(pw_basis.nrxx)/pw_basis.nxyz); + EXPECT_NEAR(rc, factor, 1e-12); + EXPECT_NEAR(rm, 3.0*factor, 1e-12); + EXPECT_DOUBLE_EQ(charge.rho[0][0], 12.0); +} diff --git a/source/source_estate/scf_diagnostics.cpp b/source/source_estate/scf_diagnostics.cpp new file mode 100644 index 00000000000..d3d5bec65bd --- /dev/null +++ b/source/source_estate/scf_diagnostics.cpp @@ -0,0 +1,106 @@ +#include "source_estate/scf_diagnostics.h" + +#include +#include +#include +#include + +namespace +{ +void write_matrix(std::ostream& out, const std::vector& matrix) +{ + if (matrix.empty()) + { + out << "null"; + return; + } + out << '['; + for (std::size_t i = 0; i < matrix.size(); ++i) + { + if (i != 0) + { + out << ','; + } + out << matrix[i]; + } + out << ']'; +} +} + +bool ScfDiagnostics::scf_diagnostics_enabled() +{ + const char* value = std::getenv("ABACUS_SCF_DIAGNOSTICS"); + return value != nullptr && std::string(value) == "1"; +} + +void ScfDiagnostics::write_scf_diagnostics(const ScfDiagnosticStep& step, + const std::vector& blocks, + std::ostream& running_log) +{ + if (step.rank != 0) + { + return; + } + const std::string path = step.output_dir + "scf_diagnostics.jsonl"; + const bool first = step.ionic_step == 1 && step.iteration == 1; + const std::ios::openmode mode = first ? std::ios::trunc : std::ios::app; + std::ofstream out(path.c_str(), std::ios::out | mode); + if (!out) + { + throw std::runtime_error("Cannot write SCF diagnostics: " + path); + } + if (first) + { + running_log << "Write SCF diagnostic records to file: " << path << '\n'; + } + out << std::scientific << std::setprecision(17); + out << "{\"schema\":3,\"basis_type\":\"" << step.basis_type << "\",\"ionic_step\":" << step.ionic_step + << ",\"iteration\":" << step.iteration + << ",\"threshold\":" << step.threshold << ",\"drho\":" << step.drho + << ",\"charge_residual_L1_per_electron\":" << step.charge_residual + << ",\"magnetic_residual_L1_per_electron\":" << step.magnetic_residual + << ",\"scf_thr_type\":" << step.scf_thr_type; + out << ",\"charge_residual_L2_normalized\":"; + if (step.has_l2_channels) { out << step.charge_residual_l2; } else { out << "null"; } + out << ",\"magnetic_residual_L2_normalized\":"; + if (step.has_l2_channels) { out << step.magnetic_residual_l2; } else { out << "null"; } + out + << ",\"scf_wall_seconds_before_occupation_observer\":" << step.wall_seconds + << ",\"mixing_restart_count\":" << step.restart_count + << ",\"mixing_restart_scheduled_step\":" << step.restart_scheduled_step + << ",\"mixing_restart_executed\":" << step.restart_executed + << ",\"scf_converged\":" << step.converged + << ",\"logged_E_gap_k_eV\":" << step.gap_eV + << ",\"fundamental_gap_eV\":null" + << ",\"total_magnetism_muB_cell\":" << step.total_magnetism + << ",\"absolute_magnetism_muB_cell\":" << step.absolute_magnetism + << ",\"total_energy_eV\":" << step.total_energy_eV + << ",\"source_band_correction_eV\":" << step.source_band_correction_eV + << ",\"mixing_type\":\"" << step.mixing_type << "\",\"mixing_beta\":" << step.beta + << ",\"mixing_beta_mag\":" << step.beta_mag << ",\"mixing_dftu\":" << step.mixing_dftu + << ",\"mixing_dmr\":" << step.mixing_dmr << ",\"mixing_restart\":" << step.mixing_restart + << ",\"blocks\":["; + for (std::size_t i = 0; i < blocks.size(); ++i) + { + const ScfOccupationBlock& b = blocks[i]; + if (i != 0) + { + out << ','; + } + out << "{\"atom\":" << b.atom << ",\"spin\":" << b.spin << ",\"l\":" << b.l + << ",\"dimension\":" << 2 * b.l + 1 << ",\"U_eff_eV\":" << b.u_eV + << ",\"n_in\":"; + write_matrix(out, b.input); + out << ",\"n_raw_out\":"; + write_matrix(out, b.raw_output); + // This observer only supports onsite collinear runs without occupation + // mixing. Do not invent a post-mixing occupation when none exists. + out << ",\"n_after_occupation_mixing\":null}"; + } + out << "]}\n"; + out.flush(); + if (!out) + { + throw std::runtime_error("Incomplete SCF diagnostic write: " + path); + } +} diff --git a/source/source_estate/scf_diagnostics.h b/source/source_estate/scf_diagnostics.h new file mode 100644 index 00000000000..8aca4690465 --- /dev/null +++ b/source/source_estate/scf_diagnostics.h @@ -0,0 +1,60 @@ +#ifndef DFTU_SCF_DIAGNOSTICS_H +#define DFTU_SCF_DIAGNOSTICS_H + +#include +#include +#include + +namespace ScfDiagnostics +{ +// Observational copies only. These objects never feed the Hamiltonian or mixer. +struct ScfOccupationBlock +{ + int atom = 0; + int spin = 0; + int l = 0; + double u_eV = 0.0; + std::vector input; + std::vector raw_output; +}; + +struct ScfDiagnosticStep +{ + std::string output_dir; + std::string basis_type = "lcao"; + std::string mixing_type; + int rank = 0; + int ionic_step = 1; + int iteration = 1; + int mixing_dftu = 0; + bool mixing_dmr = false; + double mixing_restart = 0.0; + double beta = 0.0; + double beta_mag = 0.0; + double threshold = 0.0; + double drho = 0.0; + int scf_thr_type = 2; + bool has_l2_channels = false; + double charge_residual_l2 = 0.0; + double magnetic_residual_l2 = 0.0; + double charge_residual = 0.0; + double magnetic_residual = 0.0; + double wall_seconds = 0.0; + int restart_count = 0; + int restart_scheduled_step = 0; + bool restart_executed = false; + bool converged = false; + double gap_eV = 0.0; + double total_magnetism = 0.0; + double absolute_magnetism = 0.0; + double total_energy_eV = 0.0; + double source_band_correction_eV = 0.0; +}; + +// Opt-in observer for this diagnostic build; no INPUT/SCF defaults are changed. +bool scf_diagnostics_enabled(); +void write_scf_diagnostics(const ScfDiagnosticStep& step, + const std::vector& blocks, + std::ostream& running_log); +} // namespace ScfDiagnostics +#endif diff --git a/source/source_lcao/module_dftu/dftu_nao_ijr.h b/source/source_lcao/module_dftu/dftu_nao_ijr.h index b76fee3db04..82fc82d00ff 100644 --- a/source/source_lcao/module_dftu/dftu_nao_ijr.h +++ b/source/source_lcao/module_dftu/dftu_nao_ijr.h @@ -309,11 +309,8 @@ void accumulate_hr_for_iat0(const UnitCell& ucell, * @param dmR_current [in] real-space density matrix of the active spin * @param occ [out] flattened occupation matrix; overwritten */ -inline void compute_occ_from_dmr(const UnitCell& ucell, - Plus_U_Base& dftu, +inline void project_occ_from_dmr(const UnitCell& ucell, const int iat0, - const int target_L, - const int current_spin, const int nspin, const AdjacentAtomInfo& adjs, const Parallel_Orbitals& pv, @@ -340,6 +337,23 @@ inline void compute_occ_from_dmr(const UnitCell& ucell, { for (double& v : occ) { v *= 0.5; } } +} + +// The original state-writing wrapper keeps the contraction and reduction order +// unchanged. The observer calls the pure projection above on a fresh buffer. +inline void compute_occ_from_dmr(const UnitCell& ucell, + Plus_U_Base& dftu, + const int iat0, + const int target_L, + const int current_spin, + const int nspin, + const AdjacentAtomInfo& adjs, + const Parallel_Orbitals& pv, + const NlmTot& nlm_tot, + const hamilt::HContainer& dmR_current, + std::vector& occ) +{ + project_occ_from_dmr(ucell, iat0, nspin, adjs, pv, nlm_tot, dmR_current, occ); dftu.occmat().set_flat(iat0, target_L, current_spin, occ); } diff --git a/source/source_lcao/module_dftu/dftu_nao_op.cpp b/source/source_lcao/module_dftu/dftu_nao_op.cpp index 378a838a8cb..2518ad424c5 100644 --- a/source/source_lcao/module_dftu/dftu_nao_op.cpp +++ b/source/source_lcao/module_dftu/dftu_nao_op.cpp @@ -1,6 +1,7 @@ #include "dftu_nao_op.h" #include "source_base/timer.h" +#include "source_base/constants.h" #include "source_base/tool_title.h" #include "source_basis/module_nao/two_center_integrator.h" #include "source_cell/module_neighbor/sltk_grid_driver.h" @@ -14,6 +15,7 @@ #include #include +#include #include "dftu_nao_adj.h" #include "dftu_nao_fs_r.h" @@ -184,6 +186,16 @@ void hamilt::DFTU_onsite>::contribute_hubbard_atoms } const double u_value = this->dftu->get_u_current(T0); + if (ScfDiagnostics::scf_diagnostics_enabled()) + { + ScfDiagnostics::ScfOccupationBlock snapshot; + snapshot.atom = iat0 + 1; + snapshot.spin = this->current_spin; + snapshot.l = target_L; + snapshot.u_eV = u_value * ModuleBase::Ry_to_eV; + snapshot.input = occ; + this->diagnostic_inputs_.push_back(snapshot); + } std::vector pot_onsite_tmp(occ.size()); double u_energy = this->dftu->get_energy(); DFTU_LCAO::cal_pot_onsite(occ, tlp1, u_value, pot_onsite_tmp.data(), u_energy); @@ -267,6 +279,10 @@ template void hamilt::DFTU_onsite>::contributeHR() { ModuleBase::TITLE("DFTU_onsite", "contributeHR"); + if (ScfDiagnostics::scf_diagnostics_enabled() && this->current_spin == 0) + { + this->diagnostic_inputs_.clear(); + } // Early exit: DMR not available (first SCF iteration before the first // diagonalization) AND occ_mat not yet initialized const bool dmr_null = (this->dm_ == nullptr || !this->dm_->is_dmr_ready()); @@ -303,6 +319,55 @@ void hamilt::DFTU_onsite>::contributeHR() ModuleBase::timer::end("DFTU_onsite", "contributeHR"); } +template +void hamilt::DFTU_onsite>::write_scf_diagnostics( + const ScfDiagnostics::ScfDiagnosticStep& step, + std::ostream& running_log) const +{ + // Honest scope restriction: no spinor packing or symmetry restoration is + // silently interpreted as a real collinear 5x5 matrix. + if (this->nspin != 2 || ModuleSymmetry::Symmetry::symm_flag == 1 + || step.mixing_dftu != 0 || step.mixing_dmr) + { + throw std::runtime_error("SCF diagnostics require nspin=2, symmetry=0, mixing_dftu=0, mixing_dmr=0"); + } + const Parallel_Orbitals* pv = this->hR->get_atom_pair(0).get_paraV(); + std::vector blocks; + int atom_index = 0; + for (int iat = 0; iat < this->ucell->nat; ++iat) + { + const int type = this->ucell->iat2it[iat]; + if (!this->dftu->has_l_channel(type)) + { + continue; + } + const int l = this->dftu->get_l_channel(type); + const int dim = 2 * l + 1; + const AdjacentAtomInfo& adjs = this->adjs_all[atom_index++]; + for (int spin = 0; spin < 2; ++spin) + { + ScfDiagnostics::ScfOccupationBlock block; + block.atom = iat + 1; + block.spin = spin; + block.l = l; + block.u_eV = this->dftu->get_u_current(type) * ModuleBase::Ry_to_eV; + block.raw_output.assign(dim * dim, 0.0); + for (const ScfDiagnostics::ScfOccupationBlock& input : this->diagnostic_inputs_) + { + if (input.atom == block.atom && input.spin == spin) + { + block.input = input.input; + } + } + const hamilt::HContainer* dmr = this->dm_->get_dmr_ptr(spin + 1); + DFTU_LCAO::project_occ_from_dmr(*this->ucell, iat, this->nspin, adjs, *pv, + this->nlm_tot, *dmr, block.raw_output); + blocks.push_back(block); + } + } + ScfDiagnostics::write_scf_diagnostics(step, blocks, running_log); +} + template class hamilt::DFTU_onsite>; template class hamilt::DFTU_onsite, double>>; template class hamilt::DFTU_onsite, std::complex>>; diff --git a/source/source_lcao/module_dftu/dftu_nao_op.h b/source/source_lcao/module_dftu/dftu_nao_op.h index 54483d904b6..82e1427d99e 100644 --- a/source/source_lcao/module_dftu/dftu_nao_op.h +++ b/source/source_lcao/module_dftu/dftu_nao_op.h @@ -5,6 +5,7 @@ #include "source_lcao/module_operator_lcao/operator_lcao.h" #include "source_hamilt/module_hcontainer/hcontainer.h" #include "source_lcao/module_dftu/dftu_nao_adj.h" +#include "source_estate/scf_diagnostics.h" #include "source_cell/module_symmetry/symm_rotation_k.h" // ModuleSymmetry::Symmetry_rotation_k (value member); LibRI-free #include @@ -70,6 +71,10 @@ class DFTU_onsite> : public OperatorLCAO /// unsymmetrized DMR (previous behavior). void set_kv(const K_Vectors* kv_in) { this->kv_ = kv_in; } + // Observes the raw solved DMR without modifying Plus_U, DMR, or mixing. + void write_scf_diagnostics(const ScfDiagnostics::ScfDiagnosticStep& step, + std::ostream& running_log) const; + private: bool should_restore_symmetric_dmr() const; @@ -98,6 +103,9 @@ class DFTU_onsite> : public OperatorLCAO /// @brief the number of spin components, 1 for no-spin, 2 for collinear spin case and 4 for non-collinear spin case int nspin = 0; + // Last matrices actually passed to cal_pot_onsite, copied for diagnostics. + std::vector diagnostic_inputs_; + /// @brief adjacent-atom lists for all Hubbard atoms; structure snapshot /// computed once in the constructor (operator is rebuilt every ionic step) std::vector adjs_all; diff --git a/source/source_lcao/module_dftu/unittests/CMakeLists.txt b/source/source_lcao/module_dftu/unittests/CMakeLists.txt index 4fe51317cad..1a8d6bbddbd 100644 --- a/source/source_lcao/module_dftu/unittests/CMakeLists.txt +++ b/source/source_lcao/module_dftu/unittests/CMakeLists.txt @@ -9,6 +9,12 @@ abacus_disable_feature_definitions(_OPENMP) if(ENABLE_MPI) + addtest( + TARGET MODULE_DFTU_scf_diagnostics + LIBS + SOURCES test_dftu_scf_diagnostics.cpp + ../../../source_estate/scf_diagnostics.cpp) + addtest( TARGET MODULE_DFTU_pots LIBS base device @@ -38,13 +44,12 @@ if(ENABLE_MPI) TARGET MODULE_DFTU_folding LIBS base device SOURCES - test_dftu_nao_folding.cpp - ../../../source_basis/module_ao/parallel_orbitals.cpp - # The test instantiates Parallel_Orbitals (a Parallel_Blkcyclic subclass) and links - # the MPI-built base library, so it must keep __MPI to match the layout of - # Parallel_Blkcyclic / Parallel_Orbitals across TUs (otherwise ODR/ABI mismatch). - KEEP_FEATURE_DEFINITIONS - __MPI) + test_dftu_nao_folding.cpp + ../../../source_basis/module_ao/parallel_orbitals.cpp + # The test instantiates Parallel_Orbitals (a Parallel_Blkcyclic subclass) and links + # the MPI-built base library, so it must keep __MPI to match the layout of + # Parallel_Blkcyclic / Parallel_Orbitals across TUs (otherwise ODR/ABI mismatch). + KEEP_FEATURE_DEFINITIONS __MPI) addtest( TARGET MODULE_DFTU_fs_r @@ -60,23 +65,21 @@ if(ENABLE_MPI) TARGET MODULE_DFTU_fs_k LIBS base device SOURCES - test_dftu_nao_fs_k.cpp - ../../../source_basis/module_ao/parallel_orbitals.cpp - # The test constructs Parallel_Orbitals normally and links the MPI-built - # base library, so it must keep __MPI to match the Parallel_Blkcyclic layout. - KEEP_FEATURE_DEFINITIONS - __MPI) + test_dftu_nao_fs_k.cpp + ../../../source_basis/module_ao/parallel_orbitals.cpp + # The test constructs Parallel_Orbitals normally and links the MPI-built + # base library, so it must keep __MPI to match the Parallel_Blkcyclic layout. + KEEP_FEATURE_DEFINITIONS __MPI) addtest( TARGET MODULE_DFTU_fs_accum LIBS base device SOURCES - test_dftu_nao_fs_accum.cpp - ../../../source_basis/module_ao/parallel_orbitals.cpp - # This test uses Parallel_Blkcyclic::set_serial which is a real implementation - # in parallel_blkcyc.cpp; keep __MPI so the serial path links correctly. - KEEP_FEATURE_DEFINITIONS - __MPI) + test_dftu_nao_fs_accum.cpp + ../../../source_basis/module_ao/parallel_orbitals.cpp + # This test uses Parallel_Blkcyclic::set_serial which is a real implementation + # in parallel_blkcyc.cpp; keep __MPI so the serial path links correctly. + KEEP_FEATURE_DEFINITIONS __MPI) if(ENABLE_LCAO) addtest( diff --git a/source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp b/source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp new file mode 100644 index 00000000000..a478b6b1427 --- /dev/null +++ b/source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp @@ -0,0 +1,56 @@ +#include "source_estate/scf_diagnostics.h" +#include +#include +#include +#include +#include +#include + +TEST(ScfDiagnostics, PreservePrecisionMissingInputAndAppend) +{ + ScfDiagnostics::ScfDiagnosticStep step; + step.output_dir = testing::TempDir(); + step.mixing_type = "broyden"; + step.threshold = 1e-6; + step.charge_residual = 1.2345678901234567e-7; + step.magnetic_residual = 2.5e-6; + step.restart_count = 1; + step.restart_executed = true; + ScfDiagnostics::ScfOccupationBlock block; + block.atom = 1; + block.l = 2; + block.raw_output.assign(25, 0.0); + block.raw_output[0] = 0.12345678901234567; + std::vector blocks(1, block); + std::ostringstream log; + ScfDiagnostics::write_scf_diagnostics(step, blocks, log); + step.iteration = 2; + blocks[0].input = block.raw_output; + ScfDiagnostics::write_scf_diagnostics(step, blocks, log); + const std::string path = step.output_dir + "scf_diagnostics.jsonl"; + std::ifstream in(path.c_str()); + const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + EXPECT_NE(text.find("1.234567890123456"), std::string::npos); + EXPECT_NE(text.find("\"n_in\":null"), std::string::npos); + EXPECT_NE(text.find("\"iteration\":2"), std::string::npos); + EXPECT_NE(text.find("\"fundamental_gap_eV\":null"), std::string::npos); + EXPECT_NE(text.find("\"charge_residual_L1_per_electron\":1.234567890123456"), std::string::npos); + EXPECT_NE(text.find("\"mixing_restart_count\":1"), std::string::npos); + EXPECT_NE(text.find("\"mixing_restart_executed\":1"), std::string::npos); + EXPECT_EQ(std::count(text.begin(), text.end(), '\n'), 2); + EXPECT_EQ(blocks[0].raw_output, block.raw_output); + EXPECT_NE(log.str().find(path), std::string::npos); + in.close(); + std::remove(path.c_str()); +} + +TEST(ScfDiagnostics, NonWriterRankDoesNotOpenAFile) +{ + ScfDiagnostics::ScfDiagnosticStep step; + step.rank = 1; + step.output_dir = "/nonexistent/"; + std::ostringstream log; + const std::vector blocks; + EXPECT_NO_THROW(ScfDiagnostics::write_scf_diagnostics(step, blocks, log)); + EXPECT_TRUE(log.str().empty()); +} diff --git a/source/source_pw/module_pwdft/dftu_pw.cpp b/source/source_pw/module_pwdft/dftu_pw.cpp index 153503c5df3..e2d6286f095 100644 --- a/source/source_pw/module_pwdft/dftu_pw.cpp +++ b/source/source_pw/module_pwdft/dftu_pw.cpp @@ -121,6 +121,51 @@ void cal_occ_pw(const void* psi_in, ModuleBase::timer::end("Plus_U_Base", "cal_occ_pw"); } +template +std::vector observe_occ_pw( + const void* psi_in, const ModuleBase::matrix& wg, const UnitCell& cell, + const int* isk, const int kpar, const Plus_U_Base& dftu, const bool input_ready) +{ + OccupationMatrix raw; + const std::vector& channels = dftu.get_l_channel_vec(); + raw.init(cell, channels, 2, 1); + raw.zero(cell, channels); + const auto* wavefunctions = static_cast, Device>*>(psi_in); + const int saved_k = wavefunctions->get_current_k(); + accumulate_occ_one_k(psi_in, wg, cell, isk, 2, channels, raw); + pw::reduce_occ_mat(cell, 2, kpar, channels, raw); + wavefunctions->fix_k(saved_k); + auto* projector = projectors::OnsiteProjector::get_instance(); + projector->tabulate_atomic(saved_k); + const int nbands = wavefunctions->get_nbands(); + projector->overlap_proj_psi(nbands, wavefunctions->get_pointer()); + std::vector blocks; + for (int atom = 0; atom < cell.nat; ++atom) + { + const int type = cell.iat2it[atom]; + const int l = channels[type]; + if (l < 0) { continue; } + const int size = (2*l+1)*(2*l+1); + for (int spin = 0; spin < 2; ++spin) + { + ScfDiagnostics::ScfOccupationBlock block; + block.atom = atom+1; + block.spin = spin; + block.l = l; + block.u_eV = dftu.get_u_current(type)*ModuleBase::Ry_to_eV; + const double* output = raw.mat(atom,l,spin).c; + block.raw_output.assign(output,output+size); + if (input_ready) + { + const double* input = dftu.occmat().mat(atom,l,spin).c; + block.input.assign(input,input+size); + } + blocks.push_back(block); + } + } + return blocks; +} + } // namespace DFTU_BASE // explicit instantiations @@ -132,3 +177,10 @@ template void DFTU_BASE::accumulate_occ_one_k( const void*, const ModuleBase::matrix&, const UnitCell&, const int*, const int, const std::vector&, OccupationMatrix&); #endif + +template std::vector DFTU_BASE::observe_occ_pw( + const void*, const ModuleBase::matrix&, const UnitCell&, const int*, const int, const Plus_U_Base&, const bool); +#if defined(__CUDA) || defined(__ROCM) +template std::vector DFTU_BASE::observe_occ_pw( + const void*, const ModuleBase::matrix&, const UnitCell&, const int*, const int, const Plus_U_Base&, const bool); +#endif diff --git a/source/source_pw/module_pwdft/dftu_pw.h b/source/source_pw/module_pwdft/dftu_pw.h index e1a125c76d5..7a570a95593 100644 --- a/source/source_pw/module_pwdft/dftu_pw.h +++ b/source/source_pw/module_pwdft/dftu_pw.h @@ -1,11 +1,13 @@ #ifndef DFTU_PW_H #define DFTU_PW_H +#include "source_estate/scf_diagnostics.h" #include #include #include "source_base/matrix.h" class UnitCell; +class Plus_U_Base; class OccupationMatrix; class OccMatMixer; class Charge_Mixing; @@ -57,6 +59,12 @@ void cal_occ_pw(const void* psi_in, std::vector>& uterm_mat, double& energy_u); +/// Observational projection only: separate storage; no potential/energy/mixer update. +template +std::vector observe_occ_pw( + const void* psi_in, const ModuleBase::matrix& wg, const UnitCell& cell, + const int* isk, const int kpar, const Plus_U_Base& dftu, const bool input_ready); + } // namespace DFTU_BASE #endif // DFTU_PW_H From ba7a26d8969982ef75bd0300c3fb34a304a46f60 Mon Sep 17 00:00:00 2001 From: lanshuyue <2000011337@stu.pku.edu.cn> Date: Fri, 27 Nov 2026 20:57:56 +0800 Subject: [PATCH 2/2] fix(dftu): synchronize onsite mixing and U ramping with SCF diagnostics --- docs/developers_guide/scf_diagnostics.md | 85 +++++++++++++++--- source/source_esolver/esolver_ks.cpp | 2 - source/source_esolver/esolver_ks_lcao.cpp | 34 ++++++- source/source_esolver/esolver_ks_pw.cpp | 8 +- .../source_estate/module_charge/chg_mix.cpp | 9 ++ source/source_estate/module_charge/chg_mix.h | 4 + .../module_charge/chg_routine.cpp | 24 ++--- .../module_charge/unittests/test_chg_mix.cpp | 74 ++++++++++----- source/source_estate/occ_mixer.cpp | 79 ++++++++++++++-- source/source_estate/occ_mixer.h | 16 +++- source/source_estate/scf_diagnostics.cpp | 19 ++-- source/source_estate/scf_diagnostics.h | 13 ++- source/source_estate/unittests/CMakeLists.txt | 5 ++ .../unittests/test_occ_mixer.cpp | 55 +++++++++++- .../unittests/test_scf_diagnostics.cpp} | 9 ++ .../module_parameter/read_inp_estruc.cpp | 14 ++- .../module_parameter/read_inp_exx_dftu.cpp | 17 +++- .../source_lcao/module_dftu/dftu_nao_op.cpp | 36 +++++--- source/source_lcao/module_dftu/dftu_nao_op.h | 3 +- .../module_dftu/unittests/CMakeLists.txt | 6 -- source/source_pw/module_pwdft/dftu_base.cpp | 11 ++- source/source_pw/module_pwdft/dftu_pw.cpp | 7 ++ .../module_pwdft/unittests/test_dftu_base.cpp | 21 +++++ tests/17_DS_DFTU/60_LCAO_U_BASE/INPUT | 31 +++++++ tests/17_DS_DFTU/60_LCAO_U_BASE/KPT | 4 + tests/17_DS_DFTU/60_LCAO_U_BASE/README | 3 + tests/17_DS_DFTU/60_LCAO_U_BASE/STRU | 21 +++++ tests/17_DS_DFTU/60_LCAO_U_BASE/result.ref | 3 + tests/17_DS_DFTU/61_LCAO_U_OCC/INPUT | 31 +++++++ tests/17_DS_DFTU/61_LCAO_U_OCC/KPT | 4 + tests/17_DS_DFTU/61_LCAO_U_OCC/README | 3 + tests/17_DS_DFTU/61_LCAO_U_OCC/STRU | 21 +++++ tests/17_DS_DFTU/61_LCAO_U_OCC/result.ref | 3 + tests/17_DS_DFTU/62_LCAO_U_DMR/INPUT | 31 +++++++ tests/17_DS_DFTU/62_LCAO_U_DMR/KPT | 4 + tests/17_DS_DFTU/62_LCAO_U_DMR/README | 3 + tests/17_DS_DFTU/62_LCAO_U_DMR/STRU | 21 +++++ tests/17_DS_DFTU/62_LCAO_U_DMR/result.ref | 3 + tests/17_DS_DFTU/63_LCAO_U_RAMP/INPUT | 31 +++++++ tests/17_DS_DFTU/63_LCAO_U_RAMP/KPT | 4 + tests/17_DS_DFTU/63_LCAO_U_RAMP/README | 3 + tests/17_DS_DFTU/63_LCAO_U_RAMP/STRU | 21 +++++ tests/17_DS_DFTU/63_LCAO_U_RAMP/result.ref | 3 + tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/INPUT | 31 +++++++ tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/KPT | 4 + tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/README | 3 + tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/STRU | 21 +++++ .../17_DS_DFTU/64_LCAO_U_OCC_RAMP/result.ref | 3 + tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/INPUT | 31 +++++++ tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/KPT | 4 + tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/README | 3 + tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/STRU | 21 +++++ .../17_DS_DFTU/65_LCAO_U_DMR_RAMP/result.ref | 3 + tests/17_DS_DFTU/66_PW_U_BASE/INPUT | 31 +++++++ tests/17_DS_DFTU/66_PW_U_BASE/KPT | 4 + tests/17_DS_DFTU/66_PW_U_BASE/README | 3 + tests/17_DS_DFTU/66_PW_U_BASE/STRU | 21 +++++ tests/17_DS_DFTU/66_PW_U_BASE/result.ref | 3 + tests/17_DS_DFTU/67_PW_U_OCC/INPUT | 31 +++++++ tests/17_DS_DFTU/67_PW_U_OCC/KPT | 4 + tests/17_DS_DFTU/67_PW_U_OCC/README | 3 + tests/17_DS_DFTU/67_PW_U_OCC/STRU | 21 +++++ tests/17_DS_DFTU/67_PW_U_OCC/result.ref | 3 + tests/17_DS_DFTU/68_PW_U_RAMP/INPUT | 31 +++++++ tests/17_DS_DFTU/68_PW_U_RAMP/KPT | 4 + tests/17_DS_DFTU/68_PW_U_RAMP/README | 3 + tests/17_DS_DFTU/68_PW_U_RAMP/STRU | 21 +++++ tests/17_DS_DFTU/68_PW_U_RAMP/result.ref | 3 + tests/17_DS_DFTU/69_PW_U_OCC_RAMP/INPUT | 31 +++++++ tests/17_DS_DFTU/69_PW_U_OCC_RAMP/KPT | 4 + tests/17_DS_DFTU/69_PW_U_OCC_RAMP/README | 3 + tests/17_DS_DFTU/69_PW_U_OCC_RAMP/STRU | 21 +++++ tests/17_DS_DFTU/69_PW_U_OCC_RAMP/result.ref | 3 + tests/17_DS_DFTU/CASES_CPU.txt | 12 +++ tests/17_DS_DFTU/CASES_DFTU_MIXING.txt | 10 +++ .../check_dftu_scf_diagnostics.py | 89 +++++++++++++++++++ 76 files changed, 1188 insertions(+), 94 deletions(-) rename source/{source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp => source_estate/unittests/test_scf_diagnostics.cpp} (80%) create mode 100644 tests/17_DS_DFTU/60_LCAO_U_BASE/INPUT create mode 100644 tests/17_DS_DFTU/60_LCAO_U_BASE/KPT create mode 100644 tests/17_DS_DFTU/60_LCAO_U_BASE/README create mode 100644 tests/17_DS_DFTU/60_LCAO_U_BASE/STRU create mode 100644 tests/17_DS_DFTU/60_LCAO_U_BASE/result.ref create mode 100644 tests/17_DS_DFTU/61_LCAO_U_OCC/INPUT create mode 100644 tests/17_DS_DFTU/61_LCAO_U_OCC/KPT create mode 100644 tests/17_DS_DFTU/61_LCAO_U_OCC/README create mode 100644 tests/17_DS_DFTU/61_LCAO_U_OCC/STRU create mode 100644 tests/17_DS_DFTU/61_LCAO_U_OCC/result.ref create mode 100644 tests/17_DS_DFTU/62_LCAO_U_DMR/INPUT create mode 100644 tests/17_DS_DFTU/62_LCAO_U_DMR/KPT create mode 100644 tests/17_DS_DFTU/62_LCAO_U_DMR/README create mode 100644 tests/17_DS_DFTU/62_LCAO_U_DMR/STRU create mode 100644 tests/17_DS_DFTU/62_LCAO_U_DMR/result.ref create mode 100644 tests/17_DS_DFTU/63_LCAO_U_RAMP/INPUT create mode 100644 tests/17_DS_DFTU/63_LCAO_U_RAMP/KPT create mode 100644 tests/17_DS_DFTU/63_LCAO_U_RAMP/README create mode 100644 tests/17_DS_DFTU/63_LCAO_U_RAMP/STRU create mode 100644 tests/17_DS_DFTU/63_LCAO_U_RAMP/result.ref create mode 100644 tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/INPUT create mode 100644 tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/KPT create mode 100644 tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/README create mode 100644 tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/STRU create mode 100644 tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/result.ref create mode 100644 tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/INPUT create mode 100644 tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/KPT create mode 100644 tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/README create mode 100644 tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/STRU create mode 100644 tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/result.ref create mode 100644 tests/17_DS_DFTU/66_PW_U_BASE/INPUT create mode 100644 tests/17_DS_DFTU/66_PW_U_BASE/KPT create mode 100644 tests/17_DS_DFTU/66_PW_U_BASE/README create mode 100644 tests/17_DS_DFTU/66_PW_U_BASE/STRU create mode 100644 tests/17_DS_DFTU/66_PW_U_BASE/result.ref create mode 100644 tests/17_DS_DFTU/67_PW_U_OCC/INPUT create mode 100644 tests/17_DS_DFTU/67_PW_U_OCC/KPT create mode 100644 tests/17_DS_DFTU/67_PW_U_OCC/README create mode 100644 tests/17_DS_DFTU/67_PW_U_OCC/STRU create mode 100644 tests/17_DS_DFTU/67_PW_U_OCC/result.ref create mode 100644 tests/17_DS_DFTU/68_PW_U_RAMP/INPUT create mode 100644 tests/17_DS_DFTU/68_PW_U_RAMP/KPT create mode 100644 tests/17_DS_DFTU/68_PW_U_RAMP/README create mode 100644 tests/17_DS_DFTU/68_PW_U_RAMP/STRU create mode 100644 tests/17_DS_DFTU/68_PW_U_RAMP/result.ref create mode 100644 tests/17_DS_DFTU/69_PW_U_OCC_RAMP/INPUT create mode 100644 tests/17_DS_DFTU/69_PW_U_OCC_RAMP/KPT create mode 100644 tests/17_DS_DFTU/69_PW_U_OCC_RAMP/README create mode 100644 tests/17_DS_DFTU/69_PW_U_OCC_RAMP/STRU create mode 100644 tests/17_DS_DFTU/69_PW_U_OCC_RAMP/result.ref create mode 100644 tests/17_DS_DFTU/CASES_DFTU_MIXING.txt create mode 100644 tests/integrate/validation_tools/check_dftu_scf_diagnostics.py diff --git a/docs/developers_guide/scf_diagnostics.md b/docs/developers_guide/scf_diagnostics.md index abf962469f1..f3cf985e5aa 100644 --- a/docs/developers_guide/scf_diagnostics.md +++ b/docs/developers_guide/scf_diagnostics.md @@ -1,4 +1,4 @@ -# Onsite LCAO SCF observer (local diagnostic build) +# Onsite DFT+U mixing and per-iteration diagnostics Set `ABACUS_SCF_DIAGNOSTICS=1` in the runtime environment to enable the observer. It writes one double-precision JSON record per completed electronic @@ -7,12 +7,11 @@ updates, thresholds, or mixing coefficients are changed. All MPI ranks participate in the extra projection reductions; only rank zero writes the file. Each record is flushed immediately. -Supported scope: `dft_plus_u=1`, `nspin=2`, `symmetry=0`, `mixing_dftu=0`, -`mixing_dmr=0`. Unsupported layouts raise an error rather than being -reinterpreted as real collinear matrices. The analysis accepts any number of -atoms and iterations, and can preserve complex Hermitian matrices if supplied; -the source observer itself does not implement spinor or occupation-mixing -output. This is a local diagnostic extension, not an upstream feature. +Supported diagnostic scope: onsite `dft_plus_u=1`, `nspin=2`, double precision, +and LCAO `symmetry=0`. Both `mixing_dftu` and LCAO `mixing_dmr` can be observed, +individually or with `uramping`. Enabling both mixing options is rejected. +Spinor/symmetry diagnostic layouts and PW DMR mixing are outside this feature. +The calculations themselves retain the existing spin-layout support. ## Matrix definitions and timing @@ -28,8 +27,20 @@ the potential, or mixing buffers. It is observed after the base solver computes DRHO, magnetism, gap, and energy, and before optional DMR mixing. Charge-density mixing changes rho, not this solved DMR. -`n_after_occupation_mixing` is `null`: no occupation mixer runs in this supported -onsite path. It is not a synonym for raw output or charge-mixed density. +Schema 4 records `n_before_occupation_mixing` and +`n_after_occupation_mixing` for the projection/mixing that constructed the +**current Hamiltonian input**. This projection normally belongs to the preceding +electronic output, identified by `occupation_mixing_source_iteration`; its ionic +step is the record's ionic step. The source iteration is null at an ionic-step +boundary or file initialization. These fields are null when no occupation mixing +was executed, including the first unseeded LCAO projection. They must not be +paired with the current `n_raw_out` as if they were the same projection. + +`n_after_dmr_mixing` is the current step's DMR projected after DMR mixing, and +is null if DMR mixing did not execute. Its presence agrees with +`dmr_mixing_executed`. `n_raw_out` is always captured before DMR mixing. +The writer emits one record per completed electronic step, including the final +step, and keeps absent first-step input null. The representation is the real onsite projector basis, not the nonorthogonal NAO coefficient matrix or a Mulliken/Lowdin population matrix. Projectors use @@ -123,12 +134,10 @@ complete elapsed job wall time. `scf_converged` is the actual solver flag. Local projected d moments in analysis are Tr(n_up_raw)-Tr(n_down_raw) in muB per Hubbard atom; they are partial shell moments, not total atomic moments. -## Shared PW observer (schema 3) +## PW projection observer The record model and writer now live in `source_estate/scf_diagnostics.*`, -under `ScfDiagnostics`, and are built unconditionally. LCAO still observes its -actual onsite input buffer; its established binary remains pinned for the -LCAO rerun campaign. +under `ScfDiagnostics`, and are built unconditionally. LCAO observes its actual onsite Hamiltonian input buffer. For CPU PW, `DFTU_BASE::observe_occ_pw` projects the freshly solved wavefunctions into a separate `OccupationMatrix`, using exactly the native onsite projector, @@ -138,7 +147,7 @@ matrix. It restores the wavefunction k cursor and projector cache to that k. The native `dftu.occmat()` retained after iter_init is the actual Hamiltonian input; without a loaded seed the first input is absent. The raw output is not the one-step-lagged native occ_mat.txt. Supported scope is collinear nspin=2, -double precision and mixing_dftu=0; no independent occupation mixer is claimed. +double precision; occupation mixing snapshots are supplied by the native mixer. PW projectors are the original smoothed onsite atomic projectors represented in plane waves, with overlaps contracted over bands and weighted by the native @@ -164,3 +173,51 @@ L1 channels are also retained as explicitly named additional measurements. `scf_thr_type` identifies the native convergence metric. No equality between these L2/L1 channels and the native PW DRHO is implied. L2 fields are null where not observed; missing values are not replaced with zero. + +## Mixing and U-ramping lifecycle + +`mixing_dftu=true` now acts on LCAO onsite occupations before the Hubbard +potential and its band-energy replacement correction are constructed. It uses +`n_next = beta*n_projected + (1-beta)*n_previous_input`, with `mixing_beta`. +The first unseeded projection passes through; file-loaded occupations seed the +previous input. `init_occ_mat=2` remains fixed and is never mixed. PW retains +its existing reuse of charge-history coefficients; this is not an independent +occupation-residual Pulay solver. Its first unseeded projection is not damped +against an invented zero matrix. + +`mixing_dmr=true` requires LCAO, `scf_thr_type=2`, and `mixing_restart>0`. +It starts at the first threshold-triggered restart, preserving the existing +activation policy. It mixes the solved DMR after charge mixing and before the +next Hamiltonian construction. In the collinear case, charge and magnetic DMR +channels use `mixing_beta` and `mixing_beta_mag`. DMR mixing omits Kerker +screening. Its history must advance exactly once for each fresh charge-history +coefficient set; skipped charge steps also skip auxiliary mixing. + +Any positive `uramping` increment (eV) enables ramping from zero to the target +`hubbard_u`, clamping the last increment. Zero and negative values disable it. +It requires `mixing_restart>scf_thr` and is incompatible with Yukawa U. The +threshold schedules the next iteration's restart; that iteration updates U +before building the Hamiltonian and cannot report convergence. Reconstructing +the charge mixer clears charge, DMR and PW occupation histories together. +The previous physical matrix remains available as an initial guess. LCAO +occupation mixing is linear and retains only that one previous input, with no +multistep coefficients to reuse across U stages. Once U reaches its target, +SCF must still satisfy its native convergence checks. This guard also applies +to PW-only builds. `uramping_eV`, per-block `U_eff_eV`, `u_at_target`, and restart +fields make the applied U sequence inspectable. Energy changes across different +U stages are not fixed-Hamiltonian convergence measures. + +The opt-in diagnostics preserve the original source energy, density and +potential. They do not change convergence criteria or select a magnetic state. +U-ramping and mixing can reach different metastable solutions; acceptance is +based on verified update semantics, not an assumption of identical final states. + +## Regression cases + +`tests/17_DS_DFTU/CASES_DFTU_MIXING.txt` lists fixed-input Autotest cases for +PW baseline/occupation/ramping/combined and the corresponding LCAO cases plus +DMR and DMR+ramping. Run with `OMP_NUM_THREADS=1` and +`ABACUS_SCF_DIAGNOSTICS=1`. The read-only helper +`tests/integrate/validation_tools/check_dftu_scf_diagnostics.py` validates +matrix timing, finite Hermitian matrices, the Hubbard energy identity, and +actual execution of the requested features. It does not launch calculations. diff --git a/source/source_esolver/esolver_ks.cpp b/source/source_esolver/esolver_ks.cpp index 30b3f5708b6..46d7f865f7d 100644 --- a/source/source_esolver/esolver_ks.cpp +++ b/source/source_esolver/esolver_ks.cpp @@ -355,12 +355,10 @@ void ESolver_KS::iter_finish( // SCF will continue if U is not converged for uramping calculation bool converged_u = true; // to avoid unnecessary dependence on dft+u, refactor is needed -#ifdef __LCAO if (this->inp_->dft_plus_u) { converged_u = this->dftu_->u_converged(); } -#endif module_charge::ScfMixingCtx ctx; ctx.iter_limit = iter_limit; diff --git a/source/source_esolver/esolver_ks_lcao.cpp b/source/source_esolver/esolver_ks_lcao.cpp index e899a53f2d7..3eef279ebbb 100644 --- a/source/source_esolver/esolver_ks_lcao.cpp +++ b/source/source_esolver/esolver_ks_lcao.cpp @@ -649,9 +649,10 @@ void ESolver_KS_LCAO::iter_finish( // JSON output and density restart files are handled ESolver_KS::iter_finish(ucell, istep, iter, conv_esolver); + ScfDiagnostics::ScfDiagnosticStep diagnostic_step; + std::vector diagnostic_blocks; if (observe_scf) { - ScfDiagnostics::ScfDiagnosticStep diagnostic_step; diagnostic_step.output_dir = global_out_dir; diagnostic_step.rank = GlobalV::MY_RANK; diagnostic_step.ionic_step = istep + 1; @@ -678,6 +679,8 @@ void ESolver_KS_LCAO::iter_finish( diagnostic_step.mixing_dftu = this->inp_->mixing_dftu; diagnostic_step.mixing_dmr = this->inp_->mixing_dmr; diagnostic_step.mixing_restart = this->inp_->mixing_restart; + diagnostic_step.uramping_eV = this->dftu_->get_uramping() * ModuleBase::Ry_to_eV; + diagnostic_step.u_converged = this->dftu_->u_converged(); for (hamilt::Operator* op = hamilt_lcao->getOperator(); op != nullptr; op = op->next_op) { // The onsite Hubbard operator has its own lcao_dftu main-chain @@ -686,7 +689,7 @@ void ESolver_KS_LCAO::iter_finish( OnsiteOperator* onsite = dynamic_cast(op); if (onsite != nullptr) { - onsite->write_scf_diagnostics(diagnostic_step, running_log); + diagnostic_blocks = onsite->observe_scf_occupations(); } } } @@ -717,7 +720,10 @@ void ESolver_KS_LCAO::iter_finish( // except at convergence or the maximum iteration count. if (iter != iter_limit && !conv_esolver) { - if (this->inp_->mixing_restart > 0 && this->p_chgmix->mixing_restart_count > 0 && this->inp_->mixing_dmr) + const int rho_history = this->p_chgmix->get_rho_mdata().ndim_history; + const int dmr_history = this->p_chgmix->get_dmr_mdata().ndim_history; + if (this->inp_->mixing_restart > 0 && this->p_chgmix->mixing_restart_count > 0 + && this->inp_->mixing_dmr && rho_history == dmr_history + 1) { // Extract the contiguous per-spin DMR buffers expected by the // stateless mixing kernel. @@ -733,9 +739,31 @@ void ESolver_KS_LCAO::iter_finish( module_charge::mix_dmr( dmr_out, dmr_in, dmr_containers[0]->get_nnr(), this->p_chgmix->get_mixing(), this->p_chgmix->get_dmr_mdata(), this->p_chgmix->get_mixing_config()); + diagnostic_step.dmr_mixing_executed = true; } } + if (observe_scf) + { + if (diagnostic_step.dmr_mixing_executed) + { + for (hamilt::Operator* op = hamilt_lcao->getOperator(); op != nullptr; op = op->next_op) + { + typedef hamilt::DFTU_onsite> OnsiteOperator; + OnsiteOperator* onsite = dynamic_cast(op); + if (onsite != nullptr) + { + const std::vector mixed = onsite->observe_scf_occupations(); + for (std::size_t i = 0; i < diagnostic_blocks.size(); ++i) + { + diagnostic_blocks[i].after_dmr_mixing = mixed.at(i).raw_output; + } + } + } + } + ScfDiagnostics::write_scf_diagnostics(diagnostic_step, diagnostic_blocks, running_log); + } + // control the output related to the finished iteration ModuleIO::ctrl_iter_lcao( ucell, *this->inp_, this->kv, this->pelec, *this->dmat.dm, this->pv, this->gd, this->psi, this->chr, diff --git a/source/source_esolver/esolver_ks_pw.cpp b/source/source_esolver/esolver_ks_pw.cpp index d43039d5a2d..7d791aa9e98 100644 --- a/source/source_esolver/esolver_ks_pw.cpp +++ b/source/source_esolver/esolver_ks_pw.cpp @@ -325,9 +325,9 @@ void ESolver_KS_PW::iter_finish( double magnetic_l2 = 0.0; if (observe_scf) { - if (this->inp_->nspin != 2 || this->inp_->mixing_dftu != 0 || this->inp_->precision != "double") + if (this->inp_->nspin != 2 || this->inp_->precision != "double") { - ModuleBase::WARNING_QUIT("SCF diagnostics", "PW observer requires nspin=2, precision=double, mixing_dftu=0"); + ModuleBase::WARNING_QUIT("SCF diagnostics", "PW observer requires nspin=2, precision=double"); } module_charge::cal_spin_channel_residuals( this->chr, this->inp_->nelec, *this->chr.rhopw, ucell.omega, charge_residual, magnetic_residual); @@ -369,8 +369,10 @@ void ESolver_KS_PW::iter_finish( diagnostic_step.mixing_dftu = this->inp_->mixing_dftu; diagnostic_step.mixing_dmr = this->inp_->mixing_dmr; diagnostic_step.mixing_restart = this->inp_->mixing_restart; + diagnostic_step.uramping_eV = this->dftu_->get_uramping() * ModuleBase::Ry_to_eV; + diagnostic_step.u_converged = this->dftu_->u_converged(); const bool input_ready = iter > 1 || istep > 0 || this->dftu_->is_occmat_ready(); - const auto blocks = DFTU_BASE::observe_occ_pw( + const std::vector blocks = DFTU_BASE::observe_occ_pw( this->stp.template get_psi_t(), this->pelec->wg, ucell, this->kv.isk.data(), this->inp_->kpar, *this->dftu_, input_ready); ScfDiagnostics::write_scf_diagnostics(diagnostic_step, blocks, running_log); diff --git a/source/source_estate/module_charge/chg_mix.cpp b/source/source_estate/module_charge/chg_mix.cpp index cda51fc2e21..0a892d68d10 100644 --- a/source/source_estate/module_charge/chg_mix.cpp +++ b/source/source_estate/module_charge/chg_mix.cpp @@ -185,6 +185,9 @@ void Charge_Mixing::init_mixing() } } + // Auxiliary histories use the coefficients of this newly constructed mixer. + this->dmr_mdata.reset(); + this->uom_mdata.reset(); ModuleBase::timer::end("Charge_Mixing", "init_mixing"); return; @@ -308,6 +311,12 @@ void Charge_Mixing::mix_uom(std::vector& uom_in, std::vector& uo { ModuleBase::TITLE("Charge_Mixing", "mix_uom"); ModuleBase::timer::start("Charge_Mixing", "mix_uom"); + if (this->rho_mdata.ndim_history != this->uom_mdata.ndim_history + 1) + { + // No fresh charge coefficients (restart or a skipped charge step). + ModuleBase::timer::end("Charge_Mixing", "mix_uom"); + return; + } double* uom_value_out = uom_in.data(); double* uom_value_in = uom_save_in.data(); // For all nspin cases, uom_array layout is already fully sized diff --git a/source/source_estate/module_charge/chg_mix.h b/source/source_estate/module_charge/chg_mix.h index 855cae6d2b0..ba50cbf03fc 100644 --- a/source/source_estate/module_charge/chg_mix.h +++ b/source/source_estate/module_charge/chg_mix.h @@ -69,6 +69,10 @@ class Charge_Mixing * @param uom_save_in input occupation matrix */ void mix_uom(std::vector& uom_in, std::vector& uom_save_in); + bool has_uom_coefficients() const + { + return rho_mdata.ndim_history == uom_mdata.ndim_history + 1; + } /** * @brief reset mixing, actually we only call init_mixing() to reset mixing instead of this function diff --git a/source/source_estate/module_charge/chg_routine.cpp b/source/source_estate/module_charge/chg_routine.cpp index 98ef710d0ed..300f36599e9 100644 --- a/source/source_estate/module_charge/chg_routine.cpp +++ b/source/source_estate/module_charge/chg_routine.cpp @@ -215,15 +215,11 @@ void module_charge::chgmixing_ks_pw(const int iter, // scf iteration number if (inp.dft_plus_u) { - if (dftu.get_uramping() > 0.01 && !dftu.u_converged()) - { - p_chgmix->mixing_restart_step = iter_limit + 1; - } - if (dftu.get_uramping() > 0.01) + if (dftu.get_uramping() > 0.0) { if (mag_converged) // skip uramping if mag not converged { - dftu.uramping_update(); // update U by uramping if uramping > 0.01 + dftu.uramping_update(); // update U by uramping if uramping > 0.0 std::cout << " U-Ramping! Current U = "; for (int i = 0; i < dftu.get_num_u_types(); i++) { @@ -231,6 +227,10 @@ void module_charge::chgmixing_ks_pw(const int iter, // scf iteration number } std::cout << " eV " << std::endl; } + if (!dftu.u_converged()) + { + p_chgmix->mixing_restart_step = iter_limit + 1; + } } } } @@ -250,9 +250,13 @@ void module_charge::chgmixing_ks_lcao(const int iter, // scf iteration number if (iter == 1) { p_chgmix->mix_reset(); // init mixing + if (dftu.has_occ_mixer()) + { + dftu.occ_mixer().set_beta(p_chgmix->get_mixing_beta()); + } p_chgmix->reset_scf_history(iter_limit); // this output will be removed once the feeature is stable - if (dftu.get_uramping() > 0.01) + if (dftu.get_uramping() > 0.0) { std::cout << " U-Ramping! Current U = "; for (int i = 0; i < dftu.get_num_u_types(); i++) @@ -270,8 +274,8 @@ void module_charge::chgmixing_ks_lcao(const int iter, // scf iteration number p_chgmix->mixing_restart_count++; if (inp.dft_plus_u) { - dftu.uramping_update(); // update U by uramping if uramping > 0.01 - if (dftu.get_uramping() > 0.01) + dftu.uramping_update(); // update U by uramping if uramping > 0.0 + if (dftu.get_uramping() > 0.0) { std::cout << " U-Ramping! Current U = "; for (int i = 0; i < dftu.get_num_u_types(); i++) @@ -280,7 +284,7 @@ void module_charge::chgmixing_ks_lcao(const int iter, // scf iteration number } std::cout << " eV " << std::endl; } - if (dftu.get_uramping() > 0.01 && !dftu.u_converged()) + if (dftu.get_uramping() > 0.0 && !dftu.u_converged()) { p_chgmix->mixing_restart_step = iter_limit + 1; } diff --git a/source/source_estate/module_charge/unittests/test_chg_mix.cpp b/source/source_estate/module_charge/unittests/test_chg_mix.cpp index 2d8a34bd37d..c2632e7cde5 100644 --- a/source/source_estate/module_charge/unittests/test_chg_mix.cpp +++ b/source/source_estate/module_charge/unittests/test_chg_mix.cpp @@ -235,32 +235,61 @@ TEST_F(ChargeMixingTest, ModelChangeRestartsTheOscillationWindow) TEST_F(ChargeMixingTest, ModelChangeRestartsUomHistory) { cfg.mixing_mode = "pulay"; + cfg.scf_thr_type = 2; Charge_Mixing charge_mixing; charge_mixing.set_mixing(make_cfg(), &pw_basis, &pw_basis, ucell.omega, ucell.tpiba); charge_mixing.init_mixing(); - const int uom_size = 4; - charge_mixing.allocate_mixing_uom(uom_size); - for (int step = 0; step < 2; ++step) - { - const double uom_value = 1.0 + step; - const double uom_save_value = 0.5 + step; - std::vector uom(uom_size, uom_value); - std::vector uom_save(uom_size, uom_save_value); - charge_mixing.mix_uom(uom, uom_save); - } - - const int model_change = 3; - charge_mixing.restart_for_new_model(model_change); - std::vector uom = {2.0, 3.0, 4.0, 5.0}; - std::vector uom_save = {1.0, 1.0, 1.0, 1.0}; - charge_mixing.mix_uom(uom, uom_save); - - const double beta = cfg.mixing_beta; - for (int i = 0; i < uom_size; ++i) + charge_mixing.allocate_mixing_uom(4); + std::vector uom(4, 2.0); + std::vector saved(4, 1.0); + // A restart has no rho coefficients. The auxiliary matrix must pass through. + EXPECT_FALSE(charge_mixing.has_uom_coefficients()); + charge_mixing.mix_uom(uom, saved); + EXPECT_DOUBLE_EQ(uom[0], 2.0); + Base_Mixing::Mixing_Data& rho = charge_mixing.get_rho_mdata(); + std::vector rho_in(rho.length, 0.0); + std::vector rho_out(rho.length, 1.0); + charge_mixing.get_mixing()->push_data(rho, rho_in.data(), rho_out.data(), nullptr, true); + const std::size_t length = rho.length; + std::function inner_product = [length](double* lhs, double* rhs) { + double result = 0.0; + for (std::size_t i = 0; i < length; ++i) + { + result += lhs[i] * rhs[i]; + } + return result; + }; + charge_mixing.get_mixing()->cal_coef(rho, inner_product); + EXPECT_TRUE(charge_mixing.has_uom_coefficients()); + charge_mixing.mix_uom(uom, saved); + EXPECT_NEAR(uom[0], 1.0 + cfg.mixing_beta, 1e-12); + // Skipping charge mixing must not apply the same coefficients a second time. + EXPECT_FALSE(charge_mixing.has_uom_coefficients()); + const std::vector mixed = uom; + charge_mixing.mix_uom(uom, saved); + EXPECT_EQ(uom, mixed); + // Populate a genuine multi-vector Pulay history before restarting. + for (std::size_t i = 0; i < rho.length; ++i) { - const double expected = 1.0 + beta * (2.0 + i - 1.0); - EXPECT_NEAR(uom[i], expected, 1e-12) << "element " << i; + rho_out[i] = 0.5 + (i % 2); } + charge_mixing.get_mixing()->push_data(rho, rho_in.data(), rho_out.data(), nullptr, true); + charge_mixing.get_mixing()->cal_coef(rho, inner_product); + charge_mixing.mix_uom(uom, saved); + EXPECT_GT(rho.ndim_use, 1); + charge_mixing.restart_for_new_model(3); + EXPECT_FALSE(charge_mixing.has_uom_coefficients()); + charge_mixing.get_mixing()->push_data(rho, rho_in.data(), rho_out.data(), nullptr, true); + charge_mixing.get_mixing()->cal_coef(rho, inner_product); + EXPECT_TRUE(charge_mixing.has_uom_coefficients()); + uom.assign(4, 2.0); + charge_mixing.mix_uom(uom, saved); + EXPECT_NEAR(uom[0], 1.0 + cfg.mixing_beta, 1e-12); + // U-ramping reconstructs the mixer through init_mixing, which must clear + // both auxiliary histories as well as rho. + charge_mixing.init_mixing(); + EXPECT_FALSE(charge_mixing.has_uom_coefficients()); + EXPECT_EQ(charge_mixing.get_dmr_mdata().ndim_history, 0); } TEST_F(ChargeMixingTest, MixResetClearsDmrHistory) @@ -283,6 +312,9 @@ TEST_F(ChargeMixingTest, MixResetClearsDmrHistory) EXPECT_EQ(dmr_mdata.ndim_use, 0); EXPECT_EQ(dmr_mdata.ndim_history, 0); EXPECT_EQ(dmr_mdata.start, -1); + dmr_mdata.push(dmr); + charge_mixing.init_mixing(); + EXPECT_EQ(dmr_mdata.ndim_history, 0); } TEST_F(ChargeMixingTest, SetMixingTest) diff --git a/source/source_estate/occ_mixer.cpp b/source/source_estate/occ_mixer.cpp index c82b7bf3c0a..1e3d3c95917 100644 --- a/source/source_estate/occ_mixer.cpp +++ b/source/source_estate/occ_mixer.cpp @@ -1,5 +1,8 @@ #include "source_estate/occ_mixer.h" +#include +#include + void OccMatMixer::init(const UnitCell* cell, const std::vector* l_channel, const std::vector* flat_index, @@ -12,19 +15,20 @@ void OccMatMixer::init(const UnitCell* cell, this->nspin_ = nspin; this->uom_.resize(total_size, 0.0); this->uom_save_.resize(total_size, 0.0); + this->raw_.resize(total_size, 0.0); + this->initialized_.assign(total_size, 0); + this->mixed_.assign(total_size, 0); } void OccMatMixer::seed_save(const OccupationMatrix& occmat) { - occmat.write_save_to_flat(*this->cell_, *this->l_channel_, - *this->index_, this->uom_save_); + occmat.write_to_flat(*this->cell_, *this->l_channel_, + *this->index_, this->uom_save_); + std::fill(this->initialized_.begin(), this->initialized_.end(), 1); } void OccMatMixer::begin_iter(OccupationMatrix& occmat) { - // the caller has already snapshotted occ into occ_save via - // OccupationMatrix::copy_to_save; here we only flatten that snapshot - // into uom_save_ for the mixing history. occmat.write_save_to_flat(*this->cell_, *this->l_channel_, *this->index_, this->uom_save_); } @@ -33,6 +37,12 @@ void OccMatMixer::collect(const OccupationMatrix& occmat) { occmat.write_to_flat(*this->cell_, *this->l_channel_, *this->index_, this->uom_); + this->raw_ = this->uom_; + if (std::find(this->initialized_.begin(), this->initialized_.end(), 1) == this->initialized_.end()) + { + this->uom_save_ = this->uom_; + } + std::fill(this->initialized_.begin(), this->initialized_.end(), 1); } void OccMatMixer::write_back(OccupationMatrix& occmat) @@ -47,3 +57,62 @@ void OccMatMixer::mix_plain(OccupationMatrix& occmat, const double beta) *this->cell_, *this->l_channel_, this->nspin_, beta); } + +int OccMatMixer::block_offset(const int atom, const int spin) const +{ + int offset = this->index_->at(atom); + if (this->nspin_ == 2 && spin == 1) + { + offset += this->uom_.size() / 2; + } + return offset; +} + +void OccMatMixer::mix_onsite_block(const int atom, const int spin, + std::vector& occupation, const double beta) +{ + const int offset = this->block_offset(atom, spin); + if (offset < 0 || offset + occupation.size() > this->uom_.size()) + { + throw std::out_of_range("Onsite occupation block exceeds mixing buffer"); + } + const bool initialized = this->initialized_.at(offset) != 0; + for (std::size_t i = 0; i < occupation.size(); ++i) + { + const int index = offset + i; + this->raw_[index] = occupation[i]; + if (initialized) + { + occupation[i] = beta * occupation[i] + (1.0 - beta) * this->uom_save_[index]; + } + this->uom_[index] = occupation[i]; + this->uom_save_[index] = occupation[i]; + this->initialized_[index] = 1; + this->mixed_[index] = initialized; + } +} + +std::vector OccMatMixer::raw_block(const int atom, const int spin, const int size) const +{ + const int offset = this->block_offset(atom, spin); + if (this->mixed_.at(offset) == 0) + { + return {}; + } + return std::vector(this->raw_.begin() + offset, this->raw_.begin() + offset + size); +} + +std::vector OccMatMixer::mixed_block(const int atom, const int spin, const int size) const +{ + const int offset = this->block_offset(atom, spin); + if (this->mixed_.at(offset) == 0) + { + return {}; + } + return std::vector(this->uom_.begin() + offset, this->uom_.begin() + offset + size); +} + +void OccMatMixer::record_mixing(const bool applied) +{ + std::fill(this->mixed_.begin(), this->mixed_.end(), applied); +} diff --git a/source/source_estate/occ_mixer.h b/source/source_estate/occ_mixer.h index c31aca8350c..5f17ffa0075 100644 --- a/source/source_estate/occ_mixer.h +++ b/source/source_estate/occ_mixer.h @@ -50,7 +50,7 @@ class OccMatMixer int total_size); /** - * @brief Seed uom_save from an occupation matrix loaded from file. + * @brief Seed uom_save from the live occupation matrix loaded from file. * * Used when init_occ_mat != 0 (restart from dm_onsite_ini.txt) so that * the first mixing step has a meaningful "previous" matrix. @@ -76,6 +76,7 @@ class OccMatMixer * matrix. Called after the caller has run Charge_Mixing::mix_uom. */ void write_back(OccupationMatrix& occmat); + void record_mixing(bool applied); /** * @brief Plain linear mixing for the nested-matrix (LCAO) path: @@ -86,6 +87,14 @@ class OccMatMixer */ void mix_plain(OccupationMatrix& occmat, double beta); + /// Mix one onsite atom/spin block; the first unseeded projection is unchanged. + void mix_onsite_block(int atom, int spin, std::vector& occupation, double beta); + std::vector raw_block(int atom, int spin, int size) const; + std::vector mixed_block(int atom, int spin, int size) const; + + void set_beta(double beta) { beta_ = beta; } + double beta() const { return beta_; } + /// Total flat-buffer size (== Charge_Mixing::allocate_mixing_uom argument). int flat_size() const { return static_cast(uom_.size()); } @@ -95,12 +104,17 @@ class OccMatMixer std::vector& uom_save() { return uom_save_; } private: + int block_offset(int atom, int spin) const; + std::vector raw_; + std::vector initialized_; + std::vector mixed_; std::vector uom_; ///< new / mixed flat occupation matrix std::vector uom_save_; ///< previous flat occupation matrix const std::vector* index_ = nullptr; ///< borrowed uterm_mat_index const UnitCell* cell_ = nullptr; ///< borrowed unit cell const std::vector* l_channel_ = nullptr; ///< borrowed l_channel table int nspin_ = 0; + double beta_ = 0.0; }; #endif diff --git a/source/source_estate/scf_diagnostics.cpp b/source/source_estate/scf_diagnostics.cpp index d3d5bec65bd..71cbcc14348 100644 --- a/source/source_estate/scf_diagnostics.cpp +++ b/source/source_estate/scf_diagnostics.cpp @@ -54,7 +54,7 @@ void ScfDiagnostics::write_scf_diagnostics(const ScfDiagnosticStep& step, running_log << "Write SCF diagnostic records to file: " << path << '\n'; } out << std::scientific << std::setprecision(17); - out << "{\"schema\":3,\"basis_type\":\"" << step.basis_type << "\",\"ionic_step\":" << step.ionic_step + out << "{\"schema\":4,\"basis_type\":\"" << step.basis_type << "\",\"ionic_step\":" << step.ionic_step << ",\"iteration\":" << step.iteration << ",\"threshold\":" << step.threshold << ",\"drho\":" << step.drho << ",\"charge_residual_L1_per_electron\":" << step.charge_residual @@ -79,7 +79,12 @@ void ScfDiagnostics::write_scf_diagnostics(const ScfDiagnosticStep& step, << ",\"mixing_type\":\"" << step.mixing_type << "\",\"mixing_beta\":" << step.beta << ",\"mixing_beta_mag\":" << step.beta_mag << ",\"mixing_dftu\":" << step.mixing_dftu << ",\"mixing_dmr\":" << step.mixing_dmr << ",\"mixing_restart\":" << step.mixing_restart - << ",\"blocks\":["; + << ",\"uramping_eV\":" << step.uramping_eV + << ",\"u_at_target\":" << step.u_converged + << ",\"dmr_mixing_executed\":" << step.dmr_mixing_executed + << ",\"occupation_mixing_source_iteration\":"; + if (step.iteration > 1) { out << step.iteration - 1; } else { out << "null"; } + out << ",\"blocks\":["; for (std::size_t i = 0; i < blocks.size(); ++i) { const ScfOccupationBlock& b = blocks[i]; @@ -93,9 +98,13 @@ void ScfDiagnostics::write_scf_diagnostics(const ScfDiagnosticStep& step, write_matrix(out, b.input); out << ",\"n_raw_out\":"; write_matrix(out, b.raw_output); - // This observer only supports onsite collinear runs without occupation - // mixing. Do not invent a post-mixing occupation when none exists. - out << ",\"n_after_occupation_mixing\":null}"; + out << ",\"n_before_occupation_mixing\":"; + write_matrix(out, b.raw_before_occupation_mixing); + out << ",\"n_after_occupation_mixing\":"; + write_matrix(out, b.after_occupation_mixing); + out << ",\"n_after_dmr_mixing\":"; + write_matrix(out, b.after_dmr_mixing); + out << '}'; } out << "]}\n"; out.flush(); diff --git a/source/source_estate/scf_diagnostics.h b/source/source_estate/scf_diagnostics.h index 8aca4690465..7bc9a3202d2 100644 --- a/source/source_estate/scf_diagnostics.h +++ b/source/source_estate/scf_diagnostics.h @@ -1,5 +1,5 @@ -#ifndef DFTU_SCF_DIAGNOSTICS_H -#define DFTU_SCF_DIAGNOSTICS_H +#ifndef SCF_DIAGNOSTICS_H +#define SCF_DIAGNOSTICS_H #include #include @@ -16,6 +16,12 @@ struct ScfOccupationBlock double u_eV = 0.0; std::vector input; std::vector raw_output; + // These two snapshots belong to construction of THIS step's input + // Hamiltonian, normally from the preceding electronic output. + std::vector raw_before_occupation_mixing; + std::vector after_occupation_mixing; + // Projection of this step's DMR after its actual density-matrix mixing. + std::vector after_dmr_mixing; }; struct ScfDiagnosticStep @@ -29,6 +35,9 @@ struct ScfDiagnosticStep int mixing_dftu = 0; bool mixing_dmr = false; double mixing_restart = 0.0; + double uramping_eV = 0.0; + bool u_converged = true; + bool dmr_mixing_executed = false; double beta = 0.0; double beta_mag = 0.0; double threshold = 0.0; diff --git a/source/source_estate/unittests/CMakeLists.txt b/source/source_estate/unittests/CMakeLists.txt index 03ff0d596c8..3084df73bc0 100644 --- a/source/source_estate/unittests/CMakeLists.txt +++ b/source/source_estate/unittests/CMakeLists.txt @@ -24,6 +24,11 @@ addtest( SOURCES test_pcc_2d.cpp ../pcc_2d.cpp ../charge_moments.cpp ../../source_cell/cell_geometry.cpp) +addtest( + TARGET MODULE_ESTATE_scf_diagnostics + LIBS + SOURCES test_scf_diagnostics.cpp ../scf_diagnostics.cpp) + if(ENABLE_MPI) set(pcc_test_sources diff --git a/source/source_estate/unittests/test_occ_mixer.cpp b/source/source_estate/unittests/test_occ_mixer.cpp index 3b55192f249..50c4f705abb 100644 --- a/source/source_estate/unittests/test_occ_mixer.cpp +++ b/source/source_estate/unittests/test_occ_mixer.cpp @@ -262,7 +262,7 @@ TEST_F(OccMatMixerTest, FlatRoundtripNspin4AllPauliBlocks) } // ---------------------------------------------------------------------- -// begin_iter/seed_save flatten the saved (not the live) occupation matrix +// begin_iter flattens the saved (not the live) occupation matrix // ---------------------------------------------------------------------- TEST_F(OccMatMixerTest, BeginIterFlattensSave) { @@ -286,3 +286,56 @@ TEST_F(OccMatMixerTest, BeginIterFlattensSave) EXPECT_DOUBLE_EQ(mixer.uom_save()[flat_index[0] + m], 7.0 + m); } } + +TEST_F(OccMatMixerTest, OnsiteFirstProjectionAndIndependentSpinHistory) +{ + OccupationMatrix occupation; + occupation.init(cell, l_channel, 2, 1); + OccMatMixer mixer; + const int size = total_size(2); + mixer.init(&cell, &l_channel, &flat_index, 2, size); + std::vector up(block, 0.2); + std::vector down(block, 0.6); + mixer.mix_onsite_block(0, 0, up, 0.25); + mixer.mix_onsite_block(0, 1, down, 0.25); + EXPECT_DOUBLE_EQ(up[0], 0.2); + EXPECT_DOUBLE_EQ(down[0], 0.6); + EXPECT_TRUE(mixer.mixed_block(0, 0, block).empty()); + up.assign(block, 0.8); + down.assign(block, 0.2); + mixer.mix_onsite_block(0, 0, up, 0.25); + mixer.mix_onsite_block(0, 1, down, 0.25); + EXPECT_NEAR(up[0], 0.35, 1e-15); + EXPECT_NEAR(down[0], 0.5, 1e-15); + EXPECT_DOUBLE_EQ(mixer.raw_block(0, 0, block)[0], 0.8); + EXPECT_EQ(mixer.mixed_block(0, 0, block), up); + // Another atom has no previous matrix, and must not inherit atom 0's history. + std::vector other(block, 0.9); + mixer.mix_onsite_block(1, 0, other, 0.25); + EXPECT_DOUBLE_EQ(other[0], 0.9); +} + +TEST_F(OccMatMixerTest, SeededOnsiteMatrixAndPwRawSnapshot) +{ + OccupationMatrix occupation; + occupation.init(cell, l_channel, 2, 1); + occupation.zero(cell, l_channel); + std::vector input(block, 0.4); + occupation.set_flat(0, l_corr, 0, input); + OccMatMixer mixer; + const int size = total_size(2); + mixer.init(&cell, &l_channel, &flat_index, 2, size); + mixer.seed_save(occupation); + std::vector raw(block, 0.8); + mixer.mix_onsite_block(0, 0, raw, 0.5); + EXPECT_NEAR(raw[0], 0.6, 1e-15); + occupation.copy_to_save(cell, l_channel); + mixer.begin_iter(occupation); + occupation.set_flat(0, l_corr, 0, raw); + mixer.collect(occupation); + mixer.uom()[0] = 0.1; + mixer.record_mixing(true); + mixer.write_back(occupation); + EXPECT_NEAR(mixer.raw_block(0, 0, block)[0], 0.6, 1e-15); + EXPECT_DOUBLE_EQ(mixer.mixed_block(0, 0, block)[0], 0.1); +} diff --git a/source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp b/source/source_estate/unittests/test_scf_diagnostics.cpp similarity index 80% rename from source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp rename to source/source_estate/unittests/test_scf_diagnostics.cpp index a478b6b1427..4058f18ad2f 100644 --- a/source/source_lcao/module_dftu/unittests/test_dftu_scf_diagnostics.cpp +++ b/source/source_estate/unittests/test_scf_diagnostics.cpp @@ -26,6 +26,11 @@ TEST(ScfDiagnostics, PreservePrecisionMissingInputAndAppend) ScfDiagnostics::write_scf_diagnostics(step, blocks, log); step.iteration = 2; blocks[0].input = block.raw_output; + blocks[0].raw_before_occupation_mixing = {0.8}; + blocks[0].after_occupation_mixing = {0.6}; + blocks[0].after_dmr_mixing = {0.4}; + step.uramping_eV = 0.1; + step.dmr_mixing_executed = true; ScfDiagnostics::write_scf_diagnostics(step, blocks, log); const std::string path = step.output_dir + "scf_diagnostics.jsonl"; std::ifstream in(path.c_str()); @@ -39,6 +44,10 @@ TEST(ScfDiagnostics, PreservePrecisionMissingInputAndAppend) EXPECT_NE(text.find("\"mixing_restart_executed\":1"), std::string::npos); EXPECT_EQ(std::count(text.begin(), text.end(), '\n'), 2); EXPECT_EQ(blocks[0].raw_output, block.raw_output); + EXPECT_NE(text.find("\"schema\":4"), std::string::npos); + EXPECT_NE(text.find("\"occupation_mixing_source_iteration\":1"), std::string::npos); + EXPECT_NE(text.find("\"n_after_dmr_mixing\":[4.000000000000000"), std::string::npos); + EXPECT_NE(text.find("\"n_after_occupation_mixing\":[5.999999999999999"), std::string::npos); EXPECT_NE(log.str().find(path), std::string::npos); in.close(); std::remove(path.c_str()); diff --git a/source/source_io/module_parameter/read_inp_estruc.cpp b/source/source_io/module_parameter/read_inp_estruc.cpp index 0590b4762bb..37e955ff69c 100644 --- a/source/source_io/module_parameter/read_inp_estruc.cpp +++ b/source/source_io/module_parameter/read_inp_estruc.cpp @@ -669,6 +669,18 @@ For systems that are difficult to converge, one could try increasing the value o item.unit = ""; item.set_availability("mixing_restart>0"); read_sync_bool(input.mixing_dmr); + item.check_value = [](const Input_Item& item, const Parameter& para) { + if (para.input.mixing_dmr + && (para.input.basis_type != "lcao" || para.input.mixing_restart <= 0.0 + || para.input.scf_thr_type != 2)) + { + ModuleBase::WARNING_QUIT("ReadInput", "mixing_dmr requires LCAO, scf_thr_type=2 and mixing_restart>0"); + } + if (para.input.mixing_dmr && para.input.mixing_dftu) + { + ModuleBase::WARNING_QUIT("ReadInput", "Simultaneous mixing_dmr and mixing_dftu is not supported"); + } + }; this->add_item(item); } { @@ -749,7 +761,7 @@ This setting takes effect only when the selected exchange-correlation functional item.category = "Electronic structure"; item.type = "Boolean"; item.description = R"(Whether to mix the occupation matrices. -* True: The occupation matrices will also be mixed by plain mixing. From experience this is not very helpful if the +U calculation does not converge. +* True: Mix the occupation matrices before building the Hubbard potential. LCAO uses linear mixing with mixing_beta; PW reuses the charge-mixing coefficients. Cannot be combined with mixing_dmr. * False: The occupation matrices will not be mixed.)"; item.default_value = "False"; item.unit = ""; diff --git a/source/source_io/module_parameter/read_inp_exx_dftu.cpp b/source/source_io/module_parameter/read_inp_exx_dftu.cpp index 837cb3891c2..148c158cbb0 100644 --- a/source/source_io/module_parameter/read_inp_exx_dftu.cpp +++ b/source/source_io/module_parameter/read_inp_exx_dftu.cpp @@ -866,7 +866,7 @@ void ReadInput::item_dftu() item.unit = ""; item.check_value = [](const Input_Item& item, const Parameter& para) { if (!item.is_read()) { return; } - if (para.inp.yukawa_potential && para.globalv.uramping > 0.01) + if (para.inp.yukawa_potential && para.globalv.uramping > 0.0) { ModuleBase::WARNING_QUIT("ReadInput", "yukawa_potential and uramping cannot be used together. " @@ -894,8 +894,8 @@ void ReadInput::item_dftu() item.annotation = "increasing U values during SCF"; item.category = "DFT+U correction"; item.type = "Real"; - item.description = "Once uramping > 0.15 eV. DFT+U calculations will start SCF with U = 0 eV, namely normal LDA/PBE calculations. Once SCF restarts when drho0"); item.read_value = [](const Input_Item& item, Parameter& para) { @@ -921,6 +921,17 @@ void ReadInput::item_dftu() } } }; + item.check_value = [](const Input_Item& item, const Parameter& para) { + if (para.sys.uramping > 0.0 + && (para.input.dft_plus_u != 1 || para.input.mixing_restart <= para.input.scf_thr)) + { + ModuleBase::WARNING_QUIT("ReadInput", "uramping requires dft_plus_u=1 and mixing_restart>scf_thr"); + } + if (para.sys.uramping > 0.0 && para.input.yukawa_potential) + { + ModuleBase::WARNING_QUIT("ReadInput", "uramping cannot be combined with yukawa_potential"); + } + }; sync_double(input.uramping_eV); add_double_bcast(sys.uramping); this->add_item(item); diff --git a/source/source_lcao/module_dftu/dftu_nao_op.cpp b/source/source_lcao/module_dftu/dftu_nao_op.cpp index 2518ad424c5..a59bb30562d 100644 --- a/source/source_lcao/module_dftu/dftu_nao_op.cpp +++ b/source/source_lcao/module_dftu/dftu_nao_op.cpp @@ -167,17 +167,20 @@ void hamilt::DFTU_onsite>::contribute_hubbard_atoms if (!this->dftu->is_occmat_ready()) { assert(dmr != nullptr); - DFTU_LCAO::compute_occ_from_dmr(*this->ucell, - *this->dftu, + DFTU_LCAO::project_occ_from_dmr(*this->ucell, iat0, - target_L, - this->current_spin, this->nspin, adjs, pv, this->nlm_tot, *dmr, occ); + if (this->dftu->has_occ_mixer()) + { + const double beta = this->dftu->occ_mixer().beta(); + this->dftu->occ_mixer().mix_onsite_block(iat0, this->current_spin, occ, beta); + } + this->dftu->occmat().set_flat(iat0, target_L, this->current_spin, occ); } else { @@ -194,6 +197,12 @@ void hamilt::DFTU_onsite>::contribute_hubbard_atoms snapshot.l = target_L; snapshot.u_eV = u_value * ModuleBase::Ry_to_eV; snapshot.input = occ; + if (this->dftu->has_occ_mixer() && !this->dftu->is_occmat_ready()) + { + const int size = occ.size(); + snapshot.raw_before_occupation_mixing = this->dftu->occ_mixer().raw_block(iat0, this->current_spin, size); + snapshot.after_occupation_mixing = this->dftu->occ_mixer().mixed_block(iat0, this->current_spin, size); + } this->diagnostic_inputs_.push_back(snapshot); } std::vector pot_onsite_tmp(occ.size()); @@ -217,7 +226,10 @@ void hamilt::DFTU_onsite>::finish_spin_step() } if (this->current_spin == this->nspin - 1 || this->nspin == 4) { - this->dftu->set_occmat_stale(); + if (this->dftu->get_init_occ_mat() != 2) + { + this->dftu->set_occmat_stale(); + } } if (this->nspin == 2) { @@ -320,16 +332,14 @@ void hamilt::DFTU_onsite>::contributeHR() } template -void hamilt::DFTU_onsite>::write_scf_diagnostics( - const ScfDiagnostics::ScfDiagnosticStep& step, - std::ostream& running_log) const +std::vector +hamilt::DFTU_onsite>::observe_scf_occupations() const { // Honest scope restriction: no spinor packing or symmetry restoration is // silently interpreted as a real collinear 5x5 matrix. - if (this->nspin != 2 || ModuleSymmetry::Symmetry::symm_flag == 1 - || step.mixing_dftu != 0 || step.mixing_dmr) + if (this->nspin != 2 || ModuleSymmetry::Symmetry::symm_flag == 1) { - throw std::runtime_error("SCF diagnostics require nspin=2, symmetry=0, mixing_dftu=0, mixing_dmr=0"); + throw std::runtime_error("SCF diagnostics require nspin=2, symmetry=0"); } const Parallel_Orbitals* pv = this->hR->get_atom_pair(0).get_paraV(); std::vector blocks; @@ -357,6 +367,8 @@ void hamilt::DFTU_onsite>::write_scf_diagnostics( if (input.atom == block.atom && input.spin == spin) { block.input = input.input; + block.raw_before_occupation_mixing = input.raw_before_occupation_mixing; + block.after_occupation_mixing = input.after_occupation_mixing; } } const hamilt::HContainer* dmr = this->dm_->get_dmr_ptr(spin + 1); @@ -365,7 +377,7 @@ void hamilt::DFTU_onsite>::write_scf_diagnostics( blocks.push_back(block); } } - ScfDiagnostics::write_scf_diagnostics(step, blocks, running_log); + return blocks; } template class hamilt::DFTU_onsite>; diff --git a/source/source_lcao/module_dftu/dftu_nao_op.h b/source/source_lcao/module_dftu/dftu_nao_op.h index 82e1427d99e..ca6ff9b74c6 100644 --- a/source/source_lcao/module_dftu/dftu_nao_op.h +++ b/source/source_lcao/module_dftu/dftu_nao_op.h @@ -72,8 +72,7 @@ class DFTU_onsite> : public OperatorLCAO void set_kv(const K_Vectors* kv_in) { this->kv_ = kv_in; } // Observes the raw solved DMR without modifying Plus_U, DMR, or mixing. - void write_scf_diagnostics(const ScfDiagnostics::ScfDiagnosticStep& step, - std::ostream& running_log) const; + std::vector observe_scf_occupations() const; private: bool should_restore_symmetric_dmr() const; diff --git a/source/source_lcao/module_dftu/unittests/CMakeLists.txt b/source/source_lcao/module_dftu/unittests/CMakeLists.txt index 1a8d6bbddbd..f5e43b04124 100644 --- a/source/source_lcao/module_dftu/unittests/CMakeLists.txt +++ b/source/source_lcao/module_dftu/unittests/CMakeLists.txt @@ -9,12 +9,6 @@ abacus_disable_feature_definitions(_OPENMP) if(ENABLE_MPI) - addtest( - TARGET MODULE_DFTU_scf_diagnostics - LIBS - SOURCES test_dftu_scf_diagnostics.cpp - ../../../source_estate/scf_diagnostics.cpp) - addtest( TARGET MODULE_DFTU_pots LIBS base device diff --git a/source/source_pw/module_pwdft/dftu_base.cpp b/source/source_pw/module_pwdft/dftu_base.cpp index ad00a2379fa..558f29711c9 100644 --- a/source/source_pw/module_pwdft/dftu_base.cpp +++ b/source/source_pw/module_pwdft/dftu_base.cpp @@ -56,7 +56,7 @@ void Plus_U_Base::init_base(UnitCell& cell, this->init_occ_mat = init_occ_mat; this->u_target = hubbard_u; this->u_current = hubbard_u; - if (uramping > 0.01) + if (uramping > 0.0) { std::fill(this->u_current.begin(), this->u_current.end(), @@ -181,6 +181,11 @@ void Plus_U_Base::init_base(UnitCell& cell, DFTU_BASE::local_occup_bcast(cell, this->occmat_, this->l_channel); #endif this->set_occmat_ready(); + this->occmat_.copy_to_save(cell, this->l_channel); + if (this->has_occ_mixer()) + { + this->occ_mixer().seed_save(this->occmat_); + } } else { @@ -199,8 +204,8 @@ void Plus_U_Base::uramping_update() { return; } - // if uramping < 0.1, use the original U - if (this->uramping < 0.01) + // A nonpositive increment disables U ramping. + if (this->uramping <= 0.0) { return; } diff --git a/source/source_pw/module_pwdft/dftu_pw.cpp b/source/source_pw/module_pwdft/dftu_pw.cpp index e2d6286f095..9669d10087e 100644 --- a/source/source_pw/module_pwdft/dftu_pw.cpp +++ b/source/source_pw/module_pwdft/dftu_pw.cpp @@ -110,7 +110,9 @@ void cal_occ_pw(const void* psi_in, if (occ_mixer != nullptr && p_chgmix != nullptr) { occ_mixer->collect(occmat); + const bool applied = p_chgmix->has_uom_coefficients(); p_chgmix->mix_uom(occ_mixer->uom(), occ_mixer->uom_save()); + occ_mixer->record_mixing(applied); occ_mixer->write_back(occmat); } @@ -160,6 +162,11 @@ std::vector observe_occ_pw( const double* input = dftu.occmat().mat(atom,l,spin).c; block.input.assign(input,input+size); } + if (dftu.has_occ_mixer()) + { + block.raw_before_occupation_mixing = dftu.occ_mixer().raw_block(atom, spin, size); + block.after_occupation_mixing = dftu.occ_mixer().mixed_block(atom, spin, size); + } blocks.push_back(block); } } diff --git a/source/source_pw/module_pwdft/unittests/test_dftu_base.cpp b/source/source_pw/module_pwdft/unittests/test_dftu_base.cpp index 88ae789928e..dbdb63859a8 100644 --- a/source/source_pw/module_pwdft/unittests/test_dftu_base.cpp +++ b/source/source_pw/module_pwdft/unittests/test_dftu_base.cpp @@ -184,6 +184,27 @@ TEST_F(DFTUBaseTest, InitBaseSeedsURampingState) } +TEST_F(DFTUBaseTest, SmallPositiveRampClampsAndRequiresTarget) +{ + Plus_U_Base dftu; + const std::vector channels = {2}; + const std::vector target = {0.005}; + dftu.init_base(ucell, 1, 2, channels, false, 0.5, "", "", "none", "cpu", + target, 0.002, 0, 0, DFTU_BASE::SOC_LAYOUT_PAULI); + EXPECT_DOUBLE_EQ(dftu.get_u_current(0), 0.0); + EXPECT_FALSE(dftu.u_converged()); + dftu.uramping_update(); + EXPECT_DOUBLE_EQ(dftu.get_u_current(0), 0.002); + dftu.uramping_update(); + EXPECT_DOUBLE_EQ(dftu.get_u_current(0), 0.004); + EXPECT_FALSE(dftu.u_converged()); + dftu.uramping_update(); + EXPECT_DOUBLE_EQ(dftu.get_u_current(0), 0.005); + EXPECT_TRUE(dftu.u_converged()); + dftu.uramping_update(); + EXPECT_DOUBLE_EQ(dftu.get_u_current(0), 0.005); +} + /// init_base owns the flat potential offsets used by PW and the occupation /// mixer. Check the real layout for unequal orbital sizes and all spin modes. TEST_F(DFTUBaseTest, InitBaseComputesMixedOrbitalOffsetsForSpinModes) diff --git a/tests/17_DS_DFTU/60_LCAO_U_BASE/INPUT b/tests/17_DS_DFTU/60_LCAO_U_BASE/INPUT new file mode 100644 index 00000000000..f6844d194b1 --- /dev/null +++ b/tests/17_DS_DFTU/60_LCAO_U_BASE/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type lcao +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 0 +mixing_dmr 0 +symmetry 0 +ks_solver genelpa +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/60_LCAO_U_BASE/KPT b/tests/17_DS_DFTU/60_LCAO_U_BASE/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/60_LCAO_U_BASE/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/60_LCAO_U_BASE/README b/tests/17_DS_DFTU/60_LCAO_U_BASE/README new file mode 100644 index 00000000000..e681dd55c98 --- /dev/null +++ b/tests/17_DS_DFTU/60_LCAO_U_BASE/README @@ -0,0 +1,3 @@ +Onsite DFT+U lcao: occupation mixing=False, DMR mixing=False, U-ramping=False. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/60_LCAO_U_BASE/STRU b/tests/17_DS_DFTU/60_LCAO_U_BASE/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/60_LCAO_U_BASE/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/60_LCAO_U_BASE/result.ref b/tests/17_DS_DFTU/60_LCAO_U_BASE/result.ref new file mode 100644 index 00000000000..a949c6d72c5 --- /dev/null +++ b/tests/17_DS_DFTU/60_LCAO_U_BASE/result.ref @@ -0,0 +1,3 @@ +etotref -208.4752772252195 +etotperatomref -104.2376386126 +totaltimeref 1.76 diff --git a/tests/17_DS_DFTU/61_LCAO_U_OCC/INPUT b/tests/17_DS_DFTU/61_LCAO_U_OCC/INPUT new file mode 100644 index 00000000000..8f98af2846f --- /dev/null +++ b/tests/17_DS_DFTU/61_LCAO_U_OCC/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type lcao +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 1 +mixing_dmr 0 +symmetry 0 +ks_solver genelpa +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/61_LCAO_U_OCC/KPT b/tests/17_DS_DFTU/61_LCAO_U_OCC/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/61_LCAO_U_OCC/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/61_LCAO_U_OCC/README b/tests/17_DS_DFTU/61_LCAO_U_OCC/README new file mode 100644 index 00000000000..bc4e0ba8767 --- /dev/null +++ b/tests/17_DS_DFTU/61_LCAO_U_OCC/README @@ -0,0 +1,3 @@ +Onsite DFT+U lcao: occupation mixing=True, DMR mixing=False, U-ramping=False. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/61_LCAO_U_OCC/STRU b/tests/17_DS_DFTU/61_LCAO_U_OCC/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/61_LCAO_U_OCC/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/61_LCAO_U_OCC/result.ref b/tests/17_DS_DFTU/61_LCAO_U_OCC/result.ref new file mode 100644 index 00000000000..4431ac63cf4 --- /dev/null +++ b/tests/17_DS_DFTU/61_LCAO_U_OCC/result.ref @@ -0,0 +1,3 @@ +etotref -208.4752772251175 +etotperatomref -104.2376386126 +totaltimeref 2.68 diff --git a/tests/17_DS_DFTU/62_LCAO_U_DMR/INPUT b/tests/17_DS_DFTU/62_LCAO_U_DMR/INPUT new file mode 100644 index 00000000000..1f12c1fa6b4 --- /dev/null +++ b/tests/17_DS_DFTU/62_LCAO_U_DMR/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type lcao +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 0 +mixing_dmr 1 +symmetry 0 +ks_solver genelpa +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/62_LCAO_U_DMR/KPT b/tests/17_DS_DFTU/62_LCAO_U_DMR/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/62_LCAO_U_DMR/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/62_LCAO_U_DMR/README b/tests/17_DS_DFTU/62_LCAO_U_DMR/README new file mode 100644 index 00000000000..df35ad4a2d0 --- /dev/null +++ b/tests/17_DS_DFTU/62_LCAO_U_DMR/README @@ -0,0 +1,3 @@ +Onsite DFT+U lcao: occupation mixing=False, DMR mixing=True, U-ramping=False. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/62_LCAO_U_DMR/STRU b/tests/17_DS_DFTU/62_LCAO_U_DMR/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/62_LCAO_U_DMR/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/62_LCAO_U_DMR/result.ref b/tests/17_DS_DFTU/62_LCAO_U_DMR/result.ref new file mode 100644 index 00000000000..1949a79bfe0 --- /dev/null +++ b/tests/17_DS_DFTU/62_LCAO_U_DMR/result.ref @@ -0,0 +1,3 @@ +etotref -208.4752772252149 +etotperatomref -104.2376386126 +totaltimeref 1.76 diff --git a/tests/17_DS_DFTU/63_LCAO_U_RAMP/INPUT b/tests/17_DS_DFTU/63_LCAO_U_RAMP/INPUT new file mode 100644 index 00000000000..7e967ea2221 --- /dev/null +++ b/tests/17_DS_DFTU/63_LCAO_U_RAMP/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type lcao +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 0 +mixing_dmr 0 +symmetry 0 +ks_solver genelpa +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0.5 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/63_LCAO_U_RAMP/KPT b/tests/17_DS_DFTU/63_LCAO_U_RAMP/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/63_LCAO_U_RAMP/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/63_LCAO_U_RAMP/README b/tests/17_DS_DFTU/63_LCAO_U_RAMP/README new file mode 100644 index 00000000000..73792393969 --- /dev/null +++ b/tests/17_DS_DFTU/63_LCAO_U_RAMP/README @@ -0,0 +1,3 @@ +Onsite DFT+U lcao: occupation mixing=False, DMR mixing=False, U-ramping=True. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/63_LCAO_U_RAMP/STRU b/tests/17_DS_DFTU/63_LCAO_U_RAMP/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/63_LCAO_U_RAMP/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/63_LCAO_U_RAMP/result.ref b/tests/17_DS_DFTU/63_LCAO_U_RAMP/result.ref new file mode 100644 index 00000000000..8c2b4870b74 --- /dev/null +++ b/tests/17_DS_DFTU/63_LCAO_U_RAMP/result.ref @@ -0,0 +1,3 @@ +etotref -208.4752772252224 +etotperatomref -104.2376386126 +totaltimeref 1.69 diff --git a/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/INPUT b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/INPUT new file mode 100644 index 00000000000..76f6feb9fd7 --- /dev/null +++ b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type lcao +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 1 +mixing_dmr 0 +symmetry 0 +ks_solver genelpa +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0.5 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/KPT b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/README b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/README new file mode 100644 index 00000000000..3fc20f1f9c3 --- /dev/null +++ b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/README @@ -0,0 +1,3 @@ +Onsite DFT+U lcao: occupation mixing=True, DMR mixing=False, U-ramping=True. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/STRU b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/result.ref b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/result.ref new file mode 100644 index 00000000000..b6216ed244a --- /dev/null +++ b/tests/17_DS_DFTU/64_LCAO_U_OCC_RAMP/result.ref @@ -0,0 +1,3 @@ +etotref -208.4752772252272 +etotperatomref -104.2376386126 +totaltimeref 2.58 diff --git a/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/INPUT b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/INPUT new file mode 100644 index 00000000000..36edc8d4537 --- /dev/null +++ b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type lcao +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 0 +mixing_dmr 1 +symmetry 0 +ks_solver genelpa +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0.5 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/KPT b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/README b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/README new file mode 100644 index 00000000000..e32ca210156 --- /dev/null +++ b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/README @@ -0,0 +1,3 @@ +Onsite DFT+U lcao: occupation mixing=False, DMR mixing=True, U-ramping=True. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/STRU b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/result.ref b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/result.ref new file mode 100644 index 00000000000..72f96426815 --- /dev/null +++ b/tests/17_DS_DFTU/65_LCAO_U_DMR_RAMP/result.ref @@ -0,0 +1,3 @@ +etotref -208.4752772252191 +etotperatomref -104.2376386126 +totaltimeref 1.47 diff --git a/tests/17_DS_DFTU/66_PW_U_BASE/INPUT b/tests/17_DS_DFTU/66_PW_U_BASE/INPUT new file mode 100644 index 00000000000..e36847bb91d --- /dev/null +++ b/tests/17_DS_DFTU/66_PW_U_BASE/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type pw +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 0 +mixing_dmr 0 +symmetry 0 +ks_solver dav_subspace +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/66_PW_U_BASE/KPT b/tests/17_DS_DFTU/66_PW_U_BASE/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/66_PW_U_BASE/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/66_PW_U_BASE/README b/tests/17_DS_DFTU/66_PW_U_BASE/README new file mode 100644 index 00000000000..e6cf4fe1b60 --- /dev/null +++ b/tests/17_DS_DFTU/66_PW_U_BASE/README @@ -0,0 +1,3 @@ +Onsite DFT+U pw: occupation mixing=False, DMR mixing=False, U-ramping=False. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/66_PW_U_BASE/STRU b/tests/17_DS_DFTU/66_PW_U_BASE/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/66_PW_U_BASE/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/66_PW_U_BASE/result.ref b/tests/17_DS_DFTU/66_PW_U_BASE/result.ref new file mode 100644 index 00000000000..720fda8b34f --- /dev/null +++ b/tests/17_DS_DFTU/66_PW_U_BASE/result.ref @@ -0,0 +1,3 @@ +etotref -210.4998674863253 +etotperatomref -105.2499337432 +totaltimeref 0.66 diff --git a/tests/17_DS_DFTU/67_PW_U_OCC/INPUT b/tests/17_DS_DFTU/67_PW_U_OCC/INPUT new file mode 100644 index 00000000000..be11df69895 --- /dev/null +++ b/tests/17_DS_DFTU/67_PW_U_OCC/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type pw +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 1 +mixing_dmr 0 +symmetry 0 +ks_solver dav_subspace +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/67_PW_U_OCC/KPT b/tests/17_DS_DFTU/67_PW_U_OCC/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/67_PW_U_OCC/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/67_PW_U_OCC/README b/tests/17_DS_DFTU/67_PW_U_OCC/README new file mode 100644 index 00000000000..fdbca8259ee --- /dev/null +++ b/tests/17_DS_DFTU/67_PW_U_OCC/README @@ -0,0 +1,3 @@ +Onsite DFT+U pw: occupation mixing=True, DMR mixing=False, U-ramping=False. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/67_PW_U_OCC/STRU b/tests/17_DS_DFTU/67_PW_U_OCC/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/67_PW_U_OCC/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/67_PW_U_OCC/result.ref b/tests/17_DS_DFTU/67_PW_U_OCC/result.ref new file mode 100644 index 00000000000..e0d3ea31ba3 --- /dev/null +++ b/tests/17_DS_DFTU/67_PW_U_OCC/result.ref @@ -0,0 +1,3 @@ +etotref -210.4998673442242 +etotperatomref -105.2499336721 +totaltimeref 0.62 diff --git a/tests/17_DS_DFTU/68_PW_U_RAMP/INPUT b/tests/17_DS_DFTU/68_PW_U_RAMP/INPUT new file mode 100644 index 00000000000..d49fee66cf4 --- /dev/null +++ b/tests/17_DS_DFTU/68_PW_U_RAMP/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type pw +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 0 +mixing_dmr 0 +symmetry 0 +ks_solver dav_subspace +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0.5 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/68_PW_U_RAMP/KPT b/tests/17_DS_DFTU/68_PW_U_RAMP/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/68_PW_U_RAMP/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/68_PW_U_RAMP/README b/tests/17_DS_DFTU/68_PW_U_RAMP/README new file mode 100644 index 00000000000..c5ad64e8362 --- /dev/null +++ b/tests/17_DS_DFTU/68_PW_U_RAMP/README @@ -0,0 +1,3 @@ +Onsite DFT+U pw: occupation mixing=False, DMR mixing=False, U-ramping=True. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/68_PW_U_RAMP/STRU b/tests/17_DS_DFTU/68_PW_U_RAMP/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/68_PW_U_RAMP/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/68_PW_U_RAMP/result.ref b/tests/17_DS_DFTU/68_PW_U_RAMP/result.ref new file mode 100644 index 00000000000..910486ad5d2 --- /dev/null +++ b/tests/17_DS_DFTU/68_PW_U_RAMP/result.ref @@ -0,0 +1,3 @@ +etotref -210.4998673332962 +etotperatomref -105.2499336666 +totaltimeref 0.54 diff --git a/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/INPUT b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/INPUT new file mode 100644 index 00000000000..4350283601e --- /dev/null +++ b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/INPUT @@ -0,0 +1,31 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +basis_type pw +ecutwfc 20 +nspin 2 +nbands 8 +scf_thr 1e-7 +scf_nmax 120 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 +mixing_beta_mag 0.4 +mixing_ndim 4 +mixing_restart 0.01 +mixing_dftu 1 +mixing_dmr 0 +symmetry 0 +ks_solver dav_subspace +dft_plus_u 1 +orbital_corr 1 +hubbard_u 1.0 +onsite_radius 3.0 +uramping 0.5 +out_occ_mat 1 +out_freq_elec 1 +out_chg 0 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +pw_seed 1 diff --git a/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/KPT b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/KPT new file mode 100644 index 00000000000..f5f7f4ec34c --- /dev/null +++ b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 2 2 0 0 0 diff --git a/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/README b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/README new file mode 100644 index 00000000000..571e8d5a49d --- /dev/null +++ b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/README @@ -0,0 +1,3 @@ +Onsite DFT+U pw: occupation mixing=True, DMR mixing=False, U-ramping=True. +Use ABACUS_SCF_DIAGNOSTICS=1 to validate per-electronic-step matrices. +Diamond Si p-shell regression; tests update semantics rather than a material-specific U value. diff --git a/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/STRU b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/STRU new file mode 100644 index 00000000000..d1f776f33d7 --- /dev/null +++ b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 28.085 Si_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Si_gga_6au_100Ry_2s2p1d.orb + +LATTICE_CONSTANT +10.26 + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct +Si +0.0 +2 +0.0 0.0 0.0 mag 0.0 +0.25 0.25 0.25 mag 0.0 diff --git a/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/result.ref b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/result.ref new file mode 100644 index 00000000000..5fded94c455 --- /dev/null +++ b/tests/17_DS_DFTU/69_PW_U_OCC_RAMP/result.ref @@ -0,0 +1,3 @@ +etotref -210.4998673510555 +etotperatomref -105.2499336755 +totaltimeref 0.54 diff --git a/tests/17_DS_DFTU/CASES_CPU.txt b/tests/17_DS_DFTU/CASES_CPU.txt index 892a9f68ddd..151e646c0b3 100644 --- a/tests/17_DS_DFTU/CASES_CPU.txt +++ b/tests/17_DS_DFTU/CASES_CPU.txt @@ -13,3 +13,15 @@ 03_LCAO_DFTU_S2_Z # 04_LCAO_DFTU_S4_XY # DISABLED: Convergence / numerical stability issue with LCAO noncollinear DFT+U # 05_LCAO_DFTU_S4_XYZ # DISABLED: Convergence / numerical stability issue with LCAO noncollinear DFT+U + +# Onsite +U occupation / DMR mixing and U-ramping regressions +60_LCAO_U_BASE +61_LCAO_U_OCC +62_LCAO_U_DMR +63_LCAO_U_RAMP +64_LCAO_U_OCC_RAMP +65_LCAO_U_DMR_RAMP +66_PW_U_BASE +67_PW_U_OCC +68_PW_U_RAMP +69_PW_U_OCC_RAMP diff --git a/tests/17_DS_DFTU/CASES_DFTU_MIXING.txt b/tests/17_DS_DFTU/CASES_DFTU_MIXING.txt new file mode 100644 index 00000000000..092e37fbc85 --- /dev/null +++ b/tests/17_DS_DFTU/CASES_DFTU_MIXING.txt @@ -0,0 +1,10 @@ +60_LCAO_U_BASE +61_LCAO_U_OCC +62_LCAO_U_DMR +63_LCAO_U_RAMP +64_LCAO_U_OCC_RAMP +65_LCAO_U_DMR_RAMP +66_PW_U_BASE +67_PW_U_OCC +68_PW_U_RAMP +69_PW_U_OCC_RAMP diff --git a/tests/integrate/validation_tools/check_dftu_scf_diagnostics.py b/tests/integrate/validation_tools/check_dftu_scf_diagnostics.py new file mode 100644 index 00000000000..67f44010a8a --- /dev/null +++ b/tests/integrate/validation_tools/check_dftu_scf_diagnostics.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Validate an existing onsite +U diagnostic run; does not launch calculations. + +Usage: python check_dftu_scf_diagnostics.py CASE/OUT.autotest/scf_diagnostics.jsonl + [--require-ramp] [--require-dmr] [--require-occupation] +""" +import argparse +import json +import math +from pathlib import Path + + +def close(a, b, tolerance=2e-10): + return len(a) == len(b) and all(abs(x-y) < tolerance for x, y in zip(a, b)) + + +def validate(path, require_ramp=False, require_dmr=False, require_occupation=False): + records = [json.loads(line) for line in Path(path).read_text().splitlines()] + assert records, 'Missing completed electronic steps' + previous = None + ramp_seen = False + dmr_seen = False + occupation_seen = False + for record in records: + assert record['schema'] == 4 + assert record['ionic_step'] >= 1 + if previous and previous['ionic_step'] == record['ionic_step']: + assert record['iteration'] == previous['iteration'] + 1 + blocks = record['blocks'] + assert blocks + correction = 0.0 + for index, block in enumerate(blocks): + dim = block['dimension'] + for key in ['n_in', 'n_raw_out', 'n_before_occupation_mixing', + 'n_after_occupation_mixing', 'n_after_dmr_mixing']: + matrix = block[key] + if matrix is not None: + assert len(matrix) == dim * dim + assert all(math.isfinite(x) for x in matrix) + assert all(abs(matrix[i*dim+j]-matrix[j*dim+i]) < 2e-10 + for i in range(dim) for j in range(dim)) + mixed = block['n_after_occupation_mixing'] + if mixed is not None: + occupation_seen = True + assert close(mixed, block['n_in']) + if record['basis_type'] == 'lcao' and previous: + old = previous['blocks'][index]['n_in'] + raw = block['n_before_occupation_mixing'] + if old is not None: + beta = record['mixing_beta'] + expected = [beta*x+(1-beta)*y for x, y in zip(raw, old)] + assert close(mixed, expected), 'Incorrect onsite linear mixing' + if previous and record['iteration'] > 1: + prev = previous['blocks'][index] + ramp_seen |= block['U_eff_eV'] != prev['U_eff_eV'] + if mixed is None and block['n_in'] is not None: + expected = prev['n_after_dmr_mixing'] + if expected is None: + expected = prev['n_raw_out'] + assert close(block['n_in'], expected), 'Hubbard input is not previous output' + if block['n_in'] is not None: + n = block['n_in'] + trace_n2 = sum(n[i*dim+j]*n[j*dim+i] for i in range(dim) for j in range(dim)) + correction += 0.5*block['U_eff_eV']*trace_n2 + assert (block['n_after_dmr_mixing'] is not None) == bool(record['dmr_mixing_executed']) + assert abs(correction-record['source_band_correction_eV']) < 2e-9 + if record['dmr_mixing_executed']: + dmr_seen = True + assert record['mixing_restart_count'] > 0 + # No fresh charge coefficients on the step immediately before a restart. + assert record['mixing_restart_scheduled_step'] != record['iteration'] + 1 + if record['scf_converged']: + assert record['u_at_target'] + previous = record + assert not require_ramp or ramp_seen, 'U never advanced' + assert not require_dmr or dmr_seen, 'DMR mixing never executed' + assert not require_occupation or occupation_seen, 'Occupation mixing never executed' + return dict(steps=len(records), ramp_seen=ramp_seen, dmr_seen=dmr_seen, + occupation_seen=occupation_seen, converged=bool(records[-1]['scf_converged'])) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('path') + parser.add_argument('--require-ramp', action='store_true') + parser.add_argument('--require-dmr', action='store_true') + parser.add_argument('--require-occupation', action='store_true') + args = parser.parse_args() + print(json.dumps(validate(args.path, args.require_ramp, args.require_dmr, args.require_occupation)))