diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 176e9551fd..afcf4b4158 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -282,6 +282,8 @@ OBJS_DEEPKS=lcao_deepks.o\ OBJS_ELECSTAT=elecstate.o\ + electronic_control.o\ + electronic_occupations.o\ init_scf.o\ param_update.o\ estate_e_terms.o\ @@ -309,6 +311,7 @@ OBJS_ELECSTAT=elecstate.o\ efield.o\ gatefield.o\ potential_new.o\ + elpot.o\ potential_types.o\ pot_surchem.o\ pot_sep.o\ @@ -644,8 +647,10 @@ OBJS_RELAXATION=relax_data.o\ socket_frame.o\ socket_frame_utils.o\ socket_driver.o\ + socket_ks.o\ socket_utils.o\ socket_handlers.o\ + socket_constant_potential.o\ cg_base.o\ bfgs_basic.o\ relax_driver.o\ diff --git a/source/source_esolver/esolver_factory.cpp b/source/source_esolver/esolver_factory.cpp index 5e0f0fb803..c85a95b82a 100644 --- a/source/source_esolver/esolver_factory.cpp +++ b/source/source_esolver/esolver_factory.cpp @@ -1,14 +1,15 @@ #include "esolver_factory.h" #include "esolver.h" -#include "esolver_ks_pw.h" #include "esolver_dfpt_pw.h" -#include "esolver_sdft_pw.h" +#include "esolver_ks_pw.h" #include "esolver_ks_pw_tddft.h" +#include "esolver_sdft_pw.h" #include "source_base/global_variable.h" #include "source_base/module_device/device.h" #include "source_hamilt/module_xc/general_exx_info.h" #include "source_io/module_parameter/parameter.h" +#include "source_relax/socket_driver.h" #ifdef __LCAO #include "esolver_dm2rho.h" #include "esolver_double_xc.h" @@ -158,6 +159,8 @@ ESolver* init_esolver(const Input_para& inp) // determine type of esolver based on INPUT information const std::string esolver_type = determine_type(inp); const bool gamma_only = inp.gamma_only; + const bool socket_ks = + inp.socket_driver && inp.device == "cpu" && inp.precision == "double" && (inp.nspin == 1 || inp.nspin == 2); #ifdef __LCAO const LRRuntime lr_runtime{GlobalV::ofs_running, GlobalV::ofs_warning, GlobalV::MY_RANK}; #endif @@ -184,6 +187,10 @@ ESolver* init_esolver(const Input_para& inp) } else { + if (socket_ks) + { + return SocketCP::create_pw_socket_solver(); + } return new ESolver_KS_PW, base_device::DEVICE_CPU>(); } } @@ -298,10 +305,18 @@ ESolver* init_esolver(const Input_para& inp) { if (gamma_only) { + if (socket_ks) + { + return SocketCP::create_lcao_socket_solver(true); + } return new ESolver_KS_LCAO(); } else if (inp.nspin < 4) { + if (socket_ks) + { + return SocketCP::create_lcao_socket_solver(false); + } return new ESolver_KS_LCAO, double>(); } else diff --git a/source/source_estate/CMakeLists.txt b/source/source_estate/CMakeLists.txt index 9f83433a27..96d8c0a9ed 100644 --- a/source/source_estate/CMakeLists.txt +++ b/source/source_estate/CMakeLists.txt @@ -2,6 +2,8 @@ list( APPEND objects elecstate.cpp + electronic_control.cpp + electronic_occupations.cpp init_scf.cpp estate_e_terms.cpp elecstate_energy.cpp @@ -19,6 +21,7 @@ list( module_pot/gatefield.cpp module_pot/efield.cpp module_pot/h_hartree_pw.cpp + module_pot/elpot.cpp module_pot/h_tddft_pw.cpp module_pot/pot_xc.cpp module_pot/pot_local.cpp diff --git a/source/source_estate/elecstate.cpp b/source/source_estate/elecstate.cpp index 5ed97e678c..9f96352907 100644 --- a/source/source_estate/elecstate.cpp +++ b/source/source_estate/elecstate.cpp @@ -12,19 +12,18 @@ const double* ElecState::getRho(int spin) const return &(this->charge->rho[spin][0]); } +void ElecState::init_nelec_spin() { this->init_nelec_spin(PARAM.inp.nspin, PARAM.inp.nelec, PARAM.inp.nupdown); } - -void ElecState::init_nelec_spin() +void ElecState::init_nelec_spin(int nspin, double nelect, double nupdown) { - this->nelec_spin.resize(PARAM.inp.nspin); - if (PARAM.inp.nspin == 2) + this->nelec_spin.resize(nspin); + if (nspin == 2) { - this->nelec_spin[0] = (PARAM.inp.nelec + PARAM.inp.nupdown) / 2.0; - this->nelec_spin[1] = (PARAM.inp.nelec - PARAM.inp.nupdown) / 2.0; + this->nelec_spin[0] = (nelect + nupdown) / 2.0; + this->nelec_spin[1] = (nelect - nupdown) / 2.0; } } - void ElecState::init_ks(Charge* chr_in, // pointer for class Charge const K_Vectors* klist_in, int nk_in, diff --git a/source/source_estate/elecstate.h b/source/source_estate/elecstate.h index ba96ff1457..a5643e6d7c 100644 --- a/source/source_estate/elecstate.h +++ b/source/source_estate/elecstate.h @@ -116,6 +116,7 @@ class ElecState // if nupdown is not 0(TWO_EFERMI case), // nelec_spin will be fixed and weights will be constrained void init_nelec_spin(); + void init_nelec_spin(int nspin, double nelect, double nupdown); // used to record number of electrons per spin index // for NSPIN=2, it will record number of spin up and number of spin down // for NSPIN=4, it will record total number, magnetization for x, y, z direction diff --git a/source/source_estate/elecstate_tools.cpp b/source/source_estate/elecstate_tools.cpp index 3b64aca047..bcf21b60d4 100644 --- a/source/source_estate/elecstate_tools.cpp +++ b/source/source_estate/elecstate_tools.cpp @@ -1,9 +1,11 @@ #include "elecstate_tools.h" #include "occupy.h" + #include "source_base/module_parallel/para_band_output.h" #include "source_base/module_parallel/para_bridge.h" #include "source_base/parallel_reduce.h" +#include #include diff --git a/source/source_estate/electronic_control.cpp b/source/source_estate/electronic_control.cpp new file mode 100644 index 0000000000..b6259022c5 --- /dev/null +++ b/source/source_estate/electronic_control.cpp @@ -0,0 +1,104 @@ +#include "electronic_control.h" + +#include "elecstate.h" +#include "electronic_occupations.h" +#include "module_pot/elpot.h" +#include "param_update.h" +#include "source_io/module_parameter/input_parameter.h" + +#include +#include + +namespace elecstate +{ +void prepare_electronic_step( + const UnitCell &cell, + ElecState *state, + ElectronicStep &step, + const Input_para &input) +{ + if (!state || !state->charge || !state->pot) + { + throw std::runtime_error("electronic state is not initialized for electron control"); + } + if (!step.parameters) + { + throw std::runtime_error("electronic request requires parameter storage"); + } + if (step.request_applied || step.result_ready) + { + throw std::runtime_error("electronic request has already been applied"); + } + + if (step.window.axis >= 0) + { + if (!state->charge->rhopw) + { + throw std::runtime_error("electrostatic window requires the density FFT grid"); + } + potential_window_planes( + cell, *state->charge->rhopw, step.window.axis, step.window.minimum_A, step.window.maximum_A); + } + + ParamUpdater::update_electron_count(step.control.nelect, *step.parameters); + update_electron_count(*state, step.control.nelect, input.nspin, input.nupdown, step.two_fermi); + step.request_applied = true; +} + +void complete_electronic_step( + const UnitCell &cell, + ElecState *state, + ModulePW::PW_Basis *basis, + const surchem &solvent, + const Input_para &input, + bool converged, + ElectronicStep &step) +{ + if (!step.request_applied || !converged || !state || !state->charge || !state->pot || !basis) + { + throw std::runtime_error("electronic observables require an applied request and a converged SCF state"); + } + if (step.result_ready) + { + throw std::runtime_error("electronic observables have already been collected"); + } + + ElectronicObservables result; + const int npool = input.kpar * input.bndpar; + result.nelect = checked_occupation_electron_count(state->wg, step.control.nelect, npool, basis->poolnproc); + result.fermi_ry = electronic_chemical_potential(state->eferm, step.two_fermi); + if (step.window.axis >= 0) + { + result.reference_ry = + electrostatic_reference(cell, *basis, *state->charge, *state->pot, solvent, input, step.window); + } + step.result = result; + step.result_ready = true; +} + +void update_electron_count( + ElecState &state, + double nelect, + int nspin, + double nupdown, + bool two_fermi) +{ + state.eferm.two_efermi = two_fermi; + state.init_nelec_spin(nspin, nelect, nupdown); +} + +double electronic_chemical_potential(const Efermi &fermi, bool two_fermi) +{ + double chemical_potential = fermi.ef; + if (two_fermi) + { + // Total-N derivative at fixed N_up-N_down. + chemical_potential = 0.5 * (fermi.ef_up + fermi.ef_dw); + } + if (!std::isfinite(chemical_potential)) + { + throw std::runtime_error("non-finite SCF chemical potential"); + } + return chemical_potential; +} +} // namespace elecstate diff --git a/source/source_estate/electronic_control.h b/source/source_estate/electronic_control.h new file mode 100644 index 0000000000..007f8dcfa6 --- /dev/null +++ b/source/source_estate/electronic_control.h @@ -0,0 +1,75 @@ +#ifndef ABACUS_ELECTRONIC_CONTROL_H +#define ABACUS_ELECTRONIC_CONTROL_H + +class Parameter; +class UnitCell; +class surchem; +struct Input_para; +namespace ModulePW +{ +class PW_Basis; +} + +namespace elecstate +{ +class ElecState; +struct Efermi; + +// Physical requests and results; no socket or serialization dependencies. +struct ElectronicControl +{ + double nelect = 0.0; +}; + +struct PotentialWindow +{ + int axis = -1; + double minimum_A = 0.0; + double maximum_A = 0.0; +}; + +struct ElectronicObservables +{ + double nelect = 0.0; + double fermi_ry = 0.0; + double reference_ry = 0.0; +}; + +// Owned by the caller for one evaluation; all referenced objects outlive it. +// Each MPI rank has its own step. Only a completed result may be published. +struct ElectronicStep +{ + Parameter *parameters = nullptr; + ElectronicControl control; + PotentialWindow window; + bool two_fermi = false; + ElectronicObservables result; + bool request_applied = false; + bool result_ready = false; +}; + +void prepare_electronic_step( + const UnitCell &cell, + ElecState *state, + ElectronicStep &step, + const Input_para &input); +// Call after nuclear forces: constructing the reference updates electric-field state. +void complete_electronic_step( + const UnitCell &cell, + ElecState *state, + ModulePW::PW_Basis *basis, + const surchem &solvent, + const Input_para &input, + bool converged, + ElectronicStep &step); + +void update_electron_count( + ElecState &state, + double nelect, + int nspin, + double nupdown, + bool two_fermi); +double electronic_chemical_potential(const Efermi &fermi, bool two_fermi); +} // namespace elecstate + +#endif diff --git a/source/source_estate/electronic_occupations.cpp b/source/source_estate/electronic_occupations.cpp new file mode 100644 index 0000000000..654daec659 --- /dev/null +++ b/source/source_estate/electronic_occupations.cpp @@ -0,0 +1,68 @@ +#include "electronic_occupations.h" +#include "source_base/matrix.h" +#include "source_base/parallel_reduce.h" + +#include +#include +#include +#include + +namespace elecstate +{ +double checked_occupation_electron_count( + const ModuleBase::matrix &weights, + double requested_nelect, + int npool, + int ranks_per_pool) +{ + int invalid = !std::isfinite(requested_nelect) || requested_nelect <= 0.0 || npool <= 0 || ranks_per_pool <= 0; + double occupied = 0.0; + double compensation = 0.0; + for (int ik = 0; ik < weights.nr; ++ik) + { + for (int ib = 0; ib < weights.nc; ++ib) + { + const double weight = weights(ik, ib); + if (!std::isfinite(weight)) + { + invalid = 1; + continue; + } + // Compensated sum of the local k/spin and band shard. Generalized + // smearing weights may be negative; only their total is constrained. + const double corrected = weight - compensation; + const double next = occupied + corrected; + compensation = (next - occupied) - corrected; + occupied = next; + } + } + if (!std::isfinite(occupied)) + { + invalid = 1; + } + // Synchronize failures before a rank can enter a different collective path. + Parallel_Reduce::reduce_all(invalid); + if (invalid) + { + throw std::runtime_error( + "constant-potential electron count requires finite occupations " + "and a valid target/occupation partition"); + } + + // Same distribution as the native band-energy sum: remove the replicated + // copies inside each pool before combining KPAR and BNDPAR contributions. + Parallel_Reduce::reduce_double_allpool(npool, ranks_per_pool, occupied); + const double tolerance = 1.0e-8; + int mismatch = !std::isfinite(occupied) || occupied <= 0.0 || std::abs(occupied - requested_nelect) > tolerance; + Parallel_Reduce::reduce_all(mismatch); + if (mismatch) + { + std::ostringstream message; + message << std::setprecision(17) + << "constant-potential occupation electron count mismatch: requested=" << requested_nelect + << ", occupied=" << occupied << ", absolute tolerance=" << tolerance; + throw std::runtime_error(message.str()); + } + return occupied; +} +} // namespace elecstate diff --git a/source/source_estate/electronic_occupations.h b/source/source_estate/electronic_occupations.h new file mode 100644 index 0000000000..e28271affd --- /dev/null +++ b/source/source_estate/electronic_occupations.h @@ -0,0 +1,21 @@ +#ifndef ABACUS_ELECTRONIC_OCCUPATIONS_H +#define ABACUS_ELECTRONIC_OCCUPATIONS_H + +namespace ModuleBase +{ +class matrix; +} + +namespace elecstate +{ +// weights already include k-point weights and spin degeneracy. Rows/bands are +// partitioned across npool groups and replicated on ranks_per_pool ranks. +// All ranks must participate; invalid occupations or a mismatch fail together. +double checked_occupation_electron_count( + const ModuleBase::matrix &weights, + double requested_nelect, + int npool, + int ranks_per_pool); +} // namespace elecstate + +#endif diff --git a/source/source_estate/module_pot/elpot.cpp b/source/source_estate/module_pot/elpot.cpp new file mode 100644 index 0000000000..46a2051e6f --- /dev/null +++ b/source/source_estate/module_pot/elpot.cpp @@ -0,0 +1,205 @@ +#include "elpot.h" +#include "efield.h" +#include "h_hartree_pw.h" +#include "potential_new.h" +#include "source_base/module_parallel/para_mpi_func.h" +#include "source_base/module_parallel/para_world.h" +#include "source_estate/electronic_control.h" +#include "source_estate/module_charge/charge.h" +#include "source_hamilt/module_surchem/surchem.h" +#include "source_io/module_parameter/input_parameter.h" + +#include +#include + +namespace +{ +int first_plane_at_or_after(int count, double height_A, double bound) +{ + int lo = 0; + int hi = count; + while (lo < hi) + { + const int mid = lo + (hi - lo) / 2; + if (static_cast(mid) / count * height_A < bound) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + return lo; +} +} // namespace + +namespace elecstate +{ +double electrostatic_reference( + const UnitCell &cell, + ModulePW::PW_Basis &basis, + const Charge &charge, + const Potential &pot, + const surchem &solvent, + const Input_para &input, + const PotentialWindow &window) +{ + const double *fixed = basis.nrxx > 0 ? pot.get_fixed_v() : nullptr; + const std::vector *pcc_potential = pot.pcc_electron_potential(); + const std::vector *solvent_potential = pot.find_sol_pot(); + const std::vector potential = + electrostatic_potential(cell, basis, charge, fixed, solvent, input, pcc_potential, solvent_potential); + return planar_potential_average(cell, basis, potential, window.axis, window.minimum_A, window.maximum_A); +} + +std::vector electrostatic_potential( + const UnitCell &cell, + ModulePW::PW_Basis &basis, + const Charge &charge, + const double *fixed, + const surchem &solvent, + const Input_para &input, + const std::vector *pcc_potential, + const std::vector *solvent_potential) +{ + if (basis.nrxx > 0 && (!fixed || (input.imp_sol == 1 && !solvent.delta_phi))) + { + throw std::runtime_error("electrostatic reference requires initialized fixed and solvent potentials"); + } + if (solvent_potential && solvent_potential->size() != static_cast(basis.nrxx)) + { + throw std::runtime_error("Solvent potential does not match the output grid"); + } + const ModuleBase::matrix hartree = H_Hartree_pw::v_hartree(cell, &basis, input.nspin, charge.rho); + ModuleBase::matrix dipole; + const bool add_dipole = input.efield_flag && input.dip_cor_flag; + if (add_dipole) + { + dipole = Efield::add_efield(cell, &basis, input.nspin, charge.rho, solvent); + } + std::vector potential(basis.nrxx); + for (int ir = 0; ir < basis.nrxx; ++ir) + { + potential[ir] = hartree(0, ir) + fixed[ir]; + if (add_dipole) + { + potential[ir] += dipole(0, ir); + } + if (pcc_potential) + { + potential[ir] += (*pcc_potential)[ir]; + } + if (solvent_potential) + { + potential[ir] += (*solvent_potential)[ir]; + } + if (input.imp_sol == 1) + { + potential[ir] += solvent.delta_phi[ir]; + } + } + return potential; +} + +double checked_window_height( + const UnitCell &cell, + int axis, + double minimum_A, + double maximum_A) +{ + if (axis < 0 || axis > 2 || !std::isfinite(minimum_A) || !std::isfinite(maximum_A) || minimum_A < 0 || + maximum_A <= minimum_A) + { + throw std::runtime_error("invalid electrostatic averaging axis/window"); + } + const double lattice[3][3] = {{cell.latvec.e11, cell.latvec.e12, cell.latvec.e13}, + {cell.latvec.e21, cell.latvec.e22, cell.latvec.e23}, {cell.latvec.e31, cell.latvec.e32, cell.latvec.e33}}; + const int first = (axis + 1) % 3; + const int second = (axis + 2) % 3; + const double cross[3] = {lattice[first][1] * lattice[second][2] - lattice[first][2] * lattice[second][1], + lattice[first][2] * lattice[second][0] - lattice[first][0] * lattice[second][2], + lattice[first][0] * lattice[second][1] - lattice[first][1] * lattice[second][0]}; + double area2 = 0.0; + double volume = 0.0; + for (int i = 0; i < 3; ++i) + { + area2 += cross[i] * cross[i]; + volume += lattice[axis][i] * cross[i]; + } + const double height_A = cell.lat0_angstrom * std::abs(volume) / std::sqrt(area2); + if (!std::isfinite(height_A) || height_A <= 0.0 || maximum_A > height_A + 1.0e-10) + { + throw std::runtime_error("electrostatic averaging window lies outside the cell height"); + } + return height_A; +} + +std::pair potential_window_planes( + const UnitCell &cell, + const ModulePW::PW_Basis &basis, + int axis, + double minimum_A, + double maximum_A) +{ + const double height_A = checked_window_height(cell, axis, minimum_A, maximum_A); + const int grid[3] = {basis.nx, basis.ny, basis.nz}; + if (grid[0] <= 0 || grid[1] <= 0 || grid[2] <= 0) + { + throw std::runtime_error("invalid distributed FFT grid for electrostatic averaging"); + } + + // Use the same i/n coordinates as the cube writer, including at roundoff-sensitive edges. + const int count = grid[axis]; + const int first = first_plane_at_or_after(count, height_A, minimum_A); + const int end = first_plane_at_or_after(count, height_A, maximum_A); + if (first == end) + { + throw std::runtime_error("no FFT points in averaging window"); + } + return {first, end}; +} + +double planar_potential_average( + const UnitCell &cell, + const ModulePW::PW_Basis &basis, + const std::vector &potential, + int axis, + double minimum_A, + double maximum_A) +{ + const std::pair planes = potential_window_planes(cell, basis, axis, minimum_A, maximum_A); + if (basis.nrxx < 0 || (basis.nrxx > 0 && basis.nplane <= 0) || + potential.size() != static_cast(basis.nrxx)) + { + throw std::runtime_error("invalid distributed FFT grid for electrostatic averaging"); + } + double reduction[3] = {0.0, 0.0, 0.0}; + for (int ir = 0; ir < basis.nrxx; ++ir) + { + const int xy = ir / basis.nplane; + const int indices[3] = {xy / basis.ny, xy % basis.ny, ir % basis.nplane + basis.startz_current}; + if (!std::isfinite(potential[ir])) + { + reduction[2] += 1.0; + } + if (indices[axis] >= planes.first && indices[axis] < planes.second) + { + reduction[0] += potential[ir]; + reduction[1] += 1.0; + } + } + // Reduce over this FFT grid's communicator without summing replicated pools. +#ifdef __MPI + const Parallel::ParaWorld grid_world = Parallel::ParaWorld::make_mpi("electrostatic_grid", basis.pool_world); +#else + const Parallel::ParaWorld grid_world = Parallel::ParaWorld::serial("electrostatic_grid"); +#endif + Parallel::reduce_all(reduction, 3, grid_world); + if (reduction[2] || reduction[1] <= 0.0 || !std::isfinite(reduction[0])) + { + throw std::runtime_error("non-finite electrostatic potential or no FFT points in averaging window"); + } + return reduction[0] / reduction[1]; +} +} // namespace elecstate diff --git a/source/source_estate/module_pot/elpot.h b/source/source_estate/module_pot/elpot.h new file mode 100644 index 0000000000..66db3b48c1 --- /dev/null +++ b/source/source_estate/module_pot/elpot.h @@ -0,0 +1,59 @@ +#ifndef ABACUS_ELPOT_H +#define ABACUS_ELPOT_H + +#include +#include +class UnitCell; +class Charge; +class surchem; +struct Input_para; +namespace ModulePW +{ +class PW_Basis; +} + +namespace elecstate +{ +class Potential; +struct PotentialWindow; +double electrostatic_reference( + const UnitCell &cell, + ModulePW::PW_Basis &basis, + const Charge &charge, + const Potential &pot, + const surchem &solvent, + const Input_para &input, + const PotentialWindow &window); + +// Same local electrostatic reference for cube output and electronic observables. +std::vector electrostatic_potential( + const UnitCell &cell, + ModulePW::PW_Basis &basis, + const Charge &charge, + const double *fixed, + const surchem &solvent, + const Input_para &input, + const std::vector *pcc_potential, + const std::vector *solvent_potential); +// Validate cell bounds and return the normal cell height in angstrom. +double checked_window_height( + const UnitCell &cell, + int axis, + double minimum_A, + double maximum_A); +// Return the nonempty half-open interval of global FFT plane indices. +std::pair potential_window_planes( + const UnitCell &cell, + const ModulePW::PW_Basis &basis, + int axis, + double minimum_A, + double maximum_A); +double planar_potential_average( + const UnitCell &cell, + const ModulePW::PW_Basis &basis, + const std::vector &potential, + int axis, + double minimum_A, + double maximum_A); +} // namespace elecstate +#endif diff --git a/source/source_estate/param_update.cpp b/source/source_estate/param_update.cpp index 3ff8094965..f68b08caf8 100644 --- a/source/source_estate/param_update.cpp +++ b/source/source_estate/param_update.cpp @@ -14,4 +14,6 @@ void ParamUpdater::update_from_atoms_info(const AtomsInfoResult& atoms_info) PARAM.sys.ks_run = atoms_info.ks_run; } -} \ No newline at end of file +void ParamUpdater::update_electron_count(double nelect, Parameter ¶meters) { parameters.input.nelec = nelect; } + +} // namespace elecstate diff --git a/source/source_estate/param_update.h b/source/source_estate/param_update.h index 89a0d90023..4b9fb86f16 100644 --- a/source/source_estate/param_update.h +++ b/source/source_estate/param_update.h @@ -3,13 +3,16 @@ #include "source_cell/cal_atoms_info.h" +class Parameter; + namespace elecstate { class ParamUpdater { public: static void update_from_atoms_info(const AtomsInfoResult& atoms_info); + static void update_electron_count(double nelect, Parameter ¶meters); }; } -#endif \ No newline at end of file +#endif diff --git a/source/source_estate/unittests/CMakeLists.txt b/source/source_estate/unittests/CMakeLists.txt index 7cc711ec56..0f24a029ad 100644 --- a/source/source_estate/unittests/CMakeLists.txt +++ b/source/source_estate/unittests/CMakeLists.txt @@ -26,6 +26,38 @@ addtest( if(ENABLE_MPI) + addtest( + TARGET MODULE_ESTATE_electronic_occupations_test + LIBS base device MPI::MPI_CXX + KEEP_FEATURE_DEFINITIONS __MPI + SOURCES test_electronic_occupations.cpp ../electronic_occupations.cpp) + set_tests_properties(MODULE_ESTATE_electronic_occupations_test + PROPERTIES TIMEOUT 30 ENVIRONMENT "OMP_NUM_THREADS=1") + add_test( + NAME MODULE_ESTATE_electronic_occupations_mpi4_test + COMMAND + ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 ${MPIEXEC_PREFLAGS} + $ + ${MPIEXEC_POSTFLAGS}) + set_tests_properties( + MODULE_ESTATE_electronic_occupations_mpi4_test + PROPERTIES TIMEOUT 30 PROCESSORS 4 ENVIRONMENT "OMP_NUM_THREADS=1") + + addtest( + TARGET MODULE_ESTATE_elpot_test + LIBS parameter base device planewave MPI::MPI_CXX + KEEP_FEATURE_DEFINITIONS __MPI + SOURCES test_elpot.cpp ../module_pot/elpot.cpp) + set_tests_properties(MODULE_ESTATE_elpot_test + PROPERTIES TIMEOUT 30 ENVIRONMENT "OMP_NUM_THREADS=1") + add_test( + NAME MODULE_ESTATE_elpot_mpi4_test + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) + set_tests_properties( + MODULE_ESTATE_elpot_mpi4_test PROPERTIES TIMEOUT 30 PROCESSORS 4 + ENVIRONMENT "OMP_NUM_THREADS=1") + set(pcc_test_sources ../module_pot/sccs_output.cpp ../module_pot/pot_pcc.cpp @@ -86,6 +118,9 @@ if(ENABLE_MPI) SOURCES test_elecstate.cpp ../elecstate.cpp ../elecstate_tools.cpp + ../electronic_control.cpp + ../param_update.cpp + ../electronic_occupations.cpp ../occupy.cpp ../../source_psi/psi.cpp ../../source_base/module_fft/fft_bundle.cpp diff --git a/source/source_estate/unittests/test_elecstate.cpp b/source/source_estate/unittests/test_elecstate.cpp index 317ef2805a..4fc9b4007e 100644 --- a/source/source_estate/unittests/test_elecstate.cpp +++ b/source/source_estate/unittests/test_elecstate.cpp @@ -7,12 +7,16 @@ #include #endif #include "source_base/module_fft/fft_bundle.h" +#include "source_basis/module_pw/pw_basis_big.h" // use PW_Basis_Big #include "source_estate/elecstate.h" #include "source_estate/elecstate_tools.h" +#include "source_estate/electronic_control.h" +#include "source_estate/module_pot/elpot.h" #include "source_estate/occupy.h" -#include "source_basis/module_pw/pw_basis_big.h" // use PW_Basis_Big #include "source_io/module_parameter/parameter.h" +#include + #ifdef __MPI int main(int argc, char** argv) { @@ -34,9 +38,46 @@ int main(int argc, char** argv) } #endif +namespace +{ +elecstate::PotentialWindow reference_window; +int reference_calls = 0; +bool reference_available = false; +constexpr double reference_value = -0.375; +} // namespace + // Mock functions for testing elecstate.cpp namespace elecstate { +std::pair potential_window_planes( + const UnitCell &, + const ModulePW::PW_Basis &, + int, + double, + double) +{ + throw std::runtime_error("empty window in electron-state fixture"); +} + +double electrostatic_reference( + const UnitCell &, + ModulePW::PW_Basis &, + const Charge &, + const Potential &, + const surchem &, + const Input_para &, + const PotentialWindow &window) +{ + // Real grid/reference calculations have their own MPI unit and client tests. + reference_window = window; + ++reference_calls; + if (!reference_available) + { + throw std::runtime_error("electrostatic reference unavailable in electron-state fixture"); + } + return reference_value; +} + void Potential::init_pot(Charge const*) { } @@ -50,6 +91,8 @@ Potential::~Potential() { } } // namespace elecstate +surchem::surchem() {} +surchem::~surchem() {} Charge::Charge() { } @@ -153,6 +196,8 @@ constexpr int GLOBAL_NBANDS = 6; class TestParameters { public: + static Input_para &input(Parameter ¶meters) { return parameters.input; } + static void reset() { PARAM.input.nspin = 1; @@ -194,6 +239,9 @@ class ElecStateTest : public ::testing::Test { elecstate = new elecstate::ElecState; TestParameters::reset(); + reference_window = elecstate::PotentialWindow{}; + reference_calls = 0; + reference_available = false; GlobalV::KPAR = 1; GlobalV::NPROC_IN_POOL = 1; } @@ -213,6 +261,156 @@ TEST_F(ElecStateTest, InitNelecSpin) EXPECT_EQ(elecstate->nelec_spin[1], 5.0); } +TEST_F(ElecStateTest, ElectronicRequestUsesExplicitSpinState) +{ + // The fixture uses global N=10, nspin=1 and two_fermi=false. + elecstate::update_electron_count(*elecstate, 8.2, 2, 0.2, true); + ASSERT_EQ(elecstate->nelec_spin.size(), 2u); + EXPECT_NEAR(elecstate->nelec_spin[0], 4.2, 1e-14); + EXPECT_NEAR(elecstate->nelec_spin[1], 4.0, 1e-14); + EXPECT_TRUE(elecstate->eferm.two_efermi); + + elecstate::update_electron_count(*elecstate, 7.8, 2, -0.2, false); + EXPECT_NEAR(elecstate->nelec_spin[0], 3.8, 1e-14); + EXPECT_NEAR(elecstate->nelec_spin[1], 4.0, 1e-14); + EXPECT_FALSE(elecstate->eferm.two_efermi); + + elecstate::update_electron_count(*elecstate, 8.0, 2, 0.0, true); + EXPECT_DOUBLE_EQ(elecstate->nelec_spin[0], 4.0); + EXPECT_DOUBLE_EQ(elecstate->nelec_spin[1], 4.0); + EXPECT_TRUE(elecstate->eferm.two_efermi); + + // The explicit path must leave the native parameter source unchanged. + TestParameters::set_nspin(2); + elecstate->init_nelec_spin(); + EXPECT_DOUBLE_EQ(elecstate->nelec_spin[0], 5.0); + EXPECT_DOUBLE_EQ(elecstate->nelec_spin[1], 5.0); +} + +TEST_F(ElecStateTest, ElectronicStepChecksInitializationBeforeUpdatingParameters) +{ + Parameter parameters; + Input_para &input = TestParameters::input(parameters); + input.nspin = 2; + input.nupdown = 0.5; + elecstate::ElectronicStep step; + step.parameters = ¶meters; + step.control.nelect = 8.25; + step.two_fermi = true; + EXPECT_THROW(elecstate::prepare_electronic_step(ucell, elecstate, step, input), std::runtime_error); + EXPECT_DOUBLE_EQ(0.0, parameters.inp.nelec); + EXPECT_FALSE(step.request_applied); + + Charge charge; + elecstate->charge = &charge; + elecstate->pot = new elecstate::Potential; + step.window.axis = 2; + EXPECT_THROW(elecstate::prepare_electronic_step(ucell, elecstate, step, input), std::runtime_error); + ModulePW::PW_Basis basis; + charge.rhopw = &basis; + EXPECT_THROW(elecstate::prepare_electronic_step(ucell, elecstate, step, input), std::runtime_error); + EXPECT_DOUBLE_EQ(0.0, parameters.inp.nelec); + EXPECT_FALSE(step.request_applied); + EXPECT_FALSE(step.result_ready); + EXPECT_TRUE(elecstate->nelec_spin.empty()); + step.window.axis = -1; + elecstate::prepare_electronic_step(ucell, elecstate, step, input); + EXPECT_DOUBLE_EQ(8.25, parameters.inp.nelec); + EXPECT_TRUE(step.request_applied); + EXPECT_TRUE(elecstate->eferm.two_efermi); + ASSERT_EQ(2u, elecstate->nelec_spin.size()); + EXPECT_DOUBLE_EQ(4.375, elecstate->nelec_spin[0]); + EXPECT_DOUBLE_EQ(3.875, elecstate->nelec_spin[1]); + step.control.nelect = 7.75; + EXPECT_THROW(elecstate::prepare_electronic_step(ucell, elecstate, step, input), std::runtime_error); + EXPECT_DOUBLE_EQ(8.25, parameters.inp.nelec); +} + +TEST_F(ElecStateTest, ElectronicResultRequiresConvergenceAndMatchingOccupations) +{ + Charge charge; + elecstate->charge = &charge; + elecstate->pot = new elecstate::Potential; + elecstate->wg.create(1, 2); + elecstate->wg(0, 0) = 4.125; + elecstate->wg(0, 1) = 4.125; + elecstate->eferm.ef = -0.125; + ModulePW::PW_Basis basis; + basis.poolnproc = 1; + surchem solvent; + Input_para input; + input.kpar = 1; + input.bndpar = 1; + elecstate::ElectronicStep step; + step.control.nelect = 8.25; + EXPECT_THROW( + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step), std::runtime_error); + step.request_applied = true; + EXPECT_THROW( + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, false, step), std::runtime_error); + EXPECT_FALSE(step.result_ready); + elecstate->wg(0, 1) = 4.0; + EXPECT_THROW( + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step), std::runtime_error); + EXPECT_FALSE(step.result_ready); + elecstate->wg(0, 1) = 4.125; + step.window.axis = 2; + EXPECT_THROW( + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step), std::runtime_error); + EXPECT_FALSE(step.result_ready); + EXPECT_EQ(1, reference_calls); + step.window.axis = -1; + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step); + EXPECT_TRUE(step.result_ready); + EXPECT_DOUBLE_EQ(8.25, step.result.nelect); + EXPECT_DOUBLE_EQ(-0.125, step.result.fermi_ry); + EXPECT_DOUBLE_EQ(0.0, step.result.reference_ry); + EXPECT_EQ(1, reference_calls); + EXPECT_THROW( + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step), std::runtime_error); +} + +TEST_F(ElecStateTest, ElectronicResultForwardsPotentialWindow) +{ + Charge charge; + elecstate->charge = &charge; + elecstate->pot = new elecstate::Potential; + elecstate->wg.create(1, 1); + elecstate->wg(0, 0) = 8.25; + elecstate->eferm.ef = -0.125; + ModulePW::PW_Basis basis; + basis.poolnproc = 1; + surchem solvent; + Input_para input; + input.kpar = 1; + input.bndpar = 1; + reference_available = true; + + for (int axis = 0; axis < 3; ++axis) + { + elecstate::ElectronicStep step; + step.control.nelect = 8.25; + step.request_applied = true; + step.window.axis = axis; + step.window.minimum_A = 3.5 + axis; + step.window.maximum_A = 6.25 + axis; + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step); + + EXPECT_EQ(axis + 1, reference_calls); + EXPECT_EQ(axis, reference_window.axis); + EXPECT_DOUBLE_EQ(step.window.minimum_A, reference_window.minimum_A); + EXPECT_DOUBLE_EQ(step.window.maximum_A, reference_window.maximum_A); + EXPECT_TRUE(step.result_ready); + EXPECT_DOUBLE_EQ(reference_value, step.result.reference_ry); + EXPECT_DOUBLE_EQ(8.25, step.result.nelect); + EXPECT_DOUBLE_EQ(-0.125, step.result.fermi_ry); + EXPECT_THROW( + elecstate::complete_electronic_step(ucell, elecstate, &basis, solvent, input, true, step), + std::runtime_error); + EXPECT_EQ(axis + 1, reference_calls); + } +} + TEST_F(ElecStateTest, Constructor) { Charge* charge = new Charge; diff --git a/source/source_estate/unittests/test_electronic_occupations.cpp b/source/source_estate/unittests/test_electronic_occupations.cpp new file mode 100644 index 0000000000..338624a5c9 --- /dev/null +++ b/source/source_estate/unittests/test_electronic_occupations.cpp @@ -0,0 +1,206 @@ +#include "../electronic_occupations.h" +#include "source_base/matrix.h" +#include "source_base/parallel_global.h" + +#include "gtest/gtest.h" + +#include +#include + +namespace +{ +int process_count = 1; +int process_rank = 0; + +ModuleBase::matrix fractional_weights() +{ + ModuleBase::matrix weights(2, 3); + weights(0, 0) = 2.0; + weights(0, 1) = 2.0; + weights(0, 2) = 2.0; + weights(1, 0) = 2.0; + weights(1, 1) = 0.2; + return weights; +} + +TEST(ElectronicOccupations, FractionalPopulationIncludesEveryLocalRowAndBand) +{ + // Every rank holds the same single-pool population; count its replicas only once. + const ModuleBase::matrix weights = fractional_weights(); + EXPECT_NEAR(8.2, elecstate::checked_occupation_electron_count(weights, 8.2, 1, process_count), 1e-14); +} + +TEST(ElectronicOccupations, ReturnsOccupationSumInsteadOfEchoingNearbyRequest) +{ + const ModuleBase::matrix weights = fractional_weights(); + const double requested = 8.2 + 5e-9; + const double actual = elecstate::checked_occupation_electron_count(weights, requested, 1, process_count); + EXPECT_NEAR(8.2, actual, 1e-14); + EXPECT_GT(requested - actual, 4e-9); +} + +TEST(ElectronicOccupations, RejectsPopulationMismatchOnEitherSide) +{ + const ModuleBase::matrix weights = fractional_weights(); + EXPECT_THROW( + elecstate::checked_occupation_electron_count(weights, 8.2 + 2e-8, 1, process_count), std::runtime_error); + EXPECT_THROW( + elecstate::checked_occupation_electron_count(weights, 8.2 - 2e-8, 1, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, ToleranceIsAbsoluteEvenForLargeElectronCounts) +{ + ModuleBase::matrix weights(1, 1); + weights(0, 0) = 1e6; + EXPECT_THROW( + elecstate::checked_occupation_electron_count(weights, 1e6 + 1e-6, 1, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, GeneralizedSmearingCanContainNegativeWeights) +{ + ModuleBase::matrix weights(1, 3); + weights(0, 0) = 2.125; + weights(0, 1) = -0.25; + weights(0, 2) = 0.125; + EXPECT_DOUBLE_EQ(2.0, elecstate::checked_occupation_electron_count(weights, 2.0, 1, process_count)); +} + +TEST(ElectronicOccupations, RejectsNaNOnLastRankTogether) +{ + ModuleBase::matrix weights = fractional_weights(); + if (process_rank == process_count - 1) + { + weights(1, 2) = std::numeric_limits::quiet_NaN(); + } + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, 1, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, RejectsInfinityOnLastRankTogether) +{ + ModuleBase::matrix weights = fractional_weights(); + if (process_rank == process_count - 1) + { + weights(1, 2) = std::numeric_limits::infinity(); + } + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, 1, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, RejectsLocalOverflowBeforePoolReduction) +{ + ModuleBase::matrix weights(1, 2); + weights(0, 0) = std::numeric_limits::max(); + weights(0, 1) = std::numeric_limits::max(); + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, process_count, 1), std::runtime_error); +} + +TEST(ElectronicOccupations, RejectsInvalidRequestOnLastRankTogether) +{ + const ModuleBase::matrix weights = fractional_weights(); + const double requested = process_rank == process_count - 1 ? std::numeric_limits::quiet_NaN() : 8.2; + EXPECT_THROW( + elecstate::checked_occupation_electron_count(weights, requested, 1, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, RejectsInvalidPartitionOnLastRankTogether) +{ + const ModuleBase::matrix weights = fractional_weights(); + const int local_size = process_rank == process_count - 1 ? 0 : process_count; + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, 1, local_size), std::runtime_error); + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, 0, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, SinglePoolMismatchOnOneReplicaFailsEveryRank) +{ + ModuleBase::matrix weights = fractional_weights(); + if (process_rank == process_count - 1) + { + weights(1, 1) += 0.125; + } + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, 1, process_count), std::runtime_error); +} + +TEST(ElectronicOccupations, KPointPoolsCombineDistinctRowsAndRemovePoolReplicas) +{ + const int pools = process_count % 2 == 0 ? 2 : 1; + const int ranks_per_pool = process_count / pools; + const int pool = process_rank / ranks_per_pool; + ModuleBase::matrix weights(1, 2); + const double population = pools == 1 ? 8.2 : (pool == 0 ? 2.2 : 6.0); + weights(0, 0) = 0.25 * population; + weights(0, 1) = 0.75 * population; + EXPECT_NEAR(8.2, elecstate::checked_occupation_electron_count(weights, 8.2, pools, ranks_per_pool), 1e-14); +} + +TEST(ElectronicOccupations, BandShardsUseLocalColumnCount) +{ + // Independent band shards are reduction groups, just like native BNDPAR. + const int local_bands = process_rank + 1; + ModuleBase::matrix weights(2, local_bands); + const double total_bands = process_count * (process_count + 1) / 2.0; + for (int band = 0; band < local_bands; ++band) + { + weights(0, band) = 3.0 / total_bands; + weights(1, band) = 5.2 / total_bands; + } + EXPECT_NEAR(8.2, elecstate::checked_occupation_electron_count(weights, 8.2, process_count, 1), 1e-14); +} + +TEST(ElectronicOccupations, EmptyLocalBlocksStillParticipateInCollectives) +{ + ModuleBase::matrix weights; + if (process_rank == 0) + { + weights = fractional_weights(); + } + EXPECT_NEAR(8.2, elecstate::checked_occupation_electron_count(weights, 8.2, process_count, 1), 1e-14); +} + +TEST(ElectronicOccupations, EmptyPopulationCannotSatisfyPositiveRequest) +{ + const ModuleBase::matrix weights; + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, process_count, 1), std::runtime_error); +} + +TEST(ElectronicOccupations, UnequalPoolSizesRemoveTheirOwnReplicaCounts) +{ + // One rank in the first pool and all remaining ranks in the second. + const int pools = process_count > 1 ? 2 : 1; + const int ranks_per_pool = process_rank == 0 ? 1 : process_count - 1; + ModuleBase::matrix weights(1, 1); + weights(0, 0) = pools == 1 ? 8.2 : (process_rank == 0 ? 2.2 : 6.0); + EXPECT_NEAR(8.2, elecstate::checked_occupation_electron_count(weights, 8.2, pools, ranks_per_pool), 1e-14); +} + +TEST(ElectronicOccupations, RemoteInvalidEntryCannotBeHiddenByAnEmptyRootBlock) +{ + ModuleBase::matrix weights; + if (process_rank == process_count - 1) + { + weights.create(1, 1); + weights(0, 0) = -std::numeric_limits::infinity(); + } + EXPECT_THROW(elecstate::checked_occupation_electron_count(weights, 8.2, process_count, 1), std::runtime_error); +} +} // namespace + +int main(int argc, char **argv) +{ + int thread_count = 1; + Parallel_Global::read_pal_param(argc, argv, process_count, thread_count, process_rank); +#ifdef __MPI + // Follow source_base/test/mpi_test_main.cpp: no pool communicators are + // created by these tests, so native finalization must not free them. + POOL_WORLD = MPI_COMM_NULL; + KP_WORLD = MPI_COMM_NULL; + INT_BGROUP = MPI_COMM_NULL; + BP_WORLD = MPI_COMM_NULL; + GRID_WORLD = MPI_COMM_NULL; + DIAG_WORLD = MPI_COMM_NULL; +#endif + testing::InitGoogleTest(&argc, argv); + const int result = RUN_ALL_TESTS(); +#ifdef __MPI + Parallel_Global::finalize_mpi(); +#endif + return result; +} diff --git a/source/source_estate/unittests/test_elpot.cpp b/source/source_estate/unittests/test_elpot.cpp new file mode 100644 index 0000000000..f0659fe20d --- /dev/null +++ b/source/source_estate/unittests/test_elpot.cpp @@ -0,0 +1,266 @@ +#include "source_base/parallel_global.h" +#include "source_estate/module_pot/efield.h" +#include "source_estate/module_pot/elpot.h" +#include "source_estate/module_pot/h_hartree_pw.h" +#include "source_estate/module_pot/potential_new.h" +#include "source_io/module_parameter/input_parameter.h" + +#include +#include +#include +#include + +// Only the public cell/grid storage is needed by the averaging function. +UnitCell::UnitCell() {} +UnitCell::~UnitCell() {} +Magnetism::Magnetism() {} +Magnetism::~Magnetism() {} +SepPot::SepPot() {} +SepPot::~SepPot() {} +Sep_Cell::Sep_Cell() noexcept {} +Sep_Cell::~Sep_Cell() noexcept {} +Charge::Charge() {} +Charge::~Charge() {} +surchem::surchem() {} +surchem::~surchem() {} + +// A constant Hartree term isolates the assembly of the local potentials. +// The averaging tests supply their grid directly. +ModuleBase::matrix elecstate::H_Hartree_pw::v_hartree( + const UnitCell &, + ModulePW::PW_Basis *basis, + const int &nspin, + const double *const *const) +{ + ModuleBase::matrix hartree(nspin, basis->nrxx); + for (int ir = 0; ir < basis->nrxx; ++ir) + { + hartree(0, ir) = 2.0; + } + return hartree; +} +ModuleBase::matrix elecstate::Efield::add_efield( + const UnitCell &, + const ModulePW::PW_Basis *, + const int &, + const double *const *const, + const surchem &) +{ + throw std::logic_error("unexpected dipole construction in averaging test"); +} + +const std::vector *elecstate::Potential::pcc_electron_potential() const +{ + throw std::logic_error("unexpected PCC construction in averaging test"); +} + +const std::vector *elecstate::Potential::find_sol_pot() const +{ + throw std::logic_error("unexpected solvation construction in averaging test"); +} + +namespace +{ +int process_count = 1; +int process_rank = 0; + +class ElectrostaticPotentialTest : public testing::Test +{ + protected: + void set_grid(int planes) + { + cell.lat0_angstrom = 4.0; + const double z_length = planes / 4.0; + cell.latvec = ModuleBase::Matrix3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, z_length); + basis.nx = 4; + basis.ny = 4; + basis.nz = planes; + const int remainder = planes % process_count; + const int extra = process_rank < remainder ? 1 : 0; + basis.nplane = planes / process_count + extra; + basis.startz_current = process_rank * (planes / process_count) + std::min(process_rank, remainder); + basis.nrxx = basis.nx * basis.ny * basis.nplane; +#ifdef __MPI + basis.pool_world = MPI_COMM_WORLD; +#endif + potential.clear(); + for (int x = 0; x < basis.nx; ++x) + { + for (int y = 0; y < basis.ny; ++y) + { + for (int z = basis.startz_current; z < basis.startz_current + basis.nplane; ++z) + { + const double value = 100.0 * x + 10.0 * y + z; + potential.push_back(value); + } + } + } + } + + void expect_average( + int axis, + double lower, + double upper, + double expected) + { + const double actual = elecstate::planar_potential_average(cell, basis, potential, axis, lower, upper); + EXPECT_NEAR(actual, expected, 1.0e-12); + } + + UnitCell cell; + ModulePW::PW_Basis basis; + std::vector potential; +}; + +TEST_F(ElectrostaticPotentialTest, SccsAndPccAreAddedOnce) +{ + set_grid(5); + Input_para input; + input.nspin = 1; + input.imp_sol = 2; + Charge charge; + surchem solvent; + const std::vector fixed(basis.nrxx, 3.0); + const std::vector pcc(basis.nrxx, 0.25); + const std::vector sccs(basis.nrxx, 0.5); + // SCCS does not initialize the legacy delta_phi array. + ASSERT_EQ(solvent.delta_phi, nullptr); + const std::vector result = + elecstate::electrostatic_potential(cell, basis, charge, fixed.data(), solvent, input, &pcc, &sccs); + ASSERT_EQ(result.size(), static_cast(basis.nrxx)); + for (const double value : result) + { + EXPECT_DOUBLE_EQ(value, 5.75); + } +} + +TEST_F(ElectrostaticPotentialTest, LegacySolventAndVacuumRemainUnchanged) +{ + set_grid(5); + Input_para input; + input.nspin = 1; + Charge charge; + surchem solvent; + const std::vector fixed(basis.nrxx, 3.0); + std::vector delta_phi(basis.nrxx, 0.75); + solvent.delta_phi = delta_phi.data(); + for (int model = 0; model <= 1; ++model) + { + input.imp_sol = model; + const std::vector result = + elecstate::electrostatic_potential(cell, basis, charge, fixed.data(), solvent, input, nullptr, nullptr); + const double expected = model == 0 ? 5.0 : 5.75; + for (const double value : result) + { + EXPECT_DOUBLE_EQ(value, expected); + } + } +} + +TEST_F(ElectrostaticPotentialTest, SolventGridMismatchIsRejected) +{ + set_grid(5); + Input_para input; + input.nspin = 1; + input.imp_sol = 2; + Charge charge; + surchem solvent; + const std::vector fixed(basis.nrxx, 3.0); + const std::vector wrong_grid(basis.nrxx + 1, 0.5); + EXPECT_THROW( + elecstate::electrostatic_potential(cell, basis, charge, fixed.data(), solvent, input, nullptr, &wrong_grid), + std::runtime_error); +} + +TEST_F(ElectrostaticPotentialTest, HalfOpenWindowsOnAllAxes) +{ + set_grid(5); + // V = 100*x + 10*y + z; unrestricted means are x=y=1.5, z=2. + expect_average(0, 1.0, 2.0, 117.0); + expect_average(1, 1.0, 2.0, 162.0); + expect_average(2, 1.0, 3.0, 166.5); +} + +TEST_F(ElectrostaticPotentialTest, WindowPreflightMatchesCubePointsAtAdjacentDoubles) +{ + set_grid(5); + const double below_one = std::nextafter(1.0, 0.0); + const double above_one = std::nextafter(1.0, 2.0); + for (int axis = 0; axis < 3; ++axis) + { + EXPECT_THROW(elecstate::potential_window_planes(cell, basis, axis, below_one, 1.0), std::runtime_error); + const std::pair planes = elecstate::potential_window_planes(cell, basis, axis, 1.0, above_one); + EXPECT_EQ(1, planes.first); + EXPECT_EQ(2, planes.second); + } + expect_average(2, 1.0, above_one, 166.0); + EXPECT_THROW(elecstate::checked_window_height(cell, 2, 20.0, 30.0), std::runtime_error); +} + +TEST_F(ElectrostaticPotentialTest, UnequalPartitionsUsePointCounts) +{ + set_grid(5); + // Four ranks hold 2/1/1/1 planes; averaging rank means would be wrong. + expect_average(2, 0.0, 5.0, 167.0); +} + +TEST_F(ElectrostaticPotentialTest, EmptyGlobalWindowFailsOnEveryRank) +{ + set_grid(5); + EXPECT_THROW(elecstate::planar_potential_average(cell, basis, potential, 2, 0.1, 0.2), std::runtime_error); +} + +TEST_F(ElectrostaticPotentialTest, EmptyLocalPlanesContributeZero) +{ + set_grid(2); + // With four ranks, two ranks own no planes. + if (process_rank >= 2) + { + EXPECT_EQ(basis.nplane, 0); + EXPECT_TRUE(potential.empty()); + } + expect_average(2, 0.0, 2.0, 165.5); +} + +TEST_F(ElectrostaticPotentialTest, RanksOutsideWindowStillParticipate) +{ + set_grid(5); + expect_average(2, 4.0, 5.0, 169.0); +} + +TEST_F(ElectrostaticPotentialTest, TriclinicWindowsUseNormalHeights) +{ + set_grid(5); + cell.latvec = ModuleBase::Matrix3(1.0, 0.0, 0.0, 0.75, 1.0, 0.0, 0.75, 0.75, 1.0); + // For this cell the normal heights are 64/sqrt(409), 3.2, and 4 A. + const double heights[3] = {64.0 / std::sqrt(409.0), 3.2, 4.0}; + const double centers[3] = {0.25, 0.25, 0.2}; + const double expected[3] = {117.0, 162.0, 166.0}; + for (int axis = 0; axis < 3; ++axis) + { + const double lower = (centers[axis] - 0.01) * heights[axis]; + const double upper = (centers[axis] + 0.01) * heights[axis]; + expect_average(axis, lower, upper, expected[axis]); + } +} +} // namespace + +int main(int argc, char **argv) +{ + int thread_count = 1; + Parallel_Global::read_pal_param(argc, argv, process_count, thread_count, process_rank); +#ifdef __MPI + POOL_WORLD = MPI_COMM_NULL; + KP_WORLD = MPI_COMM_NULL; + INT_BGROUP = MPI_COMM_NULL; + BP_WORLD = MPI_COMM_NULL; + GRID_WORLD = MPI_COMM_NULL; + DIAG_WORLD = MPI_COMM_NULL; +#endif + testing::InitGoogleTest(&argc, argv); + const int result = RUN_ALL_TESTS(); +#ifdef __MPI + Parallel_Global::finalize_mpi(); +#endif + return result; +} diff --git a/source/source_estate/write_elecstat_pot.cpp b/source/source_estate/write_elecstat_pot.cpp index dc0d968359..b87ae70cb3 100644 --- a/source/source_estate/write_elecstat_pot.cpp +++ b/source/source_estate/write_elecstat_pot.cpp @@ -1,11 +1,13 @@ +#include "write_elecstat_pot.h" #include "source_base/element_name.h" #include "source_base/timer.h" -#include "source_io/module_parameter/parameter.h" -#include "source_estate/module_pot/h_hartree_pw.h" -#include "source_estate/module_pot/efield.h" +#include "source_base/tool_quit.h" +#include "source_estate/module_pot/elpot.h" #include "source_io/module_output/cube_io.h" #include "source_io/module_output/output_log.h" -#include "write_elecstat_pot.h" +#include "source_io/module_parameter/parameter.h" + +#include namespace ModuleIO { @@ -31,62 +33,15 @@ void write_elecstat_pot( ModuleBase::TITLE("ModuleIO", "write_elecstat_pot"); ModuleBase::timer::start("ModuleIO", "write_elecstat_pot"); - std::vector v_elecstat(rho_basis->nrxx, 0.0); - - if (solvent_potential != nullptr && solvent_potential->size() != static_cast(rho_basis->nrxx)) + std::vector v_elecstat; + try { - ModuleBase::WARNING_QUIT("write_elecstat_pot", "Solvent potential does not match the output grid"); + v_elecstat = elecstate::electrostatic_potential( + *ucell, *rho_basis, *chr, v_eff, solvent, PARAM.inp, pcc_potential, solvent_potential); } - - const int nspin = PARAM.inp.nspin; - const int efield = PARAM.inp.efield_flag; - const int dip_corr = PARAM.inp.dip_cor_flag; - const int imp_sol = PARAM.inp.imp_sol; - - //========================================== - // Hartree potential - //========================================== - ModuleBase::matrix vh(nspin, rho_basis->nrxx); - vh = elecstate::H_Hartree_pw::v_hartree(*ucell, rho_basis, nspin, chr->rho); - - //========================================== - //! Dipole correction - //========================================== - ModuleBase::matrix v_efield; - if (efield>0 && dip_corr>0) - { - v_efield.create(nspin, rho_basis->nrxx); - v_efield = elecstate::Efield::add_efield(*ucell, - const_cast(rho_basis), - nspin, - chr->rho, - solvent); - } - - //========================================== - //! Add hartree potential and local pseudopot - //========================================== - for (int ir = 0; ir < rho_basis->nrxx; ir++) + catch (const std::exception &error) { - // the spin index is 0 - v_elecstat[ir] = vh(0, ir) + v_eff[ir]; - - if (efield>0 && dip_corr>0) - { - v_elecstat[ir] += v_efield(0, ir); - } - if (pcc_potential != nullptr) - { - v_elecstat[ir] += (*pcc_potential)[ir]; - } - if (solvent_potential != nullptr) - { - v_elecstat[ir] += (*solvent_potential)[ir]; - } - if (imp_sol == 1) - { - v_elecstat[ir] += solvent.delta_phi[ir]; - } + ModuleBase::WARNING_QUIT("write_elecstat_pot", error.what()); } //------------------------------------------- @@ -111,21 +66,9 @@ void write_elecstat_pot( double ef_tmp = 0.0; int out_fermi = 0; - ModuleIO::write_vdata_palgrid(*chr->pgrid, - v_elecstat.data(), - is, - nspin, - istep, - fn, - ef_tmp, - ucell, - precision, - out_fermi, - PARAM.globalv.two_fermi, - false, - append, - ofs_running, - "electrostatic potential"); + ModuleIO::write_vdata_palgrid( + *chr->pgrid, v_elecstat.data(), is, PARAM.inp.nspin, istep, fn, ef_tmp, ucell, precision, out_fermi, + PARAM.globalv.two_fermi, false, append, ofs_running, "electrostatic potential"); ModuleBase::timer::end("ModuleIO", "write_elecstat_pot"); return; diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index 788da1db04..af8519b976 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -222,7 +222,9 @@ void ReadInput::item_system() When using the ASE AbacusSocketIO interface, this environment variable is set automatically from the port or unixsocket calculator argument.)"; item.description += R"( -Socket mode always computes energy. Force and stress extraction follows cal_force and cal_stress independently; disabled properties are sent as protocol padding and marked absent in the ABACUS i-PI extras metadata, not reported as physical zero values. This metadata extension is required for safe optional-property handling: a legacy response with empty extras is accepted only for energy-only use, while a generic client that ignores extras cannot distinguish padding from a computed zero. A non-converged SCF step is returned with scf_converged=false metadata so an external driver can choose its policy.)"; +Socket mode always computes energy. Force and stress extraction follows cal_force and cal_stress independently; disabled properties are sent as protocol padding and marked absent in the ABACUS i-PI extras metadata, not reported as physical zero values. This metadata extension is required for safe optional-property handling: a legacy response with empty extras is accepted only for energy-only use, while a generic client that ignores extras cannot distinguish padding from a computed zero. A non-converged ordinary SCF step is returned with scf_converged=false metadata so an external driver can choose its policy. + +Constant-potential i-PI sessions use INIT electron metadata and CHGDATA before each POSDATA to set the total electron number. Use fixed-cell CPU double-precision norm-conserving PW/LCAO KSDFT with cal_force=1, cal_stress=0, symmetry=0 or -1, and nspin=1 or 2. CHGDATA flags are zero. Constant-potential electron control is incompatible with the energy-only Makov-Payne correction (assume_isolated=makov-payne). Each response contains the converged energy and forces, actual electron count, Fermi level, and requested work function. Set electron-control options in the i-PI electrons block. See the [i-PI examples and tests](https://github.com/zhangchenyu-USTC/i-pi_constant-potential/tree/abacus-develop-validation/examples/clients/abacus/validation).)"; item.default_value = "False"; read_sync_bool(input.socket_driver); item.check_value = [](const Input_Item& item, const Parameter& para) { diff --git a/source/source_lcao/module_ri/exx_lri_interface.cpp b/source/source_lcao/module_ri/exx_lri_interface.cpp index 43b1991bb9..6ef810918d 100644 --- a/source/source_lcao/module_ri/exx_lri_interface.cpp +++ b/source/source_lcao/module_ri/exx_lri_interface.cpp @@ -517,7 +517,14 @@ bool Exx_LRI_Interface::exx_after_converge( { // has separate_loop case const double ediff = std::abs(etot - etot_last_outer_loop) * ModuleBase::Ry_to_eV; if (two_level_step) - { std::cout << FmtCore::format(" deltaE (eV) from outer loop: %.8e \n", ediff); } + { + std::cout << FmtCore::format(" deltaE (eV) from outer loop: %.8e \n", ediff); + } + const bool outer_converged = this->two_level_step != 0 && (iter == 1 || ediff < scf_ene_thr); + if (strict_electronic_step_ && this->two_level_step >= this->hybrid_step_ && !outer_converged) + { + throw std::runtime_error("constant-potential EXX outer loop did not converge; increase exx_hybrid_step"); + } // exx converged or get max exx steps if (this->two_level_step == this->hybrid_step_ || (iter == 1 && this->two_level_step != 0) // density convergence of outer loop diff --git a/source/source_lcao/module_ri/exx_lri_interface.h b/source/source_lcao/module_ri/exx_lri_interface.h index bc81e475d2..65d7060306 100644 --- a/source/source_lcao/module_ri/exx_lri_interface.h +++ b/source/source_lcao/module_ri/exx_lri_interface.h @@ -110,6 +110,8 @@ class Exx_LRI_Interface const bool update_symmetry, const bool use_gpu); + void begin_electronic_step(bool active) { strict_electronic_step_ = active; } + /// @brief in eachiterinit: do DM mixing and calculate Hexx when entering 2nd SCF void exx_eachiterinit(const int istep, const UnitCell& ucell, @@ -161,40 +163,50 @@ class Exx_LRI_Interface std::shared_ptr> exx_ptr; private: - - Mix_DMk_2D mix_DMk_2D; - Mix_DMk_2D> mix_common_density_; - RI_2D_Comm::HybridDensityLayout common_density_layout_; - - std::vector>>> prepare_exx_density( - const std::vector>& dmk, const UnitCell& ucell, - const K_Vectors& kv, const Parallel_Orbitals& pv, const int nspin, - const bool restart, const ModuleBase::Vector3* source_A); - void mix_common_density(RI_2D_Comm::HybridGaugeComplexDensity& density, - const UnitCell& ucell, const ModuleBase::Vector3& source_A, const bool restart); - void mix_common_density(std::vector>>>& density, - const UnitCell& ucell, const ModuleBase::Vector3& source_A, const bool restart); - - Exx_Info_Global info_global; - size_t hybrid_step_ = 1; - // non-owning ptr to Charge_Mixing captured in exx_beforescf, used to refresh the - // borrowed mixing pointer in exx_eachiterinit (mixing_restart reallocates it via init_mixing) - const Charge_Mixing* p_chgmix_ = nullptr; - // identity of the last borrowed mixing engine; a change means init_mixing() reallocated it - // (mixing_restart fired), so the DM mixer must also restart to keep engine+history consistent - const void* last_borrowed_mixing_ = nullptr; - - bool exx_spacegroup_symmetry = false; - ModuleSymmetry::Symmetry_rotation symrot_; - - struct Flag_Finish - { - bool init = false; - bool ions = false; - bool elec = false; - bool force = false; - bool stress = false; - }; + bool strict_electronic_step_ = false; + Mix_DMk_2D mix_DMk_2D; + Mix_DMk_2D> mix_common_density_; + RI_2D_Comm::HybridDensityLayout common_density_layout_; + + std::vector>>> prepare_exx_density( + const std::vector> &dmk, + const UnitCell &ucell, + const K_Vectors &kv, + const Parallel_Orbitals &pv, + const int nspin, + const bool restart, + const ModuleBase::Vector3 *source_A); + void mix_common_density( + RI_2D_Comm::HybridGaugeComplexDensity &density, + const UnitCell &ucell, + const ModuleBase::Vector3 &source_A, + const bool restart); + void mix_common_density( + std::vector>>> &density, + const UnitCell &ucell, + const ModuleBase::Vector3 &source_A, + const bool restart); + + Exx_Info_Global info_global; + size_t hybrid_step_ = 1; + // non-owning ptr to Charge_Mixing captured in exx_beforescf, used to refresh the + // borrowed mixing pointer in exx_eachiterinit (mixing_restart reallocates it via init_mixing) + const Charge_Mixing *p_chgmix_ = nullptr; + // identity of the last borrowed mixing engine; a change means init_mixing() reallocated it + // (mixing_restart fired), so the DM mixer must also restart to keep engine+history consistent + const void *last_borrowed_mixing_ = nullptr; + + bool exx_spacegroup_symmetry = false; + ModuleSymmetry::Symmetry_rotation symrot_; + + struct Flag_Finish + { + bool init = false; + bool ions = false; + bool elec = false; + bool force = false; + bool stress = false; + }; Flag_Finish flag_finish; }; diff --git a/source/source_pw/module_pwdft/exx_helper.cpp b/source/source_pw/module_pwdft/exx_helper.cpp index 79d102becd..74b7f2ce3a 100644 --- a/source/source_pw/module_pwdft/exx_helper.cpp +++ b/source/source_pw/module_pwdft/exx_helper.cpp @@ -1,12 +1,25 @@ #include "exx_helper.h" -#include "source_io/module_parameter/parameter.h" +#include "source_estate/elecstate_pw.h" // use ElecStatePW +#include "source_estate/module_charge/charge.h" // use Charge +#include "source_estate/update_pot.h" // use elecstate::update_pot #include "source_hamilt/module_xc/general_exx_info.h" // for General_Exx_Info type -#include "source_hamilt/module_xc/xc_functional.h" // use XC_Functional +#include "source_hamilt/module_xc/xc_functional.h" // use XC_Functional +#include "source_io/module_parameter/parameter.h" #include "source_pw/module_pwdft/hamilt_pw.h" // use HamiltPW -#include "source_estate/update_pot.h" // use elecstate::update_pot -#include "source_estate/elecstate_pw.h" // use ElecStatePW -#include "source_estate/module_charge/charge.h" // use Charge -#include // for timing +#include // for timing +#include + +void validate_electronic_step_exx(int functional_type, bool cal_exx) +{ + // Separate-loop SCAN0 starts as SCAN, before switching to hybrid meta-GGA. + // The upstream PW density path updates tau only for non-hybrid meta-GGA. + if (functional_type == 5 || (functional_type == 3 && cal_exx)) + { + throw std::runtime_error( + "constant-potential PW hybrid meta-GGA is unsupported: " + "upstream kinetic-energy-density updates do not handle hybrid functionals"); + } +} template void Exx_Helper::init(const UnitCell& ucell, const Input_para& inp, const ModuleBase::matrix& wg, const General_Exx_Info& exx_info) @@ -32,7 +45,21 @@ void Exx_Helper::init(const UnitCell& ucell, const Input_para& inp, c } template -void Exx_Helper::before_scf(void* p_hamilt, void* psi, const Input_para& inp, const General_Exx_Info& exx_info) +void Exx_Helper::begin_electronic_step(bool active) +{ + strict_electronic_step = active; + if (active) + { + exx_iter = 0; + } +} + +template +void Exx_Helper::before_scf( + void *p_hamilt, + void *psi, + const Input_para &inp, + const General_Exx_Info &exx_info) { /// Return if not a valid calculation type if (inp.calculation != "scf" && inp.calculation != "relax" @@ -90,7 +117,7 @@ bool Exx_Helper::iter_finish(void* p_elec, Charge* p_charge, void* ps } bool conv_ene = std::abs(dexx) < inp.exx_ene_thr; - conv_esolver = this->exx_after_converge(iter, conv_ene); + conv_esolver = this->exx_after_converge(iter, conv_ene, inp); if (!conv_esolver) { @@ -130,9 +157,24 @@ double Exx_Helper::cal_exx_energy(void* psi_) } template -bool Exx_Helper::exx_after_converge(int iter, bool ene_conv) +bool Exx_Helper::exx_after_converge(int iter, bool ene_conv, const Input_para &inp) { - if (op_exx->first_iter) + if (strict_electronic_step && op_exx->separate_loop) + { + // A changed electron number must complete at least one EXX update. + // Reaching the outer-loop budget is not a convergence criterion. + const bool outer_converged = exx_iter > 0 && ((inp.exx_thr_type == "energy" && ene_conv) || + (inp.exx_thr_type == "density" && iter == 1)); + if (outer_converged) + { + return true; + } + if (exx_iter >= inp.exx_hybrid_step) + { + throw std::runtime_error("constant-potential EXX outer loop did not converge; increase exx_hybrid_step"); + } + } + else if (op_exx->first_iter) { op_exx->first_iter = false; } @@ -140,15 +182,15 @@ bool Exx_Helper::exx_after_converge(int iter, bool ene_conv) { return true; } - else if (PARAM.inp.exx_thr_type == "energy" && ene_conv) + else if (inp.exx_thr_type == "energy" && ene_conv) { return true; } - else if (PARAM.inp.exx_thr_type == "density" && iter == 1) + else if (inp.exx_thr_type == "density" && iter == 1) { return true; } - else if (exx_iter >= PARAM.inp.exx_hybrid_step) + else if (exx_iter >= inp.exx_hybrid_step) { GlobalV::ofs_running << " !!EXX IS NOT CONVERGED!!" << std::endl; std::cout << " !!EXX IS NOT CONVERGED!!" << std::endl; @@ -188,4 +230,3 @@ template class Exx_Helper, base_device::DEVICE_CPU>; template class Exx_Helper, base_device::DEVICE_GPU>; template class Exx_Helper, base_device::DEVICE_GPU>; #endif - diff --git a/source/source_pw/module_pwdft/exx_helper.h b/source/source_pw/module_pwdft/exx_helper.h index 31b25eeead..27b2d9b1f9 100644 --- a/source/source_pw/module_pwdft/exx_helper.h +++ b/source/source_pw/module_pwdft/exx_helper.h @@ -22,7 +22,12 @@ struct Exx_Helper : public Exx_HelperBase void init(const UnitCell& ucell, const Input_para& inp, const ModuleBase::matrix& wg, const General_Exx_Info& exx_info) override; - void before_scf(void* p_hamilt, void* psi, const Input_para& inp, const General_Exx_Info& exx_info) override; + void begin_electronic_step(bool active) override; + void before_scf( + void *p_hamilt, + void *psi, + const Input_para &inp, + const General_Exx_Info &exx_info) override; bool iter_finish(void* p_elec, Charge* p_charge, void* psi, UnitCell& ucell, const Input_para& inp, @@ -36,11 +41,12 @@ struct Exx_Helper : public Exx_HelperBase void set_op() override { op_exx->first_iter = first_iter; - set_psi(psi); + // A warm start constructs ACE in set_psi and reads the current occupations. op_exx->set_wg(wg); + set_psi(psi); } - bool exx_after_converge(int iter, bool ene_conv) override; + bool exx_after_converge(int iter, bool ene_conv, const Input_para &inp) override; double cal_exx_energy(void* psi_) override; @@ -53,6 +59,6 @@ struct Exx_Helper : public Exx_HelperBase psi::Psi *psi = nullptr; const ModuleBase::matrix *wg = nullptr; int exx_iter = 0; - + bool strict_electronic_step = false; }; #endif // EXX_HELPER_H diff --git a/source/source_pw/module_pwdft/exx_helper_base.h b/source/source_pw/module_pwdft/exx_helper_base.h index 12bd8d7aee..9f62d650ec 100644 --- a/source/source_pw/module_pwdft/exx_helper_base.h +++ b/source/source_pw/module_pwdft/exx_helper_base.h @@ -8,6 +8,8 @@ class UnitCell; struct Input_para; struct General_Exx_Info; +void validate_electronic_step_exx(int functional_type, bool cal_exx); + class Exx_HelperBase { public: @@ -16,7 +18,12 @@ class Exx_HelperBase virtual void init(const UnitCell& ucell, const Input_para& inp, const ModuleBase::matrix& wg, const General_Exx_Info& exx_info) = 0; - virtual void before_scf(void* p_hamilt, void* psi, const Input_para& inp, const General_Exx_Info& exx_info) = 0; + virtual void begin_electronic_step(bool active) = 0; + virtual void before_scf( + void *p_hamilt, + void *psi, + const Input_para &inp, + const General_Exx_Info &exx_info) = 0; virtual bool iter_finish(void* p_elec, Charge* p_charge, void* psi, UnitCell& ucell, const Input_para& inp, @@ -35,7 +42,7 @@ class Exx_HelperBase /// value (false = not converged, rerun SCF) and the caller /// (ESolver_KS_PW) sets ESolver_KS::scf_rerun_ to trigger the /// restart at iter=1 in ESolver_KS::runner. - virtual bool exx_after_converge(int iter, bool ene_conv) = 0; + virtual bool exx_after_converge(int iter, bool ene_conv, const Input_para &inp) = 0; virtual double cal_exx_energy(void* psi) = 0; diff --git a/source/source_relax/CMakeLists.txt b/source/source_relax/CMakeLists.txt index 8dc901592f..211f677171 100644 --- a/source/source_relax/CMakeLists.txt +++ b/source/source_relax/CMakeLists.txt @@ -6,7 +6,9 @@ add_library( socket_frame.cpp socket_utils.cpp socket_handlers.cpp + socket_constant_potential.cpp socket_driver.cpp + socket_ks.cpp cg_base.cpp relax_driver.cpp relax_stru_io.cpp diff --git a/source/source_relax/relax_driver.cpp b/source/source_relax/relax_driver.cpp index 97e0078b8d..22800b55bd 100644 --- a/source/source_relax/relax_driver.cpp +++ b/source/source_relax/relax_driver.cpp @@ -30,8 +30,11 @@ void Relax_Driver::relax_driver( if (inp.socket_driver) { Socket_Driver socket_driver; - socket_driver.socket_driver(p_esolver, ucell, inp, ofs_running); - p_esolver->after_all_runners(ucell); + const bool ran_frame = socket_driver.socket_driver(p_esolver, ucell, PARAM, inp, PARAM.globalv, ofs_running); + if (ran_frame) + { + p_esolver->after_all_runners(ucell); + } ModuleBase::timer::end("Relax_Driver", "relax_driver"); return; } diff --git a/source/source_relax/socket_constant_potential.cpp b/source/source_relax/socket_constant_potential.cpp new file mode 100644 index 0000000000..0eb39aea6f --- /dev/null +++ b/source/source_relax/socket_constant_potential.cpp @@ -0,0 +1,302 @@ +#include "socket_constant_potential.h" +#include "source_base/constants.h" +#include "source_esolver/esolver.h" +#include "source_io/module_parameter/input_parameter.h" +#include "source_io/module_parameter/system_parameter.h" + +#include +#include +#include +#include +#include +#include + +namespace +{ +std::string trim(const std::string &text) +{ + const std::string::size_type begin = text.find_first_not_of(" \t\r\n"); + if (begin == std::string::npos) + { + return ""; + } + return text.substr(begin, text.find_last_not_of(" \t\r\n") - begin + 1); +} + +double number(const std::map &tokens, const std::string &key) +{ + const std::map::const_iterator found = tokens.find(key); + if (found == tokens.end()) + { + throw std::runtime_error("constant-potential INIT requires " + key); + } + std::istringstream in(found->second); + in.imbue(std::locale::classic()); + double value = 0.0; + if (!(in >> value) || !std::isfinite(value)) + { + throw std::runtime_error("INIT " + key + " must be finite and numerical"); + } + in >> std::ws; + if (!in.eof()) + { + throw std::runtime_error("invalid trailing data in INIT " + key); + } + return value; +} +} // namespace + +namespace SocketCP +{ +ScopedElectronicStep::ScopedElectronicStep(elecstate::ElectronicStep **slot, elecstate::ElectronicStep *step) + : slot_(slot) +{ + if (slot_ == nullptr) + { + if (step != nullptr) + { + throw std::runtime_error("electronic request requires a solver slot"); + } + return; + } + if (*slot_ != nullptr) + { + throw std::runtime_error("an electronic step is already bound to this solver"); + } + *slot_ = step; +} + +ScopedElectronicStep::~ScopedElectronicStep() +{ + if (slot_ != nullptr) + { + *slot_ = nullptr; + } +} + +void run_electronic_step( + ModuleESolver::ESolver &solver, + UnitCell &cell, + elecstate::ElectronicStep &step, + const Input_para &inp, + const System_para &system, + int functional_type, + int istep) +{ + if (step.parameters == nullptr || step.request_applied || step.result_ready) + { + throw std::runtime_error("electron control requires a fresh bound electronic step"); + } + const elecstate::ElectronicControl &control = step.control; + if (inp.assume_isolated == "makov-payne") + { + throw std::runtime_error( + "constant-potential electron control is incompatible with the energy-only Makov-Payne correction"); + } + if (inp.esolver_type != "ksdft" || (inp.basis_type != "pw" && inp.basis_type != "lcao") || inp.device != "cpu" || + inp.precision != "double" || system.use_uspp || inp.sc_mag_switch || inp.deepks_scf || inp.rpa || inp.rdmft || + inp.dft_plus_dmft) + { + throw std::runtime_error( + "constant-potential control requires CPU double-precision PW/LCAO KSDFT with " + "norm-conserving pseudopotentials; specialized solver corrections are not supported"); + } + if (inp.basis_type == "lcao" && + (inp.dm_to_rho || inp.ks_solver == "pexsi" || inp.ks_solver == "cusolver" || inp.ks_solver == "cusolvermp")) + { + throw std::runtime_error( + "constant-potential LCAO requires dm_to_rho=0 and a CPU eigensolver " + "that computes band occupations and the Fermi level"); + } + if (functional_type < 1 || functional_type > 5) + { + throw std::runtime_error("constant-potential control requires a supported KS exchange-correlation functional"); + } + if (inp.dft_plus_u != 0 && inp.dft_plus_u != 1) + { + throw std::runtime_error( + "constant-potential forces require dft_plus_u=1; " + "the legacy dft_plus_u=2 force implementation is unavailable"); + } + if (inp.dft_plus_u && + (inp.init_occ_mat < 0 || inp.init_occ_mat > 1 || inp.yukawa_potential || system.uramping > 0.0)) + { + throw std::runtime_error( + "constant-potential DFT+U requires fixed Hubbard U and self-consistent occupations " + "(init_occ_mat=0/1, yukawa_potential=false, uramping disabled)"); + } + if (inp.init_chg == "dm_no_renormalize") + { + throw std::runtime_error("electron-number control requires charge-density renormalization"); + } + if (inp.nspin != 1 && inp.nspin != 2) + { + throw std::runtime_error("constant-potential control supports only nspin=1 or 2"); + } + if (inp.ocp || inp.nbands <= 0 || !std::isfinite(control.nelect) || control.nelect <= 0.0) + { + throw std::runtime_error("invalid total electron number, band capacity, or fixed occupation array"); + } + const bool two_fermi = system.two_fermi; + if (two_fermi && inp.nspin != 2) + { + throw std::runtime_error("two_fermi electron control requires nspin=2"); + } + const double up = 0.5 * (control.nelect + inp.nupdown); + const double down = 0.5 * (control.nelect - inp.nupdown); + if ((two_fermi && + (!std::isfinite(inp.nupdown) || up <= 0.0 || down <= 0.0 || up > inp.nbands || down > inp.nbands)) || + control.nelect > 2.0 * inp.nbands) + { + throw std::runtime_error( + "electron number exceeds band capacity or gives invalid spin populations; increase nbands"); + } + if (inp.smearing_method == "fixed") + { + // Native iweights fills paired bands for a shared Fermi level and single bands per spin otherwise. + const double paired = 0.5 * control.nelect; + const bool full_bands = + two_fermi ? up == std::floor(up) && down == std::floor(down) : paired == std::floor(paired); + if (!full_bands) + { + throw std::runtime_error( + "fractional electron populations per occupied band require a smearing occupation method"); + } + } + solver.runner(cell, istep); + if (!step.request_applied) + { + throw std::runtime_error("selected ESolver did not apply the constant-potential electron request"); + } +} + +Configuration parse_init(const std::string ¶meters) +{ + const std::string keys[] = { + "NELECT", "neutral_electrons", "potential_average_axis", "potential_average_min_A", "potential_average_max_A"}; + std::map tokens; + std::istringstream input(parameters); + std::string token; + while (std::getline(input, token, ',')) + { + token = trim(token); + const std::string::size_type colon = token.find(':'); + const std::string key = trim(token.substr(0, colon)); + if (key == "solvation_update_stride") + { + throw std::runtime_error("INIT solvation_update_stride has been removed"); + } + for (const std::string &known : keys) + { + if (key != known) + { + continue; + } + if (colon == std::string::npos || tokens.count(key)) + { + throw std::runtime_error("missing separator or duplicate constant-potential INIT token: " + key); + } + tokens[key] = trim(token.substr(colon + 1)); + } + } + Configuration config; + if (tokens.empty()) + { + return config; + } + config.enabled = true; + if (number(tokens, "NELECT") <= 0.0) + { + throw std::runtime_error("INIT NELECT must be positive"); + } + if (number(tokens, "neutral_electrons") <= 0.0) + { + throw std::runtime_error("INIT neutral_electrons must be positive"); + } + if (tokens.count("potential_average_axis") || tokens.count("potential_average_min_A") || + tokens.count("potential_average_max_A")) + { + const std::string axis = tokens["potential_average_axis"]; + if (axis.size() != 1 || axis[0] < 'x' || axis[0] > 'z') + { + throw std::runtime_error("INIT potential_average_axis must be x, y or z"); + } + config.window.axis = axis[0] - 'x'; + config.window.minimum_A = number(tokens, "potential_average_min_A"); + config.window.maximum_A = number(tokens, "potential_average_max_A"); + if (config.window.minimum_A < 0.0 || config.window.maximum_A <= config.window.minimum_A) + { + throw std::runtime_error("INIT potential window must satisfy 0 <= min < max"); + } + } + return config; +} + +elecstate::ElectronicControl make_control(const Configuration &config, double nelect, int flags) +{ + if (!config.enabled) + { + throw std::runtime_error("CHGDATA requires constant-potential INIT metadata"); + } + if (!std::isfinite(nelect) || nelect <= 0.0) + { + throw std::runtime_error("CHGDATA total electron number must be finite and positive"); + } + if (flags != 0 && flags != 2) + { + throw std::runtime_error("CHGDATA flags must be 0 or 2; bit 0 is reserved"); + } + if (flags & 2) + { + throw std::runtime_error("ABACUS Ne-electrode CHGDATA is not supported"); + } + elecstate::ElectronicControl control; + control.nelect = nelect; + return control; +} + +Observables collect_observables(const Configuration &config, const elecstate::ElectronicStep &step) +{ + if (!config.enabled) + { + throw std::runtime_error("electronic observables require constant-potential INIT"); + } + if (!step.request_applied || !step.result_ready) + { + throw std::runtime_error("ESolver did not complete this frame's electronic observables"); + } + const elecstate::ElectronicObservables &physical = step.result; + Observables result; + result.fermi_eV = physical.fermi_ry * ModuleBase::Ry_to_eV; + result.nelect = physical.nelect; + if (!std::isfinite(result.fermi_eV) || !std::isfinite(result.nelect) || result.nelect <= 0.0) + { + throw std::runtime_error("invalid constant-potential electronic observables"); + } + result.has_workfunction = config.window.axis >= 0; + if (result.has_workfunction) + { + result.reference_eV = physical.reference_ry * ModuleBase::Ry_to_eV; + result.workfunction_eV = result.reference_eV - result.fermi_eV; + if (!std::isfinite(result.reference_eV) || !std::isfinite(result.workfunction_eV)) + { + throw std::runtime_error("non-finite workfunction"); + } + } + return result; +} + +std::string serialize_observables(const Observables &result) +{ + std::ostringstream out; + out.imbue(std::locale::classic()); + out << std::setprecision(17) << "{\"fermi_level_eV\":" << result.fermi_eV << ",\"nelect\":" << result.nelect; + if (result.has_workfunction) + { + out << ",\"workfunction_eV\":" << result.workfunction_eV + << ",\"electrostatic_reference_eV\":" << result.reference_eV; + } + out << "}"; + return out.str(); +} +} // namespace SocketCP diff --git a/source/source_relax/socket_constant_potential.h b/source/source_relax/socket_constant_potential.h new file mode 100644 index 0000000000..b9eb191db8 --- /dev/null +++ b/source/source_relax/socket_constant_potential.h @@ -0,0 +1,63 @@ +#ifndef ABACUS_SOCKET_CONSTANT_POTENTIAL_H +#define ABACUS_SOCKET_CONSTANT_POTENTIAL_H + +#include "source_estate/electronic_control.h" +#include + +class UnitCell; +struct Input_para; +struct System_para; +namespace ModuleESolver +{ +class ESolver; +} + +namespace SocketCP +{ +struct Configuration +{ + bool enabled = false; + elecstate::PotentialWindow window; +}; + +struct Observables +{ + double fermi_eV = 0.0; + double nelect = 0.0; + bool has_workfunction = false; + double reference_eV = 0.0; + double workfunction_eV = 0.0; +}; + +// Borrow one rank-local request through the solver slot for this evaluation. +class ScopedElectronicStep +{ + public: + ScopedElectronicStep(elecstate::ElectronicStep **slot, elecstate::ElectronicStep *step); + ~ScopedElectronicStep(); + ScopedElectronicStep(const ScopedElectronicStep &) = delete; + ScopedElectronicStep &operator=(const ScopedElectronicStep &) = delete; + + private: + elecstate::ElectronicStep **slot_; +}; + +// Apply one external electron-number request and evaluate the current geometry. +void run_electronic_step( + ModuleESolver::ESolver &solver, + UnitCell &cell, + elecstate::ElectronicStep &step, + const Input_para &input, + const System_para &system, + int functional_type, + int istep); + +Configuration parse_init(const std::string ¶meters); +elecstate::ElectronicControl make_control(const Configuration &config, double nelect, int flags); +// Converts only the physical result completed after this frame's force calculation. +Observables collect_observables(const Configuration &config, const elecstate::ElectronicStep &step); +// Serializes only the completed frame, without calling the solver or MPI. +std::string serialize_observables(const Observables &result); +} // namespace SocketCP + +#endif diff --git a/source/source_relax/socket_driver.cpp b/source/source_relax/socket_driver.cpp index acf6c33ef8..ef4232416d 100644 --- a/source/source_relax/socket_driver.cpp +++ b/source/source_relax/socket_driver.cpp @@ -1,127 +1,30 @@ #include "socket_driver.h" -#include "source_base/timer.h" -#include "source_cell/unitcell.h" #include "source_esolver/esolver.h" -#include "source_io/module_parameter/input_parameter.h" #include "source_relax/socket_handlers.h" -#include "source_relax/socket_utils.h" -#include -#include -#include - -using SocketHandlers::DriverContext; -using SocketUtils::address; -using SocketUtils::ComputedFrame; -using SocketUtils::DriverState; -using SocketUtils::ipi_cell_bohr_from_unitcell; -using SocketUtils::is_root; -using SocketUtils::quit_if_root_failed; - -namespace -{ -void connect_on_root(IpiSocket &socket, std::ofstream &ofs_running) +bool Socket_Driver::socket_driver( + ModuleESolver::ESolver *solver, + UnitCell &cell, + const Input_para &input, + std::ofstream &log) { - int io_failed = 0; - std::string io_message; - if (is_root()) - { - try - { - const std::string endpoint = address(); - ofs_running << " ABACUS socket driver connecting to i-PI endpoint " << endpoint << std::endl; - socket.connect(endpoint); - } - catch (const std::exception &exc) - { - io_failed = 1; - io_message = exc.what(); - } - } - quit_if_root_failed(io_failed, io_message); + return SocketHandlers::run_socket_driver(solver, cell, input, nullptr, nullptr, nullptr, log); } -void log_peer_closed(std::ofstream &ofs_running) +bool Socket_Driver::socket_driver( + ModuleESolver::ESolver *solver, + UnitCell &cell, + Parameter ¶meters, + const Input_para &input, + const System_para &system, + std::ofstream &log) { - if (is_root()) - { - ofs_running << " ABACUS socket driver exiting after peer closed connection" << std::endl; - } -} -} // namespace - -void Socket_Driver::socket_driver( - ModuleESolver::ESolver *p_esolver, - UnitCell &ucell, - const Input_para &inp, - std::ofstream &ofs_running) -{ - ModuleBase::TITLE("Socket_Driver", "socket_driver"); - ModuleBase::timer::start("Socket_Driver", "socket_driver"); - - if (p_esolver == nullptr) + SocketCP::ElectronicSlot *slot = dynamic_cast(solver); + elecstate::ElectronicStep **electronic_slot = nullptr; + if (slot != nullptr) { - ModuleBase::WARNING_QUIT("ABACUS socket", "socket driver requires a valid ESolver."); + electronic_slot = &slot->electronic_step; } - IpiSocket socket; - - try - { - connect_on_root(socket, ofs_running); - - DriverContext context; - context.esolver = p_esolver; - context.ucell = &ucell; - context.inp = &inp; - context.state = DriverState::NeedInit; - context.nat_return = ucell.nat; - context.reference_cell = ipi_cell_bohr_from_unitcell(ucell); - - while (true) - { - const std::string header = SocketHandlers::read_header_bcast(socket, context.state); - if (header.empty()) - { - log_peer_closed(ofs_running); - break; - } - else if (header == "STATUS") - { - SocketHandlers::handle_status(socket, context.state); - } - else if (header == "INIT") - { - SocketHandlers::handle_init(socket, context, ofs_running); - } - else if (header == "POSDATA") - { - SocketHandlers::handle_posdata(socket, context, ofs_running); - } - else if (header == "GETFORCE") - { - SocketHandlers::handle_getforce(socket, context); - } - else if (header == "EXIT") - { - SocketHandlers::handle_exit(ofs_running); - break; - } - else - { - quit_if_root_failed(is_root() ? 1 : 0, is_root() ? "unknown i-PI header: " + header : ""); - } - } - } - catch (const std::exception &exc) - { - ModuleBase::WARNING_QUIT("ABACUS socket", exc.what()); - } - - if (is_root()) - { - socket.close(); - } - - ModuleBase::timer::end("Socket_Driver", "socket_driver"); + return SocketHandlers::run_socket_driver(solver, cell, input, ¶meters, &system, electronic_slot, log); } diff --git a/source/source_relax/socket_driver.h b/source/source_relax/socket_driver.h index 3e77291bab..4e4648271a 100644 --- a/source/source_relax/socket_driver.h +++ b/source/source_relax/socket_driver.h @@ -4,20 +4,51 @@ #include class UnitCell; +class Parameter; struct Input_para; +struct System_para; namespace ModuleESolver { class ESolver; } +namespace elecstate +{ +struct ElectronicStep; +} + +namespace SocketCP +{ +// Implemented only by socket KS adapters. The outer driver owns each request +// and binds this rank-local, non-owning slot for one evaluation. +struct ElectronicSlot +{ + virtual ~ElectronicSlot() = default; + elecstate::ElectronicStep *electronic_step = nullptr; +}; + +ModuleESolver::ESolver *create_pw_socket_solver(); +#ifdef __LCAO +ModuleESolver::ESolver *create_lcao_socket_solver(bool gamma_only); +#endif +} // namespace SocketCP + class Socket_Driver { public: Socket_Driver() = default; ~Socket_Driver() = default; - void socket_driver( + bool socket_driver( + ModuleESolver::ESolver *solver, + UnitCell &cell, + Parameter ¶meters, + const Input_para &input, + const System_para &system, + std::ofstream &log); + + bool socket_driver( ModuleESolver::ESolver *p_esolver, UnitCell &ucell, const Input_para &inp, diff --git a/source/source_relax/socket_handlers.cpp b/source/source_relax/socket_handlers.cpp index 395e8e6518..a09b1cb866 100644 --- a/source/source_relax/socket_handlers.cpp +++ b/source/source_relax/socket_handlers.cpp @@ -1,9 +1,13 @@ #include "socket_handlers.h" #include "source_base/global_function.h" +#include "source_base/timer.h" #include "source_cell/unitcell.h" #include "source_esolver/esolver.h" +#include "source_estate/module_pot/elpot.h" +#include "source_hamilt/module_xc/xc_functional.h" #include "source_io/module_parameter/input_parameter.h" +#include "source_io/module_parameter/system_parameter.h" #include "source_relax/socket_frame.h" #ifdef __JSON #include "source_io/module_json/output_info.h" @@ -12,6 +16,8 @@ #include #include #include +#include +#include #include #include #include @@ -19,10 +25,12 @@ namespace SocketHandlers { +using SocketUtils::address; using SocketUtils::all_ranks_converged; using SocketUtils::bcast_double_vector; using SocketUtils::bcast_header; using SocketUtils::bcast_int32; +using SocketUtils::bcast_string; using SocketUtils::ComputedFrame; using SocketUtils::DriverState; using SocketUtils::fail_during_collective_stage; @@ -46,7 +54,127 @@ using SocketUtils::throw_if_any_rank_failed; using SocketUtils::unchanged_cell_tolerance; using SocketUtils::vector_from_matrix9; -std::string read_header_bcast(IpiSocket &socket, const DriverState state) +namespace +{ +void connect_on_root(IpiSocket &socket, std::ofstream &ofs_running) +{ + int io_failed = 0; + std::string io_message; + if (is_root()) + { + try + { + const std::string endpoint = address(); + ofs_running << " ABACUS socket driver connecting to i-PI endpoint " << endpoint << std::endl; + socket.connect(endpoint); + } + catch (const std::exception &exc) + { + io_failed = 1; + io_message = exc.what(); + } + } + quit_if_root_failed(io_failed, io_message); +} + +void log_peer_closed(std::ofstream &ofs_running) +{ + if (is_root()) + { + ofs_running << " ABACUS socket driver exiting after peer closed connection" << std::endl; + } +} +} // namespace + +bool run_socket_driver( + ModuleESolver::ESolver *p_esolver, + UnitCell &ucell, + const Input_para &inp, + Parameter *parameters, + const System_para *system, + elecstate::ElectronicStep **electronic_slot, + std::ofstream &ofs_running) +{ + ModuleBase::TITLE("Socket_Driver", "run_socket_driver"); + ModuleBase::timer::start("Socket_Driver", "run_socket_driver"); + + if (p_esolver == nullptr) + { + ModuleBase::WARNING_QUIT("ABACUS socket", "socket driver requires a valid ESolver."); + } + IpiSocket socket; + DriverContext context; + + try + { + connect_on_root(socket, ofs_running); + + context.esolver = p_esolver; + context.ucell = &ucell; + context.inp = &inp; + context.parameters = parameters; + context.system = system; + context.electronic_slot = electronic_slot; + context.state = DriverState::NeedInit; + context.nat_return = ucell.nat; + context.reference_cell = ipi_cell_bohr_from_unitcell(ucell); + + while (true) + { + const std::string header = SocketHandlers::read_header_bcast(socket, context); + if (header.empty()) + { + log_peer_closed(ofs_running); + break; + } + else if (header == "STATUS") + { + SocketHandlers::handle_status(socket, context.state); + } + else if (header == "INIT") + { + SocketHandlers::handle_init(socket, context, ofs_running); + } + else if (header == "POSDATA") + { + SocketHandlers::handle_posdata(socket, context, ofs_running); + } + else if (header == "CHGDATA") + { + SocketHandlers::handle_chgdata(socket, context, ofs_running); + } + else if (header == "GETFORCE") + { + SocketHandlers::handle_getforce(socket, context, ofs_running); + } + else if (header == "EXIT") + { + SocketHandlers::handle_exit(context, ofs_running); + break; + } + else + { + const int failed = is_root() ? 1 : 0; + const std::string message = is_root() ? "unknown i-PI header: " + header : ""; + quit_if_root_failed(failed, message); + } + } + } + catch (const std::exception &exc) + { + ModuleBase::WARNING_QUIT("ABACUS socket", exc.what()); + } + + if (is_root()) + { + socket.close(); + } + + ModuleBase::timer::end("Socket_Driver", "run_socket_driver"); + return context.istep > 0; +} + +std::string read_header_bcast(IpiSocket &socket, const DriverContext &context) { std::string header; int io_failed = 0; @@ -59,7 +187,7 @@ std::string read_header_bcast(IpiSocket &socket, const DriverState state) } catch (const IpiSocketClosed &) { - if (state == DriverState::HasData) + if (context.state == DriverState::HasData || context.charge_pending) { io_failed = 1; io_message = "i-PI peer closed while a computed frame was pending"; @@ -154,6 +282,36 @@ void handle_init(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_r { ofs_running << " ABACUS socket INIT params bytes " << nbytes << std::endl; } + bcast_string(params); + int local_failed = 0; + std::string local_message; + try + { + context.cp = SocketCP::parse_init(params); + if (context.cp.enabled && context.electronic_slot == nullptr) + { + throw std::runtime_error("constant-potential socket requires an electronic request slot"); + } + if (context.cp.enabled && + (context.parameters == nullptr || context.system == nullptr || !context.inp->cal_force || + context.inp->cal_stress || (context.inp->symmetry != "0" && context.inp->symmetry != "-1"))) + { + throw std::runtime_error( + "constant-potential socket requires runtime parameters, " + "cal_force=1, cal_stress=0 and symmetry=0/-1"); + } + if (context.cp.window.axis >= 0) + { + const elecstate::PotentialWindow &window = context.cp.window; + elecstate::checked_window_height(*context.ucell, window.axis, window.minimum_A, window.maximum_A); + } + } + catch (const std::exception &exc) + { + local_failed = 1; + local_message = exc.what(); + } + throw_if_any_rank_failed(local_failed, local_message); context.state = DriverState::Ready; if (is_root()) { @@ -161,6 +319,53 @@ void handle_init(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_r } } +void handle_chgdata(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running) +{ + std::vector charge(1, 0.0); + std::int32_t flags = 0; + int io_failed = 0; + std::string io_message; + if (is_root()) + { + try + { + if (context.state != DriverState::Ready || context.charge_pending) + { + throw std::runtime_error("CHGDATA requires READY with no pending charge or force result"); + } + charge[0] = socket.read_double(); + flags = socket.read_int32(); + } + catch (const std::exception &exc) + { + io_failed = 1; + io_message = exc.what(); + } + } + quit_if_root_failed(io_failed, io_message); + bcast_double_vector(charge); + bcast_int32(flags); + int local_failed = 0; + std::string local_message; + try + { + context.pending_control = SocketCP::make_control(context.cp, charge[0], flags); + } + catch (const std::exception &exc) + { + local_failed = 1; + local_message = exc.what(); + } + throw_if_any_rank_failed(local_failed, local_message); + context.charge_pending = true; + if (is_root()) + { + const std::streamsize previous_precision = ofs_running.precision(17); + ofs_running << " @IPI DRIVER: CHGDATA nelect=" << charge[0] << " flag=" << flags << std::endl; + ofs_running.precision(previous_precision); + } +} + namespace { struct PosdataPayload @@ -177,18 +382,23 @@ struct PosdataPayload // passes through the single quit_if_root_failed collective sequence below; // a root-only early quit outside would deadlock if any collective were // added ahead of it. -PosdataPayload read_posdata(IpiSocket &socket, const UnitCell &ucell, const DriverState state) +PosdataPayload read_posdata(IpiSocket &socket, const DriverContext &context) { PosdataPayload payload; int io_failed = 0; std::string io_message; if (is_root()) { - if (state != DriverState::Ready) + if (context.state != DriverState::Ready) { io_failed = 1; io_message = "POSDATA requires READY state"; } + else if (context.cp.enabled && !context.charge_pending) + { + io_failed = 1; + io_message = "constant-potential POSDATA requires one fresh CHGDATA"; + } else { try @@ -207,8 +417,8 @@ PosdataPayload read_posdata(IpiSocket &socket, const UnitCell &ucell, const Driv io_message = "invalid POSDATA cell: " + validation.message; } std::size_t coordinate_count = 0; - if (io_failed == 0 && - !SocketFrame::checked_position_count(payload.nat_socket, ucell.nat, coordinate_count, io_message)) + if (io_failed == 0 && !SocketFrame::checked_position_count( + payload.nat_socket, context.ucell->nat, coordinate_count, io_message)) { io_failed = 1; } @@ -253,17 +463,33 @@ void bcast_posdata(PosdataPayload &payload) bcast_double_vector(payload.positions); } -void check_posdata_geometry(const DriverContext &context, const PosdataPayload &payload, DriverContext &mutable_context) +void check_posdata_geometry(DriverContext &context, const PosdataPayload &payload) { - const double max_cell_delta_bohr = - max_abs_delta(std::vector(payload.cell.begin(), payload.cell.end()), context.reference_cell); - if (max_cell_delta_bohr > unchanged_cell_tolerance(payload.cell)) + const std::vector wire_cell(payload.cell.begin(), payload.cell.end()); + const std::vector &expected_cell = + context.cp.enabled && !context.cp_wire_cell.empty() ? context.cp_wire_cell : context.reference_cell; + double cell_tolerance = unchanged_cell_tolerance(payload.cell); + if (context.cp.enabled && context.cp_wire_cell.empty()) + { + // Allow the two applications' rounded length constants once; lock later wire cells. + double scale = 1.0; + for (const double value : context.reference_cell) + { + scale = std::max(scale, std::abs(value)); + } + cell_tolerance = 1.0e-6 * scale; + } + if (max_abs_delta(wire_cell, expected_cell) > cell_tolerance) { ModuleBase::WARNING_QUIT("ABACUS socket", "variable-cell socket updates are not supported yet."); } - if (!mutable_context.checked_initial_positions) + if (context.cp.enabled && context.cp_wire_cell.empty()) + { + context.cp_wire_cell = wire_cell; + } + if (!context.checked_initial_positions) { - mutable_context.checked_initial_positions = true; + context.checked_initial_positions = true; if (max_wrapped_direct_delta_from_unitcell(*context.ucell, payload.positions) > 1.0e-5 && is_root()) { ModuleBase::WARNING( @@ -275,14 +501,11 @@ void check_posdata_geometry(const DriverContext &context, const PosdataPayload & } void run_esolver_for_positions( - UnitCell &ucell, - ModuleESolver::ESolver *esolver, - const std::vector &positions, - const int istep) + DriverContext &context, const std::vector &positions, elecstate::ElectronicStep *step) { try { - set_positions_from_ipi_bohr(ucell, positions); + set_positions_from_ipi_bohr(*context.ucell, positions, context.cp.enabled); } catch (const std::exception &exc) { @@ -294,7 +517,17 @@ void run_esolver_for_positions( } try { - esolver->runner(ucell, istep); + if (context.cp.enabled) + { + context.charge_pending = false; + const int functional_type = XC_Functional::get_func_type(); + SocketCP::run_electronic_step( + *context.esolver, *context.ucell, *step, *context.inp, *context.system, functional_type, context.istep); + } + else + { + context.esolver->runner(*context.ucell, context.istep); + } } catch (const std::exception &exc) { @@ -414,17 +647,32 @@ void compute_stress(UnitCell &ucell, ModuleESolver::ESolver *esolver, ComputedFr void handle_posdata(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running) { - PosdataPayload payload = read_posdata(socket, *context.ucell, context.state); + PosdataPayload payload = read_posdata(socket, context); bcast_posdata(payload); - check_posdata_geometry(context, payload, context); + check_posdata_geometry(context, payload); + elecstate::ElectronicStep step; + elecstate::ElectronicStep *active_step = nullptr; + if (context.cp.enabled) + { + step.parameters = context.parameters; + step.control = context.pending_control; + step.window = context.cp.window; + step.two_fermi = context.system->two_fermi; + active_step = &step; + } + const SocketCP::ScopedElectronicStep binding(context.electronic_slot, active_step); #ifdef __JSON // Each POSDATA frame is one electronic-structure output step. Json::init_output_array_obj(); #endif - run_esolver_for_positions(*context.ucell, context.esolver, payload.positions, context.istep); + run_esolver_for_positions(context, payload.positions, active_step); ComputedFrame computed; computed.scf_converged = all_ranks_converged(context.esolver->conv_esolver); + if (context.cp.enabled && !computed.scf_converged) + { + throw std::runtime_error("SCF did not converge; refusing to return constant-potential results"); + } if (!computed.scf_converged && is_root()) { ModuleBase::WARNING( @@ -439,13 +687,29 @@ void handle_posdata(IpiSocket &socket, DriverContext &context, std::ofstream &of { compute_stress(*context.ucell, context.esolver, computed); } + if (context.cp.enabled) + { + try + { + computed.electronic = SocketCP::collect_observables(context.cp, step); + } + catch (const std::exception &exc) + { + fail_during_collective_stage("electronic_observables", exc.what()); + } + catch (...) + { + fail_during_collective_stage("electronic_observables", "unknown electronic observables failure"); + } + computed.electronic_present = true; + } computed.valid = true; context.published = computed; ++context.istep; context.state = DriverState::HasData; } -void handle_getforce(IpiSocket &socket, DriverContext &context) +void handle_getforce(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running) { int io_failed = 0; std::string io_message; @@ -473,6 +737,10 @@ void handle_getforce(IpiSocket &socket, DriverContext &context) } socket.write_int32(static_cast(extra.size())); socket.write_string(extra); + if (context.cp.enabled) + { + ofs_running << " @IPI DRIVER: Sending extras JSON = " << extra << std::endl; + } } catch (const std::exception &exc) { @@ -485,8 +753,13 @@ void handle_getforce(IpiSocket &socket, DriverContext &context) context.state = DriverState::Ready; } -void handle_exit(std::ofstream &ofs_running) +void handle_exit(const DriverContext &context, std::ofstream &ofs_running) { + if (context.cp.enabled) + { + const bool unfinished = context.state == DriverState::HasData || context.charge_pending; + throw_if_any_rank_failed(unfinished, "EXIT with an unfinished request/result"); + } if (is_root()) { ofs_running << " ABACUS socket driver received i-PI EXIT" << std::endl; diff --git a/source/source_relax/socket_handlers.h b/source/source_relax/socket_handlers.h index d1bcab2967..b334c94ce5 100644 --- a/source/source_relax/socket_handlers.h +++ b/source/source_relax/socket_handlers.h @@ -9,6 +9,8 @@ #include class UnitCell; +class Parameter; +struct System_para; namespace ModuleESolver { @@ -23,28 +25,47 @@ struct DriverContext ModuleESolver::ESolver *esolver = nullptr; UnitCell *ucell = nullptr; const Input_para *inp = nullptr; + Parameter *parameters = nullptr; + const System_para *system = nullptr; + elecstate::ElectronicStep **electronic_slot = nullptr; SocketUtils::DriverState state = SocketUtils::DriverState::NeedInit; int istep = 0; int nat_return = 0; SocketUtils::ComputedFrame published; std::vector reference_cell; bool checked_initial_positions = false; + SocketCP::Configuration cp; + elecstate::ElectronicControl pending_control; + bool charge_pending = false; + std::vector cp_wire_cell; }; +// Run one socket session with an optional, rank-local electronic request slot. +bool run_socket_driver( + ModuleESolver::ESolver *solver, + UnitCell &cell, + const Input_para &input, + Parameter *parameters, + const System_para *system, + elecstate::ElectronicStep **electronic_slot, + std::ofstream &log); + // Reads the next i-PI header on the root rank and broadcasts it to all ranks. // Returns an empty string when the peer closed the connection while no frame // is pending. Calls WARNING_QUIT on unrecoverable I/O failure. -std::string read_header_bcast(IpiSocket &socket, const SocketUtils::DriverState state); +std::string read_header_bcast(IpiSocket &socket, const DriverContext &context); void handle_status(IpiSocket &socket, const SocketUtils::DriverState state); void handle_init(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running); +void handle_chgdata(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running); + void handle_posdata(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running); -void handle_getforce(IpiSocket &socket, DriverContext &context); +void handle_getforce(IpiSocket &socket, DriverContext &context, std::ofstream &ofs_running); -void handle_exit(std::ofstream &ofs_running); +void handle_exit(const DriverContext &context, std::ofstream &ofs_running); } // namespace SocketHandlers #endif diff --git a/source/source_relax/socket_ks.cpp b/source/source_relax/socket_ks.cpp new file mode 100644 index 0000000000..492c7aa048 --- /dev/null +++ b/source/source_relax/socket_ks.cpp @@ -0,0 +1,110 @@ +#include "socket_driver.h" + +#include "source_base/parallel_grid.h" +#include "source_cell/stru_fac.h" +#include "source_cell/unitcell.h" +#include "source_esolver/esolver_ks_pw.h" +#include "source_estate/electronic_control.h" +#include "source_hamilt/module_xc/xc_functional.h" + +#ifdef __LCAO +#include "source_esolver/esolver_ks_lcao.h" +#ifdef __EXX +#include "source_lcao/module_ri/exx_lri_interface.h" +#endif +#endif + +namespace +{ +// Reuse the native solver lifecycle; only a bound electronic request changes +// convergence handling or collects feedback after the native nuclear forces. +template +class SocketKS : public Solver, public SocketCP::ElectronicSlot +{ + public: + void cal_force(BaseCell &basecell, ModuleBase::matrix &force) override + { + Solver::cal_force(basecell, force); + if (this->electronic_step != nullptr) + { + basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); + const UnitCell &cell = static_cast(basecell); + elecstate::complete_electronic_step( + cell, this->pelec, this->pw_rhod, this->solvent, *this->inp_, this->conv_esolver, + *this->electronic_step); + } + } + + protected: + void iter_finish( + UnitCell &cell, + const int istep, + int &iter, + bool &converged) override + { + Solver::iter_finish(cell, istep, iter, converged); + if (this->electronic_step != nullptr && this->oscillate_esolver) + { + converged = false; + } + } +}; + +class SocketPW : public SocketKS, base_device::DEVICE_CPU>> +{ + protected: + void before_scf(UnitCell &cell, const int istep) override + { + const bool active = this->electronic_step != nullptr; + if (active) + { + this->conv_esolver = false; + validate_electronic_step_exx(XC_Functional::get_func_type(), this->general_exx_info_.cal_exx); + elecstate::prepare_electronic_step(cell, this->pelec, *this->electronic_step, *this->inp_); + } + this->exx_helper->begin_electronic_step(active); + ModuleESolver::ESolver_KS_PW, base_device::DEVICE_CPU>::before_scf(cell, istep); + } +}; + +#ifdef __LCAO +template +class SocketLCAO : public SocketKS> +{ + protected: + void before_scf(UnitCell &cell, const int istep) override + { + const bool active = this->electronic_step != nullptr; + if (active) + { + this->conv_esolver = false; + elecstate::prepare_electronic_step(cell, this->pelec, *this->electronic_step, *this->inp_); + } +#ifdef __EXX + if (this->exx_nao.exd) + { + this->exx_nao.exd->begin_electronic_step(active); + } + if (this->exx_nao.exc) + { + this->exx_nao.exc->begin_electronic_step(active); + } +#endif + ModuleESolver::ESolver_KS_LCAO::before_scf(cell, istep); + } +}; +#endif +} // namespace + +ModuleESolver::ESolver *SocketCP::create_pw_socket_solver() { return new SocketPW(); } + +#ifdef __LCAO +ModuleESolver::ESolver *SocketCP::create_lcao_socket_solver(bool gamma_only) +{ + if (gamma_only) + { + return new SocketLCAO(); + } + return new SocketLCAO>(); +} +#endif diff --git a/source/source_relax/socket_utils.cpp b/source/source_relax/socket_utils.cpp index eb37a51e6d..7b31e1e2a9 100644 --- a/source/source_relax/socket_utils.cpp +++ b/source/source_relax/socket_utils.cpp @@ -77,7 +77,13 @@ std::string properties_extra(const ComputedFrame &frame) { extra << ",\"stress\""; } - extra << "],\"scf_converged\":" << (frame.scf_converged ? "true" : "false") << "}"; + extra << "],\"scf_converged\":" << (frame.scf_converged ? "true" : "false"); + if (frame.electronic_present) + { + const std::string electronic = SocketCP::serialize_observables(frame.electronic); + extra << "," << electronic.substr(1, electronic.size() - 2); + } + extra << "}"; return extra.str(); } @@ -231,7 +237,8 @@ double unchanged_cell_tolerance(const SocketFrame::Matrix9 &cell) return 32.0 * std::numeric_limits::epsilon() * std::max(1.0, maximum); } -void set_positions_from_ipi_bohr(UnitCell &ucell, const std::vector &positions_bohr) +void set_positions_from_ipi_bohr( + UnitCell &ucell, const std::vector &positions_bohr, bool minimum_image_displacement) { if (positions_bohr.size() != static_cast(3 * ucell.nat)) { @@ -258,6 +265,12 @@ void set_positions_from_ipi_bohr(UnitCell &ucell, const std::vector &pos atom->dis[ia].x = dx - atom->taud[ia].x; atom->dis[ia].y = dy - atom->taud[ia].y; atom->dis[ia].z = dz - atom->taud[ia].z; + if (minimum_image_displacement) + { + atom->dis[ia].x -= std::round(atom->dis[ia].x); + atom->dis[ia].y -= std::round(atom->dis[ia].y); + atom->dis[ia].z -= std::round(atom->dis[ia].z); + } atom->taud[ia].x = dx; atom->taud[ia].y = dy; atom->taud[ia].z = dz; diff --git a/source/source_relax/socket_utils.h b/source/source_relax/socket_utils.h index 2d6e5d01b8..59f7dae5ad 100644 --- a/source/source_relax/socket_utils.h +++ b/source/source_relax/socket_utils.h @@ -2,6 +2,7 @@ #define ABACUS_SOURCE_RELAX_SOCKET_UTILS_H #include "source_base/matrix.h" +#include "source_relax/socket_constant_potential.h" #include "source_relax/socket_frame.h" #include @@ -35,6 +36,8 @@ struct ComputedFrame bool forces_present = false; bool stress_present = false; bool scf_converged = true; + bool electronic_present = false; + SocketCP::Observables electronic; double energy_hartree = 0.0; std::vector forces_hartree_per_bohr; SocketFrame::Matrix9 virial_wire_hartree = {{0.0}}; @@ -57,7 +60,8 @@ std::vector ipi_cell_bohr_from_unitcell(const UnitCell &ucell); double max_wrapped_direct_delta_from_unitcell(const UnitCell &ucell, const std::vector &positions_bohr); double max_abs_delta(const std::vector &a, const std::vector &b); double unchanged_cell_tolerance(const SocketFrame::Matrix9 &cell); -void set_positions_from_ipi_bohr(UnitCell &ucell, const std::vector &positions_bohr); +void set_positions_from_ipi_bohr( + UnitCell &ucell, const std::vector &positions_bohr, bool minimum_image_displacement); std::vector flatten_forces_hartree_per_bohr(const ModuleBase::matrix &force, int nat); SocketFrame::Matrix9 matrix9_from_stress(const ModuleBase::matrix &stress); std::vector vector_from_matrix9(const SocketFrame::Matrix9 &values); diff --git a/source/source_relax/unittests/CMakeLists.txt b/source/source_relax/unittests/CMakeLists.txt index 895c5a0707..2a25e5c22f 100644 --- a/source/source_relax/unittests/CMakeLists.txt +++ b/source/source_relax/unittests/CMakeLists.txt @@ -11,6 +11,10 @@ addtest(TARGET MODULE_RELAX_socket_frame_test SOURCES test_socket_frame.cpp ../socket_frame.cpp ../socket_frame_utils.cpp) +addtest(TARGET MODULE_RELAX_socket_constant_potential_test + SOURCES test_socket_constant_potential.cpp + ../socket_constant_potential.cpp) + set(socket_json_sources) if(ENABLE_JSON) list(APPEND socket_json_sources ../../source_io/module_json/abacusjson.cpp @@ -25,6 +29,7 @@ addtest( ../socket_driver.cpp ../socket_utils.cpp ../socket_handlers.cpp + ../socket_constant_potential.cpp ../socket_frame_utils.cpp ../socket_frame.cpp ../socket_ipi.cpp diff --git a/source/source_relax/unittests/test_relax_driver.cpp b/source/source_relax/unittests/test_relax_driver.cpp index 19f4c6547c..6e83781b34 100644 --- a/source/source_relax/unittests/test_relax_driver.cpp +++ b/source/source_relax/unittests/test_relax_driver.cpp @@ -108,12 +108,24 @@ void write_stru( } } // namespace relax_stru_io -void Socket_Driver::socket_driver( - ModuleESolver::ESolver *, - UnitCell &, +namespace +{ +int socket_frame_count = 0; +} + +bool Socket_Driver::socket_driver( + ModuleESolver::ESolver *solver, + UnitCell &cell, + Parameter &, const Input_para &, + const System_para &, std::ofstream &) { + for (int step = 0; step < socket_frame_count; ++step) + { + solver->runner(cell, step); + } + return socket_frame_count > 0; } namespace @@ -173,7 +185,11 @@ class DriverTestESolver : public ModuleESolver::ESolver class RelaxDriverTest : public ::testing::Test { protected: - void SetUp() override { log_file_ = testing::TempDir() + "running.log"; } + void SetUp() override + { + log_file_ = testing::TempDir() + "running.log"; + socket_frame_count = 0; + } static void make_cell(UnitCell &ucell) { @@ -462,3 +478,32 @@ TEST_F(RelaxDriverTest, ExitStopsBeforeSimultaneousRelaxStep) } } // namespace + +TEST_F(RelaxDriverTest, SocketWithoutCompletedFrameSkipsFinalization) +{ + Input_para inp; + inp.socket_driver = true; + UnitCell cell; + make_cell(cell); + DriverTestESolver solver(0.0); + std::ofstream output(log_file_); + Relax_Driver driver; + driver.relax_driver(&solver, cell, inp, output); + EXPECT_EQ(solver.runner_count, 0); + EXPECT_EQ(solver.after_all_count, 0); +} + +TEST_F(RelaxDriverTest, SocketCompletedFramesFinalizeOnce) +{ + Input_para inp; + inp.socket_driver = true; + socket_frame_count = 2; + UnitCell cell; + make_cell(cell); + DriverTestESolver solver(0.0); + std::ofstream output(log_file_); + Relax_Driver driver; + driver.relax_driver(&solver, cell, inp, output); + EXPECT_EQ(solver.runner_count, 2); + EXPECT_EQ(solver.after_all_count, 1); +} diff --git a/source/source_relax/unittests/test_socket_constant_potential.cpp b/source/source_relax/unittests/test_socket_constant_potential.cpp new file mode 100644 index 0000000000..09efaf6547 --- /dev/null +++ b/source/source_relax/unittests/test_socket_constant_potential.cpp @@ -0,0 +1,220 @@ +#include "source_base/constants.h" +#include "source_relax/socket_constant_potential.h" + +#include "gtest/gtest.h" + +#include +#include +#include +#include + +namespace +{ +const std::string metadata = "NELECT:8.25,neutral_electrons:8"; +} + +TEST(SocketConstantPotentialTest, OrdinaryInitDoesNotEnableElectronControl) +{ + EXPECT_FALSE(SocketCP::parse_init("").enabled); + EXPECT_FALSE(SocketCP::parse_init("label:ordinary,unused:123").enabled); + EXPECT_THROW(SocketCP::make_control(SocketCP::Configuration(), 8.0, 1), std::runtime_error); +} + +TEST(SocketConstantPotentialTest, FractionalElectronRequestIsPreserved) +{ + const SocketCP::Configuration config = SocketCP::parse_init(metadata); + const elecstate::ElectronicControl control = SocketCP::make_control(config, 8.3125, 0); + EXPECT_TRUE(config.enabled); + EXPECT_DOUBLE_EQ(8.3125, control.nelect); +} + +TEST(SocketConstantPotentialTest, ConstantPotentialInitRequiresCompleteMetadata) +{ + EXPECT_THROW(SocketCP::parse_init("NELECT:8"), std::runtime_error); + EXPECT_THROW(SocketCP::parse_init("neutral_electrons:8"), std::runtime_error); + EXPECT_TRUE(SocketCP::parse_init("NELECT:8,neutral_electrons:8").enabled); + EXPECT_THROW(SocketCP::parse_init(metadata + ",NELECT:9"), std::runtime_error); + EXPECT_THROW(SocketCP::parse_init(metadata + ",neutral_electrons:8"), std::runtime_error); +} + +TEST(SocketConstantPotentialTest, InitRejectsInvalidNumericalValues) +{ + EXPECT_THROW(SocketCP::parse_init("NELECT:8junk,neutral_electrons:8"), std::runtime_error); + EXPECT_THROW(SocketCP::parse_init("NELECT:0,neutral_electrons:8"), std::runtime_error); + EXPECT_THROW(SocketCP::parse_init("NELECT:8,neutral_electrons:-1"), std::runtime_error); +} + +TEST(SocketConstantPotentialTest, PotentialWindowsSupportEachCartesianAxis) +{ + for (int axis = 0; axis < 3; ++axis) + { + const SocketCP::Configuration config = SocketCP::parse_init( + metadata + ",potential_average_axis:" + std::string(1, 'x' + axis) + + ",potential_average_min_A:12.5,potential_average_max_A:15"); + EXPECT_EQ(axis, config.window.axis); + EXPECT_DOUBLE_EQ(12.5, config.window.minimum_A); + EXPECT_DOUBLE_EQ(15.0, config.window.maximum_A); + } +} + +TEST(SocketConstantPotentialTest, PotentialWindowRejectsInvalidOrMissingBounds) +{ + EXPECT_THROW(SocketCP::parse_init(metadata + ",potential_average_axis:xy"), std::runtime_error); + EXPECT_THROW( + SocketCP::parse_init(metadata + ",potential_average_axis:z,potential_average_min_A:1"), std::runtime_error); + EXPECT_THROW( + SocketCP::parse_init( + metadata + ",potential_average_axis:z,potential_average_min_A:2,potential_average_max_A:1"), + std::runtime_error); + EXPECT_THROW( + SocketCP::parse_init( + metadata + ",potential_average_axis:z,potential_average_min_A:-1,potential_average_max_A:2"), + std::runtime_error); +} + +TEST(SocketConstantPotentialTest, RejectsRemovedStrideEvenForOrdinaryInit) +{ + EXPECT_THROW(SocketCP::parse_init("solvation_update_stride:1"), std::runtime_error); + EXPECT_THROW(SocketCP::parse_init(metadata + ",solvation_update_stride:5"), std::runtime_error); +} + +TEST(SocketConstantPotentialTest, RejectsNeElectrodeAndUnknownFlags) +{ + const SocketCP::Configuration config = SocketCP::parse_init(metadata); + EXPECT_THROW(SocketCP::make_control(config, 8.0, 1), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, 8.0, 2), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, 8.0, 3), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, 8.0, 4), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, 8.0, -1), std::runtime_error); +} + +TEST(SocketConstantPotentialTest, RejectsInvalidElectronRequests) +{ + const SocketCP::Configuration config = SocketCP::parse_init(metadata); + EXPECT_THROW(SocketCP::make_control(config, 0.0, 0), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, -1.0, 0), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, std::numeric_limits::quiet_NaN(), 0), std::runtime_error); + EXPECT_THROW(SocketCP::make_control(config, std::numeric_limits::infinity(), 0), std::runtime_error); +} + +TEST(SocketConstantPotentialTest, SerializesTheExistingElectronicExtrasKeys) +{ + SocketCP::Observables values; + values.nelect = 8.125; + values.fermi_eV = -0.25; + EXPECT_EQ("{\"fermi_level_eV\":-0.25,\"nelect\":8.125}", SocketCP::serialize_observables(values)); + values.has_workfunction = true; + values.reference_eV = 4.0; + values.workfunction_eV = 4.25; + EXPECT_EQ( + "{\"fermi_level_eV\":-0.25,\"nelect\":8.125,\"workfunction_eV\":4.25," + "\"electrostatic_reference_eV\":4}", + SocketCP::serialize_observables(values)); +} + +namespace +{ +class DecimalComma : public std::numpunct +{ + char do_decimal_point() const override { return ','; } +}; +} // namespace + +TEST(SocketConstantPotentialTest, JsonNumbersIgnoreTheGlobalDecimalSeparator) +{ + SocketCP::Observables values; + values.nelect = 8.125; + values.fermi_eV = -0.25; + const std::locale previous = std::locale(); + std::locale::global(std::locale(previous, new DecimalComma)); + const std::string json = SocketCP::serialize_observables(values); + std::locale::global(previous); + EXPECT_EQ("{\"fermi_level_eV\":-0.25,\"nelect\":8.125}", json); +} + +TEST(SocketElectronicFrameTest, BindingIsScopedAndRejectsNestedRequests) +{ + elecstate::ElectronicStep *slot = nullptr; + elecstate::ElectronicStep first; + elecstate::ElectronicStep second; + EXPECT_EQ(nullptr, slot); + { + SocketCP::ScopedElectronicStep binding(&slot, &first); + EXPECT_EQ(&first, slot); + EXPECT_THROW(SocketCP::ScopedElectronicStep nested(&slot, &second), std::runtime_error); + EXPECT_EQ(&first, slot); + } + EXPECT_EQ(nullptr, slot); + try + { + SocketCP::ScopedElectronicStep binding(&slot, &second); + throw std::runtime_error("evaluation failed"); + } + catch (const std::runtime_error &) + { + EXPECT_EQ(nullptr, slot); + } +} + +TEST(SocketElectronicFrameTest, MissingSlotOnlyAcceptsOrdinaryEvaluation) +{ + elecstate::ElectronicStep step; + EXPECT_NO_THROW(SocketCP::ScopedElectronicStep ordinary(nullptr, nullptr)); + EXPECT_THROW(SocketCP::ScopedElectronicStep missing(nullptr, &step), std::runtime_error); +} + +TEST(SocketElectronicFrameTest, SeparateSolversDoNotShareRequestState) +{ + elecstate::ElectronicStep *first_slot = nullptr; + elecstate::ElectronicStep *second_slot = nullptr; + elecstate::ElectronicStep first; + elecstate::ElectronicStep second; + first.control.nelect = 8.25; + second.control.nelect = 7.75; + SocketCP::ScopedElectronicStep first_binding(&first_slot, &first); + { + SocketCP::ScopedElectronicStep second_binding(&second_slot, &second); + first_slot->request_applied = true; + EXPECT_FALSE(second_slot->request_applied); + EXPECT_DOUBLE_EQ(8.25, first_slot->control.nelect); + EXPECT_DOUBLE_EQ(7.75, second_slot->control.nelect); + } + EXPECT_EQ(nullptr, second_slot); + EXPECT_EQ(&first, first_slot); +} + +TEST(SocketElectronicFrameTest, CollectionConvertsPhysicalUnitsAndKeepsZeroFermi) +{ + elecstate::ElectronicStep step; + step.request_applied = true; + step.result_ready = true; + step.result.nelect = 8.125; + step.result.fermi_ry = 0.0; + step.result.reference_ry = 0.25; + const SocketCP::Configuration config = SocketCP::parse_init( + "NELECT:8,neutral_electrons:8,potential_average_axis:y,potential_average_min_A:2,potential_average_max_A:3"); + step.window = config.window; + const SocketCP::Observables values = SocketCP::collect_observables(config, step); + EXPECT_DOUBLE_EQ(0.0, values.fermi_eV); + EXPECT_DOUBLE_EQ(8.125, values.nelect); + EXPECT_TRUE(values.has_workfunction); + EXPECT_DOUBLE_EQ(0.25 * ModuleBase::Ry_to_eV, values.reference_eV); + EXPECT_DOUBLE_EQ(values.reference_eV, values.workfunction_eV); +} + +TEST(SocketElectronicFrameTest, CollectionRejectsMissingOrInvalidPhysicalObservables) +{ + elecstate::ElectronicStep step; + const SocketCP::Configuration config = SocketCP::parse_init("NELECT:8,neutral_electrons:8"); + const SocketCP::Configuration ordinary; + EXPECT_THROW(SocketCP::collect_observables(ordinary, step), std::runtime_error); + EXPECT_THROW(SocketCP::collect_observables(config, step), std::runtime_error); + step.result_ready = true; + EXPECT_THROW(SocketCP::collect_observables(config, step), std::runtime_error); + step.request_applied = true; + step.result.nelect = 0.0; + EXPECT_THROW(SocketCP::collect_observables(config, step), std::runtime_error); + step.result.nelect = 8.0; + step.result.fermi_ry = std::numeric_limits::quiet_NaN(); + EXPECT_THROW(SocketCP::collect_observables(config, step), std::runtime_error); +} diff --git a/source/source_relax/unittests/test_socket_driver.cpp b/source/source_relax/unittests/test_socket_driver.cpp index ead2612e66..8e9c4b608b 100644 --- a/source/source_relax/unittests/test_socket_driver.cpp +++ b/source/source_relax/unittests/test_socket_driver.cpp @@ -1,14 +1,21 @@ #include "for_test.h" +#ifdef __MPI #include "mpi.h" +#endif +#include "source_base/constants.h" #include "source_cell/unitcell.h" #include "source_esolver/esolver.h" +#include "source_estate/module_pot/elpot.h" +#include "source_hamilt/module_xc/xc_functional.h" #include "source_io/module_parameter/input_parameter.h" +#include "source_io/module_parameter/parameter.h" +#include "source_relax/socket_constant_potential.h" #include "source_relax/socket_driver.h" +#include "source_relax/socket_utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include -#include #include #include #include @@ -23,6 +30,19 @@ #include #include #include +#include + +int XC_Functional::func_type = 2; + +// All cells in this socket fixture are cubic. The grid and geometry tests live in source_estate. +double elecstate::checked_window_height( + const UnitCell &cell, + int, + double, + double) +{ + return cell.lat0 * ModuleBase::BOHR_TO_A; +} namespace { @@ -71,23 +91,6 @@ void send_header(const int fd, const std::string &header) send_all(fd, padded.data(), padded.size()); } -bool try_send_status(const int fd) -{ - try - { - send_header(fd, "STATUS"); - return true; - } - catch (const std::runtime_error &) - { - if (errno == EPIPE || errno == ECONNRESET) - { - return false; - } - throw; - } -} - std::string read_header_or_close(const int fd) { char header[kIpiHeaderLen]; @@ -193,16 +196,17 @@ class UnixSocketServer std::string path_; }; -class FakeESolver : public ModuleESolver::ESolver +class FrameESolver : public ModuleESolver::ESolver { public: - explicit FakeESolver(const bool converged) : converged_(converged) {} + explicit FrameESolver(const bool converged) : converged_(converged) {} void before_all_runners(BaseCell &, const Input_para &) override {} void runner(BaseCell &cell, const int step) override { - position_ = dynamic_cast(cell).atoms[0].tau[0].x; + UnitCell &ucell = dynamic_cast(cell); + position_ = ucell.atoms[0].tau[0].x; this->conv_esolver = converged_ && step == 0; } @@ -229,10 +233,78 @@ class FakeESolver : public ModuleESolver::ESolver bool converged_; }; +enum class ElectronicFailure +{ + None, + SecondFrame, + IgnoreRequest, + MissingResult, + MissingSlot +}; + +class ControlledESolver : public FrameESolver, public SocketCP::ElectronicSlot +{ + public: + explicit ControlledESolver(const ElectronicFailure failure) : FrameESolver(true), failure_(failure) {} + + void runner(BaseCell &cell, const int step) override + { + if (electronic_step == nullptr || electronic_step->request_applied || electronic_step->result_ready) + { + throw std::runtime_error("each runner needs one fresh electronic request"); + } + if (failure_ != ElectronicFailure::IgnoreRequest) + { + nelect = electronic_step->control.nelect; + electronic_step->request_applied = true; + ++control_count; + } + FrameESolver::runner(cell, step); + ++runner_count; + conv_esolver = failure_ != ElectronicFailure::SecondFrame || step == 0; + } + + double cal_energy() override { return FrameESolver::cal_energy() + nelect; } + + void cal_force(BaseCell &cell, ModuleBase::matrix &force) override + { + FrameESolver::cal_force(cell, force); + elecstate::ElectronicStep *electronic = electronic_step; + if (!electronic || !electronic->request_applied || electronic->result_ready || !conv_esolver) + { + throw std::runtime_error("electronic result requires one converged request"); + } + if (failure_ == ElectronicFailure::MissingResult) + { + return; + } + electronic->result.nelect = nelect; + electronic->result.fermi_ry = -0.125; + const elecstate::PotentialWindow &window = electronic->window; + if (window.axis >= 0) + { + if (window.axis != 1 || window.minimum_A != 0.125 || window.maximum_A != 0.375) + { + throw std::runtime_error("solver received the wrong potential window"); + } + electronic->result.reference_ry = 0.25; + } + electronic->result_ready = true; + ++collection_count; + } + + double nelect = 0.0; + int control_count = 0; + int runner_count = 0; + int collection_count = 0; + + private: + ElectronicFailure failure_; +}; + struct DriverResult { int exit_code = -1; - std::string response_header; std::string diagnostic; }; @@ -271,6 +343,14 @@ void send_positions(const int fd, const double x) send_all(fd, position, sizeof(position)); } +void send_charge(const int fd, const double nelect) +{ + const std::int32_t flags = 0; + send_header(fd, "CHGDATA"); + send_value(fd, nelect); + send_value(fd, flags); +} + void send_fixed_cell_frame(const int fd) { const std::int32_t replica = 0; @@ -340,6 +420,17 @@ ForceResponse read_force_response(const int fd) return response; } +double read_extra_number(const std::string &extra, const std::string &field) +{ + const std::string key = "\"" + field + "\":"; + const std::string::size_type offset = extra.find(key); + if (offset == std::string::npos) + { + throw std::runtime_error("missing GETFORCE field: " + field); + } + return std::stod(extra.substr(offset + key.size())); +} + std::string read_pipe(const int fd) { std::string output; @@ -364,11 +455,7 @@ std::string read_pipe(const int fd) return output; } -DriverResult run_driver_frame( - const bool converged, - const bool cal_force, - const bool cal_stress, - const std::function &peer_action) +DriverResult run_driver_session(const std::function &driver_action, const std::function &peer_action) { UnixSocketServer server; int output_pipe[2]; @@ -392,15 +479,14 @@ DriverResult run_driver_frame( ::close(output_pipe[1]); ::setenv("ABACUS_SOCKET_ADDRESS", server.address().c_str(), 1); - UnitCell ucell; - initialize_one_atom_cell(ucell); - Input_para input; - input.cal_force = cal_force; - input.cal_stress = cal_stress; - FakeESolver solver(converged); - std::ofstream running("/dev/null"); - Socket_Driver driver; - driver.socket_driver(&solver, ucell, input, running); + // The socket peer stays outside MPI; each child owns its MPI runtime. +#ifdef __MPI + MPI_Init(nullptr, nullptr); +#endif + driver_action(); +#ifdef __MPI + MPI_Finalize(); +#endif std::cout.flush(); std::cerr.flush(); ::_exit(0); @@ -420,7 +506,6 @@ DriverResult run_driver_frame( { throw std::runtime_error(errno_message("setsockopt failed")); } - send_fixed_cell_frame(peer_fd); peer_action(peer_fd); } catch (...) @@ -453,67 +538,373 @@ DriverResult run_driver_frame( } return result; } -} // namespace -TEST(SocketDriverTest, NonconvergedFrameIsPublishedWithMetadata) +DriverResult run_driver_frame( + const bool converged, + const bool cal_force, + const bool cal_stress, + const std::function &peer_action) { - ForceResponse response; - const DriverResult result = run_driver_frame( - false, true, false, + return run_driver_session( + [&]() + { + UnitCell cell; + initialize_one_atom_cell(cell); + Parameter parameters; + Input_para input; + System_para system; + input.cal_force = cal_force; + input.cal_stress = cal_stress; + FrameESolver solver(converged); + std::ofstream running("/dev/null"); + Socket_Driver driver; + if (!driver.socket_driver(&solver, cell, parameters, input, system, running)) + { + throw std::runtime_error("ordinary socket driver reported no completed frame"); + } + }, [&](const int fd) { - send_header(fd, "GETFORCE"); - response = read_force_response(fd); + send_fixed_cell_frame(fd); + peer_action(fd); }); - - EXPECT_EQ("FORCEREADY", response.header); - EXPECT_EQ(0, result.exit_code); - EXPECT_THAT(response.extra, testing::HasSubstr("\"scf_converged\":false")); } -TEST(SocketDriverTest, EnergyOnlyFrameMarksForceAndStressAbsent) +DriverResult run_constant_potential_session( + const std::function &peer_action, const ElectronicFailure failure, const std::string &init_options) { - ForceResponse response; - const DriverResult result = run_driver_frame( - true, false, false, + return run_driver_session( + [&]() + { + UnitCell cell; + initialize_one_atom_cell(cell); + Parameter parameters; + Input_para input; + System_para system; + input.cal_force = true; + input.cal_stress = false; + input.symmetry = "0"; + input.esolver_type = "ksdft"; + input.basis_type = "pw"; + input.device = "cpu"; + input.precision = "double"; + input.nspin = 1; + input.nbands = 8; + input.smearing_method = "gaussian"; + std::ofstream running("/dev/null"); + Socket_Driver driver; + if (failure == ElectronicFailure::MissingSlot) + { + FrameESolver solver(true); + driver.socket_driver(&solver, cell, parameters, input, system, running); + return; + } + ControlledESolver solver(failure); + driver.socket_driver(&solver, cell, parameters, input, system, running); + if (solver.electronic_step != nullptr) + { + throw std::runtime_error("completed electronic request remained bound to the solver"); + } + std::cout << "CP calls: " << solver.control_count << " controls, " << solver.runner_count << " runners, " + << solver.collection_count << " collections\n"; + }, [&](const int fd) { - send_header(fd, "GETFORCE"); - response = read_force_response(fd); + send_header(fd, "STATUS"); + EXPECT_EQ("NEEDINIT", read_header_or_close(fd)); + const std::string metadata = "NELECT:8,neutral_electrons:8" + init_options; + const std::int32_t replica = 0; + const std::int32_t nbytes = static_cast(metadata.size()); + send_header(fd, "INIT"); + send_value(fd, replica); + send_value(fd, nbytes); + send_all(fd, metadata.data(), metadata.size()); + peer_action(fd); }); +} +} // namespace - EXPECT_EQ("FORCEREADY", response.header); +TEST(SocketDriverTest, CrossingUsesRequestedDisplacementConvention) +{ + UnitCell cell; + initialize_one_atom_cell(cell); + const std::vector positions = {0.05, 0.95, 0.5}; + const ModuleBase::Vector3 initial(0.95, 0.05, 0.5); + cell.atoms[0].taud[0] = initial; + SocketUtils::set_positions_from_ipi_bohr(cell, positions, false); + EXPECT_NEAR(cell.atoms[0].dis[0].x, -0.9, 1e-14); + EXPECT_NEAR(cell.atoms[0].dis[0].y, 0.9, 1e-14); + cell.atoms[0].taud[0] = initial; + SocketUtils::set_positions_from_ipi_bohr(cell, positions, true); + EXPECT_NEAR(cell.atoms[0].dis[0].x, 0.1, 1e-14); + EXPECT_NEAR(cell.atoms[0].dis[0].y, -0.1, 1e-14); +} + +TEST(SocketDriverTest, RejectedElectronicStepLeavesSolverUntouched) +{ + UnitCell cell; + initialize_one_atom_cell(cell); + Parameter parameters; + // Configuration comes from the explicit references, not the opaque handle. + Input_para input; + System_para system; + input.esolver_type = "ksdft"; + input.basis_type = "pw"; + input.device = "cpu"; + input.precision = "double"; + input.nspin = 1; + input.nbands = 8; + input.smearing_method = "gaussian"; + ControlledESolver solver(ElectronicFailure::None); + elecstate::ElectronicStep request; + request.parameters = ¶meters; + request.control.nelect = 8.25; + SocketCP::ScopedElectronicStep binding(&solver.electronic_step, &request); + + input.assume_isolated = "makov-payne"; + try + { + SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0); + FAIL() << "Makov-Payne request reached the solver"; + } + catch (const std::runtime_error &error) + { + EXPECT_THAT(error.what(), testing::HasSubstr("energy-only Makov-Payne")); + } + input.assume_isolated = "none"; + input.nbands = 4; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + input.nbands = 8; + input.smearing_method = "fixed"; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + for (double invalid : {7.0, 8.000000001, 7.999999999}) + { + request.control.nelect = invalid; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + } + input.nspin = 2; + request.control.nelect = 7.0; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + system.two_fermi = true; + input.nupdown = 1.0; + request.control.nelect = 8.0; // 4.5 up, 3.5 down + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + system.two_fermi = false; + input.nspin = 1; + input.nupdown = 0.0; + request.control.nelect = 8.25; + input.smearing_method = "gaussian"; + system.use_uspp = true; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + system.use_uspp = false; + system.two_fermi = true; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + system.two_fermi = false; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 0, 0), std::runtime_error); + + input.basis_type = "lcao"; + for (const char *backend : {"pexsi", "cusolver", "cusolvermp"}) + { + SCOPED_TRACE(backend); + input.ks_solver = backend; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + } + input.ks_solver = "lapack"; + input.dm_to_rho = true; + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0), std::runtime_error); + input.dm_to_rho = false; + EXPECT_EQ(0, solver.control_count); + EXPECT_EQ(0, solver.runner_count); + EXPECT_DOUBLE_EQ(0.0, solver.nelect); + EXPECT_FALSE(request.request_applied); + EXPECT_FALSE(request.result_ready); + EXPECT_DOUBLE_EQ(0.0, parameters.inp.nelec); + + SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0); + EXPECT_EQ(1, solver.control_count); + EXPECT_EQ(1, solver.runner_count); + EXPECT_DOUBLE_EQ(8.25, solver.nelect); + + EXPECT_TRUE(request.request_applied); + EXPECT_FALSE(request.result_ready); + EXPECT_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 1), std::runtime_error); + EXPECT_EQ(1, solver.runner_count); +} + +TEST(SocketDriverTest, FixedOccupationsAcceptFullBandsInEachRequestedChannel) +{ + UnitCell cell; + initialize_one_atom_cell(cell); + Parameter parameters; + Input_para input; + System_para system; + input.esolver_type = "ksdft"; + input.basis_type = "pw"; + input.device = "cpu"; + input.precision = "double"; + input.smearing_method = "fixed"; + input.nbands = 4; + + for (bool separate_fermi : {false, true}) + { + input.nspin = separate_fermi ? 2 : 1; + input.nupdown = separate_fermi ? 1.0 : 0.0; + system.two_fermi = separate_fermi; + ControlledESolver solver(ElectronicFailure::None); + elecstate::ElectronicStep request; + request.parameters = ¶meters; + request.control.nelect = separate_fermi ? 7.0 : 8.0; + SocketCP::ScopedElectronicStep binding(&solver.electronic_step, &request); + EXPECT_NO_THROW(SocketCP::run_electronic_step(solver, cell, request, input, system, 2, 0)); + EXPECT_EQ(1, solver.runner_count); + EXPECT_DOUBLE_EQ(request.control.nelect, solver.nelect); + } +} + +TEST(SocketDriverTest, PublicDriverBindsRequestAndReturnsWindowFeedback) +{ + const DriverResult result = run_constant_potential_session( + [](const int fd) + { + const double counts[] = {8.25, 7.75}; + const double positions[] = {0.0, 0.125}; + const std::string extras[] = {"\"nelect\":8.25", "\"nelect\":7.75"}; + for (int frame = 0; frame < 2; ++frame) + { + send_header(fd, "STATUS"); + EXPECT_EQ("READY", read_header_or_close(fd)); + send_charge(fd, counts[frame]); + send_header(fd, "STATUS"); + EXPECT_EQ("READY", read_header_or_close(fd)); + send_positions(fd, positions[frame]); + for (int query = 0; query < 2; ++query) + { + send_header(fd, "STATUS"); + EXPECT_EQ("HAVEDATA", read_header_or_close(fd)); + } + send_header(fd, "GETFORCE"); + const ForceResponse response = read_force_response(fd); + EXPECT_EQ("FORCEREADY", response.header); + EXPECT_DOUBLE_EQ((4.0 + positions[frame] + counts[frame]) * 0.5, response.energy_hartree); + ASSERT_EQ(3u, response.forces_hartree_per_bohr.size()); + EXPECT_DOUBLE_EQ(2.0 + positions[frame], response.forces_hartree_per_bohr[0]); + EXPECT_THAT(response.extra, testing::HasSubstr(extras[frame])); + EXPECT_THAT(response.extra, testing::HasSubstr("\"scf_converged\":true")); + EXPECT_DOUBLE_EQ( + 0.25 * ModuleBase::Ry_to_eV, read_extra_number(response.extra, "electrostatic_reference_eV")); + EXPECT_DOUBLE_EQ(0.375 * ModuleBase::Ry_to_eV, read_extra_number(response.extra, "workfunction_eV")); + } + send_header(fd, "STATUS"); + EXPECT_EQ("READY", read_header_or_close(fd)); + send_header(fd, "EXIT"); + EXPECT_EQ("", read_header_or_close(fd)); + }, + ElectronicFailure::None, + ",potential_average_axis:y,potential_average_min_A:0.125,potential_average_max_A:0.375"); EXPECT_EQ(0, result.exit_code); - EXPECT_THAT(response.extra, testing::HasSubstr("\"present\":[\"energy\"]")); - EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"forces\""))); - EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"stress\""))); - EXPECT_THAT(response.forces_hartree_per_bohr, testing::ElementsAre(0.0, 0.0, 0.0)); - EXPECT_THAT(response.virial_wire_hartree, testing::ElementsAre(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); + EXPECT_THAT(result.diagnostic, testing::HasSubstr("CP calls: 2 controls, 2 runners, 2 collections")); } -TEST(SocketDriverTest, EnergyAndStressFrameDoesNotAdvertiseForce) +TEST(SocketDriverTest, PublicDriverRejectsConstantPotentialInitForOrdinarySolver) { - ForceResponse response; - const DriverResult result = run_driver_frame( - true, false, true, - [&](const int fd) + const DriverResult result = run_constant_potential_session( + [](const int fd) { EXPECT_EQ("", read_header_or_close(fd)); }, ElectronicFailure::MissingSlot, ""); + EXPECT_NE(0, result.exit_code); + EXPECT_THAT(result.diagnostic, testing::HasSubstr("constant-potential socket requires an electronic request slot")); +} + +TEST(SocketDriverTest, ConstantPotentialPositionRequiresFreshCharge) +{ + const DriverResult result = run_constant_potential_session( + [](const int fd) + { + send_header(fd, "POSDATA"); + EXPECT_EQ("", read_header_or_close(fd)); + }, + ElectronicFailure::None, ""); + EXPECT_NE(0, result.exit_code); + EXPECT_THAT(result.diagnostic, testing::HasSubstr("constant-potential POSDATA requires one fresh CHGDATA")); +} + +TEST(SocketDriverTest, FailedElectronicFrameCannotReturnPreviousFeedback) +{ + const DriverResult result = run_constant_potential_session( + [](const int fd) { + send_charge(fd, 8.25); + send_positions(fd, 0.0); send_header(fd, "GETFORCE"); - response = read_force_response(fd); - }); + const ForceResponse first = read_force_response(fd); + EXPECT_EQ("FORCEREADY", first.header); + EXPECT_THAT(first.extra, testing::HasSubstr("\"nelect\":8.25")); + send_charge(fd, 7.75); + send_positions(fd, 0.125); + EXPECT_EQ("", read_header_or_close(fd)); + }, + ElectronicFailure::SecondFrame, ""); + EXPECT_NE(0, result.exit_code); + EXPECT_THAT(result.diagnostic, testing::HasSubstr("SCF did not converge")); +} - EXPECT_EQ("FORCEREADY", response.header); - EXPECT_EQ(0, result.exit_code); - EXPECT_THAT(response.extra, testing::HasSubstr("\"present\":[\"energy\",\"stress\"]")); - EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"forces\""))); - EXPECT_NE(0.0, response.virial_wire_hartree[0]); +TEST(SocketDriverTest, ConvergedSolverMustApplyRequestAndCompleteFeedback) +{ + const ElectronicFailure failures[] = {ElectronicFailure::IgnoreRequest, ElectronicFailure::MissingResult}; + for (const ElectronicFailure failure : failures) + { + const DriverResult result = run_constant_potential_session( + [](const int fd) + { + send_charge(fd, 8.25); + send_positions(fd, 0.0); + EXPECT_EQ("", read_header_or_close(fd)); + }, + failure, ""); + EXPECT_NE(0, result.exit_code); + const char *diagnostic = "did not complete this frame's electronic observables"; + if (failure == ElectronicFailure::IgnoreRequest) + { + diagnostic = "did not apply the constant-potential electron request"; + } + EXPECT_THAT(result.diagnostic, testing::HasSubstr(diagnostic)); +#ifdef __MPI + const char *fatal_stage = "ABACUS_SOCKET_MPI_FATAL stage=electronic_observables"; + if (failure == ElectronicFailure::IgnoreRequest) + { + fatal_stage = "ABACUS_SOCKET_MPI_FATAL stage=runner"; + } + EXPECT_THAT(result.diagnostic, testing::HasSubstr(fatal_stage)); +#endif + } +} + +TEST(SocketElectronicFrameTest, SerializationUsesPublishedSnapshotWithoutCollectingAgain) +{ + elecstate::ElectronicStep step; + step.request_applied = true; + step.result_ready = true; + step.result.nelect = 8.125; + step.result.fermi_ry = -0.125; + const SocketCP::Configuration config = SocketCP::parse_init("NELECT:8,neutral_electrons:8"); + SocketUtils::ComputedFrame frame; + frame.valid = true; + frame.forces_present = true; + frame.electronic = SocketCP::collect_observables(config, step); + frame.electronic_present = true; + step.result.nelect = 9.0; + step.result_ready = false; + const std::string first = SocketUtils::properties_extra(frame); + const std::string second = SocketUtils::properties_extra(frame); + EXPECT_EQ(first, second); + EXPECT_THAT(first, testing::HasSubstr("\"nelect\":8.125")); + EXPECT_THAT(first, testing::HasSubstr("\"present\":[\"energy\",\"forces\"]")); + EXPECT_THAT(first, testing::Not(testing::HasSubstr("workfunction_eV"))); } -TEST(SocketDriverTest, EnergyAndForceFrameAdvertisesOnlyForce) +TEST(SocketDriverTest, NonconvergedFrameIsPublishedWithMetadata) { ForceResponse response; const DriverResult result = run_driver_frame( - true, true, false, + false, true, false, [&](const int fd) { send_header(fd, "GETFORCE"); @@ -522,17 +913,27 @@ TEST(SocketDriverTest, EnergyAndForceFrameAdvertisesOnlyForce) EXPECT_EQ("FORCEREADY", response.header); EXPECT_EQ(0, result.exit_code); - EXPECT_THAT(response.extra, testing::HasSubstr("\"present\":[\"energy\",\"forces\"]")); - EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"stress\""))); - EXPECT_THAT(response.forces_hartree_per_bohr, testing::ElementsAre(2.0, 0.0, 0.0)); - EXPECT_THAT(response.virial_wire_hartree, testing::ElementsAre(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); + EXPECT_THAT(response.extra, testing::HasSubstr("\"scf_converged\":false")); } -TEST(SocketDriverTest, EnergyForceAndStressFrameAdvertisesBothDerivatives) +struct OrdinaryOutput +{ + bool cal_force; + bool cal_stress; + const char *name; + const char *present; +}; + +class SocketOrdinaryOutputTest : public testing::TestWithParam +{ +}; + +TEST_P(SocketOrdinaryOutputTest, PublicDriverReturnsRequestedProperties) { + const OrdinaryOutput &requested = GetParam(); ForceResponse response; const DriverResult result = run_driver_frame( - true, true, true, + true, requested.cal_force, requested.cal_stress, [&](const int fd) { send_header(fd, "GETFORCE"); @@ -541,15 +942,39 @@ TEST(SocketDriverTest, EnergyForceAndStressFrameAdvertisesBothDerivatives) EXPECT_EQ("FORCEREADY", response.header); EXPECT_EQ(0, result.exit_code); - EXPECT_THAT(response.extra, testing::HasSubstr("\"present\":[\"energy\",\"forces\",\"stress\"]")); - EXPECT_EQ(3u, response.forces_hartree_per_bohr.size()); - EXPECT_THAT(response.forces_hartree_per_bohr, testing::ElementsAre(2.0, 0.0, 0.0)); - EXPECT_NE(0.0, response.virial_wire_hartree[0]); + EXPECT_DOUBLE_EQ(2.0, response.energy_hartree); + EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"nelect\""))); + EXPECT_THAT(response.extra, testing::HasSubstr(requested.present)); + if (!requested.cal_force) + { + EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"forces\""))); + } + if (!requested.cal_stress) + { + EXPECT_THAT(response.extra, testing::Not(testing::HasSubstr("\"stress\""))); + } + const double force_x = requested.cal_force ? 2.0 : 0.0; + EXPECT_THAT(response.forces_hartree_per_bohr, testing::ElementsAre(force_x, 0.0, 0.0)); + const double diagonal_virial = requested.cal_stress ? 1.0 : 0.0; + EXPECT_THAT( + response.virial_wire_hartree, + testing::ElementsAre(diagonal_virial, 0.0, 0.0, 0.0, diagonal_virial, 0.0, 0.0, 0.0, diagonal_virial)); } +INSTANTIATE_TEST_SUITE_P( + ForceAndStress, + SocketOrdinaryOutputTest, + testing::Values( + OrdinaryOutput{false, false, "EnergyOnly", "\"present\":[\"energy\"]"}, + OrdinaryOutput{false, true, "EnergyAndStress", "\"present\":[\"energy\",\"stress\"]"}, + OrdinaryOutput{true, false, "EnergyAndForce", "\"present\":[\"energy\",\"forces\"]"}, + OrdinaryOutput{true, true, "EnergyForceAndStress", "\"present\":[\"energy\",\"forces\",\"stress\"]"}), + [](const testing::TestParamInfo &info) { return std::string(info.param.name); }); + TEST(SocketDriverTest, ConsecutiveFramesKeepGeometryResultsAndConvergenceTogether) { - ForceResponse first, second; + ForceResponse first; + ForceResponse second; const DriverResult result = run_driver_frame( true, true, true, [&](const int fd) @@ -586,6 +1011,62 @@ TEST(SocketDriverTest, ConsumedFrameCannotBeReturnedTwice) EXPECT_THAT(result.diagnostic, testing::HasSubstr("GETFORCE requires HAVEDATA")); } +TEST(SocketDriverTest, OrdinaryExitMayDiscardUnconsumedFrame) +{ + const DriverResult result = run_driver_frame( + true, true, false, + [&](const int fd) + { + send_header(fd, "STATUS"); + EXPECT_EQ("HAVEDATA", read_header_or_close(fd)); + send_header(fd, "EXIT"); + EXPECT_EQ("", read_header_or_close(fd)); + }); + EXPECT_EQ(0, result.exit_code); +} + +TEST(SocketDriverTest, ConstantPotentialExitRequiresCompletedRequest) +{ + enum class ExitState + { + UnreadResult, + PendingCharge, + Ready + }; + const ExitState states[] = {ExitState::UnreadResult, ExitState::PendingCharge, ExitState::Ready}; + for (const ExitState state : states) + { + const DriverResult result = run_constant_potential_session( + [&](const int fd) + { + if (state != ExitState::Ready) + { + send_charge(fd, 8.25); + } + const char *expected_status = "READY"; + if (state == ExitState::UnreadResult) + { + send_positions(fd, 0.0); + expected_status = "HAVEDATA"; + } + send_header(fd, "STATUS"); + EXPECT_EQ(expected_status, read_header_or_close(fd)); + send_header(fd, "EXIT"); + EXPECT_EQ("", read_header_or_close(fd)); + }, + ElectronicFailure::None, ""); + if (state == ExitState::Ready) + { + EXPECT_EQ(0, result.exit_code); + } + else + { + EXPECT_NE(0, result.exit_code); + EXPECT_THAT(result.diagnostic, testing::HasSubstr("EXIT with an unfinished request/result")); + } + } +} + TEST(SocketDriverTest, InvalidNextFrameCannotReturnPreviousResults) { const DriverResult result = run_driver_frame( @@ -603,9 +1084,7 @@ TEST(SocketDriverTest, InvalidNextFrameCannotReturnPreviousResults) int main(int argc, char **argv) { - MPI_Init(&argc, &argv); testing::InitGoogleTest(&argc, argv); const int result = RUN_ALL_TESTS(); - MPI_Finalize(); return result; }