From 5bdd4e0a23caa0a09f76739d29814f89eb457c73 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Wed, 2 Dec 2026 21:58:56 +0800 Subject: [PATCH 01/11] refactor(input): declare prerequisites beside parameter choices --- docs/developers_guide/input_validation.md | 38 +++++++++- .../module_parameter/input_domain.cpp | 50 ++++++++++++-- .../source_io/module_parameter/input_item.h | 12 ++++ .../module_parameter/read_inp_estruc.cpp | 8 +-- .../module_parameter/read_inp_sys.cpp | 7 +- .../module_parameter/test/CMakeLists.txt | 4 +- .../test => unittests}/test_input_domain.cpp | 69 +++++++++++++++++-- .../unittests/test_input_domain_reader.cpp | 42 +++++++++-- .../source_io/unittests/test_read_input.cmake | 28 +++++--- .../unittests/test_read_input_item.cpp | 22 +++--- .../unittests/test_read_input_serial.cpp | 8 +-- 11 files changed, 240 insertions(+), 48 deletions(-) rename source/source_io/{module_parameter/test => unittests}/test_input_domain.cpp (63%) diff --git a/docs/developers_guide/input_validation.md b/docs/developers_guide/input_validation.md index 2fdb64fb87e..83a3ef37084 100644 --- a/docs/developers_guide/input_validation.md +++ b/docs/developers_guide/input_validation.md @@ -8,7 +8,43 @@ with custom input syntax keep their own parsing rules. | --- | --- | | A fixed set of choices | `item.domain.set_choices({"cpu", "gpu"});` | | A numerical range | `item.domain.set_rule("value>0");` | -| A dependency on another parameter | `item.domain.add_requirement("device_xc==gpu", "device==gpu");` | +| A prerequisite for selecting an option | `item.add_choice_requirement("gpu", "device==gpu");` (in `device_xc`) | + +Register a prerequisite beside the option that introduces it. For example, in +the `basis_type` item: + +```cpp +item.add_choice_requirement("pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); +``` + +This is shorthand for `domain.add_requirement("basis_type==pw", requirement)`. +It reuses the condition parser, validation, and metadata export. Requirements +check the configuration; they do not assign defaults or reset parameters. +The prerequisite is shown under the selecting parameter in help and the manual. + +Use the existing expression syntax to describe allowed values. A parameter's +own range uses `value` in `domain.set_rule(...)`; a requirement names the +parameter it constrains: + +| Allowed values | Example expression | +| --- | --- | +| One value | `nspin==4` | +| Enumerated choices | `nspin in [1, 2, 4]` | +| Closed interval | `weight>=0 and weight<=1` | +| Open interval | `weight>0 and weight<1` | +| Half-open interval | `weight>=0 and weight<1` | +| Alternative ranges | `weight==-1 or (weight>=0 and weight<1)` | + +`weight` is an illustrative numeric parameter. Bounds in this syntax are +literals; expressions such as `weight clauses; + for (const AvailabilityExpr& child : expression.children) + { + std::string clause = format_condition(child); + if (!child.is_leaf()) { clause = "(" + clause + ")"; } + clauses.push_back(clause); + } + const std::string separator = " " + expression.op + " "; + return join(clauses, separator); +} + +std::string requirement_diagnostic(const std::string& owner, const InputRequirement& rule, + const InputValues& values) +{ + std::ostringstream out; + out << "ERROR: INPUT requirement not satisfied for '" << owner << "'.\n\n"; + const std::string when = format_condition(rule.when); + if (when.empty()) { out << "The following is required:\n"; } + else { out << "When " << when << ", the following is required:\n"; } + out << " " << format_condition(rule.require) << "\n\nCurrent settings:\n"; std::set references; collect_references(rule.when, references); collect_references(rule.require, references); - std::vector rendered; - for (const std::string& name : references) { rendered.push_back(name + "=" + values.at(name).format()); } - return join(rendered, ", "); + references.erase(owner); + std::vector names = {owner}; + names.insert(names.end(), references.begin(), references.end()); + for (const std::string& name : names) + { + const InputValues::const_iterator value = values.find(name); + if (value != values.end()) { out << " " << name << " = " << value->second.format() << '\n'; } + } + out << "\nDocumentation:\n"; + for (const std::string& name : names) { out << " " << input_manual_link(name) << '\n'; } + return out.str(); } } // namespace @@ -330,9 +368,7 @@ std::string InputDomain::validate_requirements(const std::string& label, const I { if (evaluate_input_condition(rule.when, values) && !evaluate_input_condition(rule.require, values)) { - const std::string actual = describe_values(values, rule); - const std::string expected = "Requires " + rule.require.to_string() + "."; - errors += input_diagnostic(label, actual, "configuration", expected); + errors += requirement_diagnostic(label, rule, values); } } return errors; diff --git a/source/source_io/module_parameter/input_item.h b/source/source_io/module_parameter/input_item.h index 3b168604980..62dda532e1e 100644 --- a/source/source_io/module_parameter/input_item.h +++ b/source/source_io/module_parameter/input_item.h @@ -52,6 +52,18 @@ class Input_Item std::string default_value; ///< default value as string std::string unit; ///< unit of measurement (empty if none) InputDomain domain; ///< shared runtime validation and legal-value metadata + + /// Declare the prerequisite for selecting one value of this parameter. + void add_choice_requirement(const std::string& choice, const std::string& require) + { + AvailabilityCondition selected; + selected.param = label; + selected.op = "=="; + selected.values = {choice}; + const std::string when = selected.to_string(); + domain.add_requirement(when, require); + } + /// Set and validate the canonical availability expression. An empty value /// means that the item is always available. void set_availability(const std::string& value) diff --git a/source/source_io/module_parameter/read_inp_estruc.cpp b/source/source_io/module_parameter/read_inp_estruc.cpp index ce58dd9caab..4dc2f7f5949 100644 --- a/source/source_io/module_parameter/read_inp_estruc.cpp +++ b/source/source_io/module_parameter/read_inp_estruc.cpp @@ -13,6 +13,8 @@ void ReadInput::item_elec_stru() { Input_Item item("basis_type"); item.domain.set_choices({"pw", "lcao", "lcao_in_pw"}); + item.add_choice_requirement("pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); + item.add_choice_requirement("lcao", "ks_solver in [genelpa, elpa, lapack, scalapack_gvx, cusolver, cusolvermp, pexsi]"); item.annotation = "PW; LCAO in pw; LCAO"; item.category = "Electronic structure"; item.type = "String"; @@ -38,9 +40,7 @@ void ReadInput::item_elec_stru() { Input_Item item("ks_solver"); item.domain.set_choices({"cg", "dav", "bpcg", "dav_subspace", "lobpcg", "genelpa", "elpa", "lapack", "scalapack_gvx", "cusolver", "cusolvermp", "pexsi"}); - item.domain.add_requirement("basis_type==pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); - item.domain.add_requirement("basis_type==lcao", "ks_solver in [genelpa, elpa, lapack, scalapack_gvx, cusolver, cusolvermp, pexsi]"); - item.domain.add_requirement("ks_solver==genelpa", "device==cpu"); + item.add_choice_requirement("genelpa", "device==cpu"); item.annotation = "cg; dav; dav_subspace; bpcg; lobpcg; lapack; genelpa; elpa; scalapack_gvx; cusolver; cusolvermp; pexsi"; item.category = "Electronic structure"; item.type = "String"; @@ -319,7 +319,7 @@ The other way is only available when compiling with LIBXC, and it allows for sup { Input_Item item("device_xc"); item.domain.set_choices({"cpu", "gpu"}); - item.domain.add_requirement("device_xc==gpu", "device==gpu"); + item.add_choice_requirement("gpu", "device==gpu"); item.annotation = "device for Libxc LDA/GGA potential evaluation"; item.category = "Electronic structure"; item.type = "String"; diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index 7544d0b9766..b8cee7596b9 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -146,8 +146,9 @@ void ReadInput::item_system() { Input_Item item("calculation"); item.domain.set_choices({"scf", "relax", "md", "cell-relax", "nscf", "get_s", "get_wf", "get_pchg", "gen_bessel", "gen_opt_abfs", "test_memory", "test_neighbour"}); - item.domain.add_requirement("calculation in [get_pchg, get_wf]", "basis_type!=pw"); - item.domain.add_requirement("calculation==gen_bessel", "basis_type==pw"); + item.add_choice_requirement("get_pchg", "basis_type!=pw"); + item.add_choice_requirement("get_wf", "basis_type!=pw"); + item.add_choice_requirement("gen_bessel", "basis_type==pw"); item.annotation = "scf; relax; md; cell-relax; nscf; get_s; get_wf; get_pchg; gen_bessel; gen_opt_abfs; test_memory; test_neighbour"; item.category = "System variables"; item.type = "String"; @@ -1053,7 +1054,7 @@ Available options are: { Input_Item item("precision"); item.domain.set_choices({"single", "double"}); - item.domain.add_requirement("precision==single", "basis_type!=lcao"); + item.add_choice_requirement("single", "basis_type!=lcao"); item.annotation = "the computing precision for ABACUS"; item.category = "System variables"; item.type = "String"; diff --git a/source/source_io/module_parameter/test/CMakeLists.txt b/source/source_io/module_parameter/test/CMakeLists.txt index 747d28d1bc8..8f18aba339e 100644 --- a/source/source_io/module_parameter/test/CMakeLists.txt +++ b/source/source_io/module_parameter/test/CMakeLists.txt @@ -5,5 +5,5 @@ addtest(TARGET MODULE_IO_availability ../availability_validator.cpp) addtest(TARGET MODULE_IO_input_domain - SOURCES test_input_domain.cpp ../input_domain.cpp ../availability.cpp - ../availability_validator.cpp) + SOURCES ../../unittests/test_input_domain.cpp ../input_domain.cpp + ../availability.cpp ../availability_validator.cpp) diff --git a/source/source_io/module_parameter/test/test_input_domain.cpp b/source/source_io/unittests/test_input_domain.cpp similarity index 63% rename from source/source_io/module_parameter/test/test_input_domain.cpp rename to source/source_io/unittests/test_input_domain.cpp index bc7adbb2ad6..36e087bd2ce 100644 --- a/source/source_io/module_parameter/test/test_input_domain.cpp +++ b/source/source_io/unittests/test_input_domain.cpp @@ -1,5 +1,6 @@ -#include "../input_domain.h" -#include "../input_parameter.h" +#include "source_io/module_parameter/input_domain.h" +#include "source_io/module_parameter/input_item.h" +#include "source_io/module_parameter/input_parameter.h" #include #include @@ -110,9 +111,9 @@ TEST(InputDomain, SharedConditionsAndDependencyDiagnostics) ModuleIO::InputDomain domain; domain.add_requirement("noncolin==true", "nspin==4"); const auto error = domain.validate_requirements("nspin", values); - EXPECT_NE(error.find("noncolin=true"), std::string::npos); - EXPECT_NE(error.find("nspin=2"), std::string::npos); - EXPECT_NE(error.find("Requires nspin==4"), std::string::npos); + EXPECT_NE(error.find("noncolin = true"), std::string::npos); + EXPECT_NE(error.find("nspin = 2"), std::string::npos); + EXPECT_NE(error.find("When noncolin = true, the following is required:\n nspin = 4"), std::string::npos); EXPECT_NE(error.find("input-main.html#nspin"), std::string::npos); EXPECT_THROW(domain.validate_schema("nspin", {}), std::invalid_argument); } @@ -142,3 +143,61 @@ TEST(InputDomain, RejectsNonfiniteRuleLiteralsAndVectorScalarComparisons) vector_domain.add_requirement("axes==1", "flag==true"); EXPECT_THROW(vector_domain.validate_schema("bad_vector", types), std::invalid_argument); } + +TEST(InputDomain, ChoiceRequirementsCheckRangesAndAlternatives) +{ + ModuleIO::Input_Item item("mode"); + item.add_choice_requirement("bounded", "weight>=0 and weight<1"); + item.add_choice_requirement("optional", "weight==-1 or (weight>=0 and weight<1)"); + const std::map types = { + {"mode", ModuleIO::AvailabilityValueKind::String}, {"weight", ModuleIO::AvailabilityValueKind::Real}}; + EXPECT_NO_THROW(item.domain.validate_schema(item.label, types)); + for (const std::string mode : {"bounded", "optional", "unrestricted"}) + { + for (const double weight : {-1.0, -0.1, 0.0, 0.5, 1.0}) + { + const ModuleIO::InputValues values = { + {"mode", ModuleIO::InputValue(mode)}, {"weight", ModuleIO::InputValue(weight)}}; + const bool accepted = mode == "unrestricted" || (weight >= 0 && weight < 1) + || (mode == "optional" && weight == -1); + const std::string error = item.domain.validate_requirements(item.label, values); + EXPECT_EQ(error.empty(), accepted) << mode << ": " << weight; + EXPECT_EQ(values.at("weight").numbers.front(), weight); + } + } + const ModuleIO::InputValues invalid = { + {"mode", ModuleIO::InputValue(std::string("optional"))}, {"weight", ModuleIO::InputValue(2.0)}}; + const std::string error = item.domain.validate_requirements(item.label, invalid); + EXPECT_NE(error.find("weight = -1 or (weight >= 0 and weight < 1)"), std::string::npos); +} + +TEST(InputDomain, ChoiceRequirementGeneratesContextValuesAndManualLinks) +{ + ModuleIO::Input_Item item("basis_type"); + item.add_choice_requirement("pw", "ks_solver in [cg, dav]"); + const ModuleIO::InputValues values = { + {"basis_type", ModuleIO::InputValue(std::string("pw"))}, + {"ks_solver", ModuleIO::InputValue(std::string("lapack"))}, {"unrelated", ModuleIO::InputValue(42)}}; + const std::string expected = + "ERROR: INPUT requirement not satisfied for 'basis_type'.\n\n" + "When basis_type = pw, the following is required:\n" + " ks_solver in [cg, dav]\n\n" + "Current settings:\n" + " basis_type = pw\n" + " ks_solver = lapack\n\n" + "Documentation:\n" + " https://abacus.deepmodeling.com/en/latest/advanced/input_files/input-main.html#basis-type\n" + " https://abacus.deepmodeling.com/en/latest/advanced/input_files/input-main.html#ks-solver\n"; + EXPECT_EQ(item.domain.validate_requirements(item.label, values), expected); + EXPECT_EQ(item.domain.format_requirements(), "When basis_type==pw: require ks_solver in [cg, dav]"); +} + +TEST(InputDomain, ChoiceRequirementQuotesTheSelectedValue) +{ + ModuleIO::Input_Item item("mode"); + item.add_choice_requirement("x==y", "flag==true"); + const ModuleIO::InputValues values = { + {"mode", ModuleIO::InputValue(std::string("x==y"))}, {"flag", ModuleIO::InputValue(false)}}; + const std::string error = item.domain.validate_requirements(item.label, values); + EXPECT_NE(error.find("When mode = \"x==y\", the following is required:\n flag = true"), std::string::npos); +} diff --git a/source/source_io/unittests/test_input_domain_reader.cpp b/source/source_io/unittests/test_input_domain_reader.cpp index 5074623329d..b3c1a9206b7 100644 --- a/source/source_io/unittests/test_input_domain_reader.cpp +++ b/source/source_io/unittests/test_input_domain_reader.cpp @@ -409,7 +409,7 @@ TEST_F(InputDomainReaderTest, RejectsMissingStringChoiceAtEndOfFile) TEST_F(InputDomainReaderTest, RetainsExistingSpinDependencyCheck) { const std::string output = reject_input("nspin 2\nnoncolin 1\n"); - EXPECT_NE(output.find("Requires nspin==4"), std::string::npos); + EXPECT_NE(output.find("the following is required:\n nspin = 4"), std::string::npos); } TEST_F(InputDomainReaderTest, RejectsPrivateSentinelsBeforeDefaultResolution) @@ -455,13 +455,15 @@ TEST_F(InputDomainReaderTest, ChecksTypesRangesAndDependenciesThroughOnePath) for (const std::pair& example : invalid) { const std::string output = reject_input(example.first + "\n"); - EXPECT_NE(output.find("Invalid INPUT parameter"), std::string::npos) << example.first; + const bool domain_error = output.find("Invalid INPUT parameter") != std::string::npos; + const bool requirement_error = output.find("ERROR: INPUT requirement not satisfied for") != std::string::npos; + EXPECT_TRUE(domain_error || requirement_error) << example.first; EXPECT_NE(output.find("input-main.html#" + example.second), std::string::npos) << example.first; } // The legacy nupdown reset used to erase this conflicting explicit value. const std::string output = reject_input("nupdown 1\nnspin 1\n"); - EXPECT_NE(output.find("nupdown=1"), std::string::npos); - EXPECT_NE(output.find("Requires nupdown==0"), std::string::npos); + EXPECT_NE(output.find("nupdown = 1"), std::string::npos); + EXPECT_NE(output.find("the following is required:\n nupdown = 0"), std::string::npos); } TEST_F(InputDomainReaderTest, PreservesDisabledModesNegativePhysicsAndInactiveSwitches) @@ -490,6 +492,32 @@ TEST_F(InputDomainReaderTest, PreservesDisabledModesNegativePhysicsAndInactiveSw EXPECT_EQ(restored.mdp.md_plast, -1); } +TEST_F(InputDomainReaderTest, ChoiceRequirementsReportTheSelectingParameter) +{ + const std::string solver = reject_input("ks_solver lapack\n"); + EXPECT_NE(solver.find("INPUT requirement not satisfied for 'basis_type'"), std::string::npos); + EXPECT_NE(solver.find("When basis_type = pw, the following is required:\n ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"), + std::string::npos); + EXPECT_NE(solver.find("ks_solver = lapack"), std::string::npos); + EXPECT_NE(solver.find("input-main.html#basis-type"), std::string::npos); + EXPECT_NE(solver.find("input-main.html#ks-solver"), std::string::npos); + + const std::string precision = reject_input("precision single\n", "lcao"); + EXPECT_NE(precision.find("When precision = single, the following is required:\n basis_type != lcao"), + std::string::npos); + const std::string calculation = reject_input("calculation get_wf\n"); + EXPECT_NE(calculation.find("When calculation = get_wf, the following is required:\n basis_type != pw"), + std::string::npos); + + write_input("ks_solver dav\nprecision double\n"); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.ks_solver, "dav"); + EXPECT_EQ(input.inp.precision, "double"); +} + TEST(InputDomainHelp, ExportsTheRuntimeRules) { const ModuleIO::ParameterMetadata spin = ModuleIO::ParameterHelp::get_metadata("nspin"); @@ -508,6 +536,12 @@ TEST(InputDomainHelp, ExportsTheRuntimeRules) const ModuleIO::ParameterMetadata criterion = ModuleIO::ParameterHelp::get_metadata("scf_thr_type"); EXPECT_EQ(criterion.allowed_values, "1, 2"); EXPECT_NE(spin.requirements.find("nspin==4"), std::string::npos); + const ModuleIO::ParameterMetadata basis = ModuleIO::ParameterHelp::get_metadata("basis_type"); + EXPECT_NE(basis.requirements.find("When basis_type==pw: require ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"), + std::string::npos); + EXPECT_NE(dump.find(basis.requirements), std::string::npos); + const ModuleIO::ParameterMetadata solver = ModuleIO::ParameterHelp::get_metadata("ks_solver"); + EXPECT_EQ(solver.requirements, "When ks_solver==genelpa: require device==cpu"); } } // namespace diff --git a/source/source_io/unittests/test_read_input.cmake b/source/source_io/unittests/test_read_input.cmake index 26e4086cce0..56489ec280d 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -29,23 +29,30 @@ elseif(INPUT_CASE STREQUAL "invalid_value") set(expected_manual "input-main.html#nspin") elseif(INPUT_CASE STREQUAL "invalid_dependency") string(APPEND contents "nspin 2\nnoncolin true\n") - set(expected "Requires nspin==4") + set(expected "the following is required:\n nspin = 4") set(expected_manual "input-main.html#nspin") elseif(INPUT_CASE STREQUAL "unsupported_libxc_cuda") string(APPEND contents "device gpu\ndevice_xc gpu\n") - set(expected "device_xc gpu requires ABACUS built with -DENABLE_LIBXC_CUDA=ON.") + set(expected + "device_xc gpu requires ABACUS built with -DENABLE_LIBXC_CUDA=ON.") set(expected_manual "input-main.html#device-xc") elseif(INPUT_CASE STREQUAL "out_dmk_zero_precision") string(APPEND contents "out_dmk 1 0\n") - set(expected "Invalid INPUT parameter 'out_dmk': precision must be a positive integer.") + set(expected + "Invalid INPUT parameter 'out_dmk': precision must be a positive integer." + ) set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_hsk_zero_precision") string(APPEND contents "out_hsk 1 0\n") - set(expected "Invalid INPUT parameter 'out_hsk': precision must be a positive integer.") + set(expected + "Invalid INPUT parameter 'out_hsk': precision must be a positive integer." + ) set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_tk_zero_precision") string(APPEND contents "out_mat_tk 1 0\n") - set(expected "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer.") + set(expected + "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer." + ) set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_p_invalid_boolean") string(APPEND contents "out_mat_p maybe\n") @@ -75,7 +82,9 @@ elseif(INPUT_CASE MATCHES "^dftu_alpha_") set(expected "Invalid INPUT parameter 'dftu_alpha'") set(expected_manual "input-main.html#dftu-alpha") elseif(INPUT_CASE MATCHES "^dftu_") - set(contents "INPUT_PARAMETERS\nsuffix dftu_dc_bcast\nntype 1\nbasis_type lcao\nks_solver genelpa\ndft_functional PBE\nsymmetry 0\ndft_plus_u 1\norbital_corr 2\nhubbard_u 2\nnspin 2\necutwfc 100\n") + set(contents + "INPUT_PARAMETERS\nsuffix dftu_dc_bcast\nntype 1\nbasis_type lcao\nks_solver genelpa\ndft_functional PBE\nsymmetry 0\ndft_plus_u 1\norbital_corr 2\nhubbard_u 2\nnspin 2\necutwfc 100\n" + ) if(INPUT_CASE STREQUAL "dftu_default") set(expected_dc "fll 1") elseif(INPUT_CASE STREQUAL "dftu_fll") @@ -136,9 +145,12 @@ if(expected_exit EQUAL 1) endforeach() endif() if(DEFINED expected_dc) - string(REGEX MATCHALL "DFTU DC received: ${expected_dc}[\r\n]" received "${output}") + string(REGEX MATCHALL "DFTU DC received: ${expected_dc}[\r\n]" received + "${output}") list(LENGTH received received_count) if(NOT received_count EQUAL 4) - message(FATAL_ERROR "Only ${received_count} of 4 ranks received ${expected_dc}:\n${output}") + message( + FATAL_ERROR + "Only ${received_count} of 4 ranks received ${expected_dc}:\n${output}") endif() endif() diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 293ae1addc0..377e03763f1 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -336,18 +336,18 @@ TEST_F(InputTest, RejectInvalidMemSaver) testing::internal::CaptureStdout(); EXPECT_EXIT(reader.read_parameters(param, filename), testing::ExitedWithCode(1), ""); const std::string diagnostic = testing::internal::GetCapturedStdout(); - const std::string invalid_value = "Invalid INPUT parameter 'mem_saver'"; - EXPECT_THAT(diagnostic, testing::HasSubstr(invalid_value)); EXPECT_THAT(diagnostic, testing::HasSubstr("input-main.html#mem-saver")); if (value == 1) { - EXPECT_THAT(diagnostic, testing::HasSubstr("mem_saver=1")); - const std::string invalid_mode = "calculation=" + calculation; + EXPECT_THAT(diagnostic, testing::HasSubstr("INPUT requirement not satisfied for 'mem_saver'")); + EXPECT_THAT(diagnostic, testing::HasSubstr("mem_saver = 1")); + const std::string invalid_mode = "calculation = " + calculation; EXPECT_THAT(diagnostic, testing::HasSubstr(invalid_mode)); - EXPECT_THAT(diagnostic, testing::HasSubstr("Requires mem_saver==0")); + EXPECT_THAT(diagnostic, testing::HasSubstr("the following is required:\n mem_saver = 0")); } else { + EXPECT_THAT(diagnostic, testing::HasSubstr("Invalid INPUT parameter 'mem_saver'")); const std::string supplied = "supplied '" + std::to_string(value) + "'"; EXPECT_THAT(diagnostic, testing::HasSubstr(supplied)); EXPECT_THAT(diagnostic, testing::HasSubstr("from {0, 1}")); @@ -1192,7 +1192,7 @@ TEST_F(InputTest, Item_test) testing::internal::CaptureStdout(); EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); - EXPECT_THAT(output, testing::HasSubstr("Requires device==cpu")); + EXPECT_THAT(output, testing::HasSubstr("the following is required:\n device = cpu")); #ifdef __ELPA TestParameters::input(param).towannier90 = true; TestParameters::input(param).basis_type = "lcao_in_pw"; @@ -1218,17 +1218,19 @@ TEST_F(InputTest, Item_test) TestParameters::input(param).ks_solver = "genelpa"; TestParameters::input(param).basis_type = "pw"; + std::vector>::iterator basis + = find_label("basis_type", readinput.input_lists); testing::internal::CaptureStdout(); - EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); + EXPECT_EXIT(check_item(basis->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); - EXPECT_THAT(output, testing::HasSubstr("NOTICE")); + EXPECT_THAT(output, testing::HasSubstr("When basis_type = pw, the following is required:")); TestParameters::input(param).ks_solver = "cg"; TestParameters::input(param).basis_type = "lcao"; testing::internal::CaptureStdout(); - EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); + EXPECT_EXIT(check_item(basis->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); - EXPECT_THAT(output, testing::HasSubstr("NOTICE")); + EXPECT_THAT(output, testing::HasSubstr("When basis_type = lcao, the following is required:")); TestParameters::input(param).ks_solver = "scalapack_gvx"; TestParameters::input(param).basis_type = "lcao"; diff --git a/source/source_io/unittests/test_read_input_serial.cpp b/source/source_io/unittests/test_read_input_serial.cpp index 5b02dc4a9bb..3654e67c296 100644 --- a/source/source_io/unittests/test_read_input_serial.cpp +++ b/source/source_io/unittests/test_read_input_serial.cpp @@ -319,13 +319,13 @@ TEST_F(InputTest, ValidateNoncollinearSpin) expect_invalid_input("noncolin_missing_nspin_INPUT", "noncolin 1\n", - "Requires nspin==4"); + "the following is required:\n nspin = 4"); expect_invalid_input("noncolin_invalid_nspin_INPUT", "noncolin 1\nnspin 2\n", - "Requires nspin==4"); + "the following is required:\n nspin = 4"); expect_invalid_input("soc_missing_nspin_INPUT", "lspinorb 1\n", - "Requires nspin==4"); + "the following is required:\n nspin = 4"); } TEST_F(InputTest, ValidateSdftStochasticBands) @@ -435,7 +435,7 @@ TEST_F(InputTest, ValidateDeepksOutputFrequency) "Invalid INPUT parameter 'deepks_out_freq_elec': supplied '-1'. Expected one Integer satisfying value>=0."); expect_invalid_input("deepks_freq_missing_base_INPUT", "deepks_out_freq_elec 2\n", - "Requires deepks_out_base!=none"); + "the following is required:\n deepks_out_base != none"); Parameter enabled_param; testing::internal::CaptureStdout(); From a4bdc0ec6db815a335cdfb021587f61e62e32933 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Wed, 2 Dec 2026 22:33:24 +0800 Subject: [PATCH 02/11] refactor(input): resolve force and BSE choice requirements centrally --- docs/developers_guide/input_validation.md | 47 ++----- .../module_parameter/input_domain.cpp | 68 +++++---- .../source_io/module_parameter/input_domain.h | 3 + .../source_io/module_parameter/input_item.h | 4 +- .../module_parameter/read_inp_bse.cpp | 7 +- .../module_parameter/read_inp_estruc.cpp | 8 +- .../module_parameter/read_inp_sys.cpp | 37 ++--- .../source_io/module_parameter/read_input.cpp | 31 +++++ .../source_io/module_parameter/read_input.h | 3 + source/source_io/unittests/CMakeLists.txt | 9 +- .../source_io/unittests/test_input_domain.cpp | 84 ++++------- .../unittests/test_input_domain_reader.cpp | 131 +++++++++++++----- .../source_io/unittests/test_read_input.cmake | 22 ++- .../source_io/unittests/test_read_input.cpp | 4 + .../unittests/test_read_input_item.cpp | 86 +++++++----- .../unittests/test_read_input_serial.cpp | 10 +- 16 files changed, 310 insertions(+), 244 deletions(-) diff --git a/docs/developers_guide/input_validation.md b/docs/developers_guide/input_validation.md index 83a3ef37084..6d67f25833b 100644 --- a/docs/developers_guide/input_validation.md +++ b/docs/developers_guide/input_validation.md @@ -8,43 +8,16 @@ with custom input syntax keep their own parsing rules. | --- | --- | | A fixed set of choices | `item.domain.set_choices({"cpu", "gpu"});` | | A numerical range | `item.domain.set_rule("value>0");` | -| A prerequisite for selecting an option | `item.add_choice_requirement("gpu", "device==gpu");` (in `device_xc`) | - -Register a prerequisite beside the option that introduces it. For example, in -the `basis_type` item: - -```cpp -item.add_choice_requirement("pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); -``` - -This is shorthand for `domain.add_requirement("basis_type==pw", requirement)`. -It reuses the condition parser, validation, and metadata export. Requirements -check the configuration; they do not assign defaults or reset parameters. -The prerequisite is shown under the selecting parameter in help and the manual. - -Use the existing expression syntax to describe allowed values. A parameter's -own range uses `value` in `domain.set_rule(...)`; a requirement names the -parameter it constrains: - -| Allowed values | Example expression | -| --- | --- | -| One value | `nspin==4` | -| Enumerated choices | `nspin in [1, 2, 4]` | -| Closed interval | `weight>=0 and weight<=1` | -| Open interval | `weight>0 and weight<1` | -| Half-open interval | `weight>=0 and weight<1` | -| Alternative ranges | `weight==-1 or (weight>=0 and weight<1)` | - -`weight` is an illustrative numeric parameter. Bounds in this syntax are -literals; expressions such as `weight& defaults) { - if (expression.is_leaf()) + if (expression.is_leaf() && expression.condition.op == "==" + && !evaluate_input_condition(expression, values)) { - AvailabilityCondition condition = expression.condition; - if (condition.op == "==") { condition.op = " = "; } - else if (condition.op != "in" && condition.op != "contains") - { - condition.op = " " + condition.op + " "; - } - return condition.to_string(); + defaults.push_back(expression.condition); } - std::vector clauses; - for (const AvailabilityExpr& child : expression.children) + if (expression.op == "and") { - std::string clause = format_condition(child); - if (!child.is_leaf()) { clause = "(" + clause + ")"; } - clauses.push_back(clause); + for (const AvailabilityExpr& child : expression.children) { collect_equalities(child, values, defaults); } } - const std::string separator = " " + expression.op + " "; - return join(clauses, separator); } -std::string requirement_diagnostic(const std::string& owner, const InputRequirement& rule, - const InputValues& values) +std::string describe_values(const InputValues& values, const InputRequirement& rule) { - std::ostringstream out; - out << "ERROR: INPUT requirement not satisfied for '" << owner << "'.\n\n"; - const std::string when = format_condition(rule.when); - if (when.empty()) { out << "The following is required:\n"; } - else { out << "When " << when << ", the following is required:\n"; } - out << " " << format_condition(rule.require) << "\n\nCurrent settings:\n"; std::set references; collect_references(rule.when, references); collect_references(rule.require, references); - references.erase(owner); - std::vector names = {owner}; - names.insert(names.end(), references.begin(), references.end()); - for (const std::string& name : names) - { - const InputValues::const_iterator value = values.find(name); - if (value != values.end()) { out << " " << name << " = " << value->second.format() << '\n'; } - } - out << "\nDocumentation:\n"; - for (const std::string& name : names) { out << " " << input_manual_link(name) << '\n'; } - return out.str(); + std::vector rendered; + for (const std::string& name : references) { rendered.push_back(name + "=" + values.at(name).format()); } + return join(rendered, ", "); } } // namespace @@ -255,12 +231,30 @@ void InputDomain::set_rule(const std::string& rule) } void InputDomain::set_active_when(const std::string& condition) { active_when_ = parse_availability(condition); } void InputDomain::add_requirement(const std::string& when, const std::string& require) +{ + add_requirement(when, require, false); +} +void InputDomain::add_requirement(const std::string& when, const std::string& require, const bool resolve_defaults) { InputRequirement rule; rule.when = parse_availability(when); rule.require = parse_availability(require); + rule.resolve_defaults = resolve_defaults; requirements_.push_back(rule); } + +std::vector InputDomain::choice_defaults(const InputValues& values) const +{ + std::vector defaults; + for (const InputRequirement& rule : requirements_) + { + if (rule.resolve_defaults && evaluate_input_condition(rule.when, values)) + { + collect_equalities(rule.require, values, defaults); + } + } + return defaults; +} bool InputDomain::empty() const { return !scalar_; } bool InputDomain::bound() const { return static_cast(getter_); } bool InputDomain::can_write(const Parameter& input) const @@ -368,7 +362,9 @@ std::string InputDomain::validate_requirements(const std::string& label, const I { if (evaluate_input_condition(rule.when, values) && !evaluate_input_condition(rule.require, values)) { - errors += requirement_diagnostic(label, rule, values); + const std::string actual = describe_values(values, rule); + const std::string expected = "Requires " + rule.require.to_string() + "."; + errors += input_diagnostic(label, actual, "configuration", expected); } } return errors; diff --git a/source/source_io/module_parameter/input_domain.h b/source/source_io/module_parameter/input_domain.h index dbf0bf7c42e..7fce168dc79 100644 --- a/source/source_io/module_parameter/input_domain.h +++ b/source/source_io/module_parameter/input_domain.h @@ -38,6 +38,7 @@ struct InputRequirement { AvailabilityExpr when; AvailabilityExpr require; + bool resolve_defaults = false; }; class InputDomain @@ -52,6 +53,8 @@ class InputDomain // Only effective defaults may be inactive; explicit input is always checked. void set_active_when(const std::string& condition); void add_requirement(const std::string& when, const std::string& require); + void add_requirement(const std::string& when, const std::string& require, bool resolve_defaults); + std::vector choice_defaults(const InputValues& values) const; bool empty() const; bool bound() const; diff --git a/source/source_io/module_parameter/input_item.h b/source/source_io/module_parameter/input_item.h index 62dda532e1e..c04cd485641 100644 --- a/source/source_io/module_parameter/input_item.h +++ b/source/source_io/module_parameter/input_item.h @@ -53,7 +53,7 @@ class Input_Item std::string unit; ///< unit of measurement (empty if none) InputDomain domain; ///< shared runtime validation and legal-value metadata - /// Declare the prerequisite for selecting one value of this parameter. + /// Require a configuration for this choice; fixed equalities fill omitted values. void add_choice_requirement(const std::string& choice, const std::string& require) { AvailabilityCondition selected; @@ -61,7 +61,7 @@ class Input_Item selected.op = "=="; selected.values = {choice}; const std::string when = selected.to_string(); - domain.add_requirement(when, require); + domain.add_requirement(when, require, true); } /// Set and validate the canonical availability expression. An empty value diff --git a/source/source_io/module_parameter/read_inp_bse.cpp b/source/source_io/module_parameter/read_inp_bse.cpp index 9685973acd8..52b5ba53a28 100644 --- a/source/source_io/module_parameter/read_inp_bse.cpp +++ b/source/source_io/module_parameter/read_inp_bse.cpp @@ -42,16 +42,13 @@ void ReadInput::item_bse() } { Input_Item item("bse_mem_save"); + item.add_choice_requirement("true", "bse_continue==0 and bse_ri_hartree==true"); item.annotation = "whether to save memory by adding V and W to BSE matrix directly"; item.category = "Bethe-Salpeter Equation"; item.type = "Boolean"; item.description - = "Whether to save memory by adding V and W directly to the BSE matrix. When enabled, " - "bse_ri_hartree is enabled and bse_continue is reset to 0."; + = "Whether to save memory by adding V and W directly to the BSE matrix."; item.default_value = "false"; - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.bse_mem_save == true) { para.input.bse_continue=0; para.input.bse_ri_hartree=true; } - }; read_sync_bool(input.bse_mem_save); this->add_item(item); } diff --git a/source/source_io/module_parameter/read_inp_estruc.cpp b/source/source_io/module_parameter/read_inp_estruc.cpp index 4dc2f7f5949..ce58dd9caab 100644 --- a/source/source_io/module_parameter/read_inp_estruc.cpp +++ b/source/source_io/module_parameter/read_inp_estruc.cpp @@ -13,8 +13,6 @@ void ReadInput::item_elec_stru() { Input_Item item("basis_type"); item.domain.set_choices({"pw", "lcao", "lcao_in_pw"}); - item.add_choice_requirement("pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); - item.add_choice_requirement("lcao", "ks_solver in [genelpa, elpa, lapack, scalapack_gvx, cusolver, cusolvermp, pexsi]"); item.annotation = "PW; LCAO in pw; LCAO"; item.category = "Electronic structure"; item.type = "String"; @@ -40,7 +38,9 @@ void ReadInput::item_elec_stru() { Input_Item item("ks_solver"); item.domain.set_choices({"cg", "dav", "bpcg", "dav_subspace", "lobpcg", "genelpa", "elpa", "lapack", "scalapack_gvx", "cusolver", "cusolvermp", "pexsi"}); - item.add_choice_requirement("genelpa", "device==cpu"); + item.domain.add_requirement("basis_type==pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); + item.domain.add_requirement("basis_type==lcao", "ks_solver in [genelpa, elpa, lapack, scalapack_gvx, cusolver, cusolvermp, pexsi]"); + item.domain.add_requirement("ks_solver==genelpa", "device==cpu"); item.annotation = "cg; dav; dav_subspace; bpcg; lobpcg; lapack; genelpa; elpa; scalapack_gvx; cusolver; cusolvermp; pexsi"; item.category = "Electronic structure"; item.type = "String"; @@ -319,7 +319,7 @@ The other way is only available when compiling with LIBXC, and it allows for sup { Input_Item item("device_xc"); item.domain.set_choices({"cpu", "gpu"}); - item.add_choice_requirement("gpu", "device==gpu"); + item.domain.add_requirement("device_xc==gpu", "device==gpu"); item.annotation = "device for Libxc LDA/GGA potential evaluation"; item.category = "Electronic structure"; item.type = "String"; diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index b8cee7596b9..8b3f47b3d92 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -146,9 +146,16 @@ void ReadInput::item_system() { Input_Item item("calculation"); item.domain.set_choices({"scf", "relax", "md", "cell-relax", "nscf", "get_s", "get_wf", "get_pchg", "gen_bessel", "gen_opt_abfs", "test_memory", "test_neighbour"}); - item.add_choice_requirement("get_pchg", "basis_type!=pw"); - item.add_choice_requirement("get_wf", "basis_type!=pw"); - item.add_choice_requirement("gen_bessel", "basis_type==pw"); + for (const std::string& choice : {"md", "relax", "cell-relax"}) + { + item.add_choice_requirement(choice, "cal_force==true"); + } + for (const std::string& choice : {"get_wf", "get_pchg", "get_s"}) + { + item.add_choice_requirement(choice, "cal_force==false"); + } + item.domain.add_requirement("calculation in [get_pchg, get_wf]", "basis_type!=pw"); + item.domain.add_requirement("calculation==gen_bessel", "basis_type==pw"); item.annotation = "scf; relax; md; cell-relax; nscf; get_s; get_wf; get_pchg; gen_bessel; gen_opt_abfs; test_memory; test_neighbour"; item.category = "System variables"; item.type = "String"; @@ -425,28 +432,10 @@ Socket mode always computes energy. Force and stress extraction follows cal_forc item.category = "System variables"; item.type = "Boolean"; item.description = R"(If set to True, calculate the force at the end of the electronic iteration. +See calculation requirements for the value required by each calculation type. +If omitted, the required value is used; an explicit conflicting value is rejected. In socket_driver mode, this flag controls whether the returned frame advertises forces; it is not forced on by the socket protocol.)"; item.default_value = "False"; - item.reset_value = [](const Input_Item& item, Parameter& para) { - std::vector use_force = {"cell-relax", "relax", "md"}; - std::vector not_use_force = {"get_wf", "get_pchg", "get_s"}; - if (std::find(use_force.begin(), use_force.end(), para.input.calculation) != use_force.end()) - { - if (!para.input.cal_force) - { - ModuleBase::GlobalFunc::AUTO_SET("cal_force", "true"); - } - para.input.cal_force = true; - } - else if (std::find(not_use_force.begin(), not_use_force.end(), para.input.calculation) != not_use_force.end()) - { - if (para.input.cal_force) - { - ModuleBase::GlobalFunc::AUTO_SET("cal_force", "false"); - } - para.input.cal_force = false; - } - }; read_sync_bool(input.cal_force); this->add_item(item); } @@ -1054,7 +1043,7 @@ Available options are: { Input_Item item("precision"); item.domain.set_choices({"single", "double"}); - item.add_choice_requirement("single", "basis_type!=lcao"); + item.domain.add_requirement("precision==single", "basis_type!=lcao"); item.annotation = "the computing precision for ABACUS"; item.category = "System variables"; item.type = "String"; diff --git a/source/source_io/module_parameter/read_input.cpp b/source/source_io/module_parameter/read_input.cpp index 02afc382d47..3d076ac5532 100644 --- a/source/source_io/module_parameter/read_input.cpp +++ b/source/source_io/module_parameter/read_input.cpp @@ -484,6 +484,12 @@ std::string ReadInput::read_txt_input(Parameter& param, const std::string& filen return this->prepare_input(param); } +bool ReadInput::is_explicit(const std::string& label) const +{ + return std::any_of(readvalue_items.begin(), readvalue_items.end(), + [&label](const Input_Item* item) { return item->label == label; }); +} + std::string ReadInput::prepare_input(Parameter& param) { // Validate original tokens before any reader or default hook can discard @@ -611,6 +617,31 @@ std::string ReadInput::prepare_input(Parameter& param) { requested_values[supplied.first] = supplied.second; } + + // Select rules from one snapshot, then fill omitted scalar values through + // their existing readers. Do not record these generated values as explicit. + std::vector defaults; + for (const std::pair& entry : this->input_lists) + { + const std::vector required = entry.second.domain.choice_defaults(requested_values); + defaults.insert(defaults.end(), required.begin(), required.end()); + } + for (const AvailabilityCondition& required : defaults) + { + if (is_explicit(required.param)) { continue; } + const std::vector>::const_iterator target = std::find_if( + input_lists.begin(), input_lists.end(), + [&required](const std::pair& entry) { return entry.first == required.param; }); + Input_Item default_input(target->second); + default_input.str_values = required.values; + default_input.read_value(default_input, param); + const InputValue resolved = default_input.domain.value(param); + values[required.param] = resolved; + requested_values[required.param] = resolved; + const std::string rendered = resolved.format(); + ModuleBase::GlobalFunc::AUTO_SET(required.param, rendered); + } + for (const std::pair& entry : this->input_lists) { errors += entry.second.domain.validate_requirements(entry.first, requested_values); diff --git a/source/source_io/module_parameter/read_input.h b/source/source_io/module_parameter/read_input.h index 93a2284916c..90e39582910 100644 --- a/source/source_io/module_parameter/read_input.h +++ b/source/source_io/module_parameter/read_input.h @@ -44,6 +44,9 @@ class ReadInput */ void read_parameters(Parameter& param, const std::string& filename_in); + /// Whether this reader saw the keyword; INPUT parsing runs on rank 0. + bool is_explicit(const std::string& label) const; + /** * @brief Create a directory for output files * diff --git a/source/source_io/unittests/CMakeLists.txt b/source/source_io/unittests/CMakeLists.txt index d27056956dc..2b379f4b897 100644 --- a/source/source_io/unittests/CMakeLists.txt +++ b/source/source_io/unittests/CMakeLists.txt @@ -32,9 +32,9 @@ addtest(TARGET MODULE_IO_parse_command_line_test addtest(TARGET MODULE_IO_spin_tag SOURCES test_spin_tag.cpp) -addtest( - TARGET MODULE_IO_dftu_dc_check - SOURCES test_dftu_dc_check.cpp ../../source_lcao/module_dftu/dftu_dc_check.cpp) +addtest(TARGET MODULE_IO_dftu_dc_check + SOURCES test_dftu_dc_check.cpp + ../../source_lcao/module_dftu/dftu_dc_check.cpp) addtest(TARGET MODULE_IO_libxc_r_suffix SOURCES test_libxc_r_suffix.cpp ../module_chgpot/libxc_r_suffix.cpp) @@ -67,6 +67,9 @@ foreach( duplicate_string_eof invalid_value invalid_dependency + md_force_conflict + bse_requirement_conflict + md_force_default unsupported_libxc_cuda dftu_default dftu_fll diff --git a/source/source_io/unittests/test_input_domain.cpp b/source/source_io/unittests/test_input_domain.cpp index 36e087bd2ce..b5dbdb82318 100644 --- a/source/source_io/unittests/test_input_domain.cpp +++ b/source/source_io/unittests/test_input_domain.cpp @@ -1,6 +1,5 @@ #include "source_io/module_parameter/input_domain.h" #include "source_io/module_parameter/input_item.h" -#include "source_io/module_parameter/input_parameter.h" #include #include @@ -110,10 +109,11 @@ TEST(InputDomain, SharedConditionsAndDependencyDiagnostics) } ModuleIO::InputDomain domain; domain.add_requirement("noncolin==true", "nspin==4"); + EXPECT_TRUE(domain.choice_defaults(values).empty()); const auto error = domain.validate_requirements("nspin", values); - EXPECT_NE(error.find("noncolin = true"), std::string::npos); - EXPECT_NE(error.find("nspin = 2"), std::string::npos); - EXPECT_NE(error.find("When noncolin = true, the following is required:\n nspin = 4"), std::string::npos); + EXPECT_NE(error.find("noncolin=true"), std::string::npos); + EXPECT_NE(error.find("nspin=2"), std::string::npos); + EXPECT_NE(error.find("Requires nspin==4"), std::string::npos); EXPECT_NE(error.find("input-main.html#nspin"), std::string::npos); EXPECT_THROW(domain.validate_schema("nspin", {}), std::invalid_argument); } @@ -144,60 +144,30 @@ TEST(InputDomain, RejectsNonfiniteRuleLiteralsAndVectorScalarComparisons) EXPECT_THROW(vector_domain.validate_schema("bad_vector", types), std::invalid_argument); } -TEST(InputDomain, ChoiceRequirementsCheckRangesAndAlternatives) +TEST(InputDomain, ChoiceRequirementsDeriveOnlyFixedEqualities) { ModuleIO::Input_Item item("mode"); - item.add_choice_requirement("bounded", "weight>=0 and weight<1"); - item.add_choice_requirement("optional", "weight==-1 or (weight>=0 and weight<1)"); - const std::map types = { - {"mode", ModuleIO::AvailabilityValueKind::String}, {"weight", ModuleIO::AvailabilityValueKind::Real}}; - EXPECT_NO_THROW(item.domain.validate_schema(item.label, types)); - for (const std::string mode : {"bounded", "optional", "unrestricted"}) - { - for (const double weight : {-1.0, -0.1, 0.0, 0.5, 1.0}) - { - const ModuleIO::InputValues values = { - {"mode", ModuleIO::InputValue(mode)}, {"weight", ModuleIO::InputValue(weight)}}; - const bool accepted = mode == "unrestricted" || (weight >= 0 && weight < 1) - || (mode == "optional" && weight == -1); - const std::string error = item.domain.validate_requirements(item.label, values); - EXPECT_EQ(error.empty(), accepted) << mode << ": " << weight; - EXPECT_EQ(values.at("weight").numbers.front(), weight); - } - } - const ModuleIO::InputValues invalid = { - {"mode", ModuleIO::InputValue(std::string("optional"))}, {"weight", ModuleIO::InputValue(2.0)}}; - const std::string error = item.domain.validate_requirements(item.label, invalid); - EXPECT_NE(error.find("weight = -1 or (weight >= 0 and weight < 1)"), std::string::npos); -} - -TEST(InputDomain, ChoiceRequirementGeneratesContextValuesAndManualLinks) -{ - ModuleIO::Input_Item item("basis_type"); - item.add_choice_requirement("pw", "ks_solver in [cg, dav]"); - const ModuleIO::InputValues values = { - {"basis_type", ModuleIO::InputValue(std::string("pw"))}, - {"ks_solver", ModuleIO::InputValue(std::string("lapack"))}, {"unrelated", ModuleIO::InputValue(42)}}; - const std::string expected = - "ERROR: INPUT requirement not satisfied for 'basis_type'.\n\n" - "When basis_type = pw, the following is required:\n" - " ks_solver in [cg, dav]\n\n" - "Current settings:\n" - " basis_type = pw\n" - " ks_solver = lapack\n\n" - "Documentation:\n" - " https://abacus.deepmodeling.com/en/latest/advanced/input_files/input-main.html#basis-type\n" - " https://abacus.deepmodeling.com/en/latest/advanced/input_files/input-main.html#ks-solver\n"; - EXPECT_EQ(item.domain.validate_requirements(item.label, values), expected); - EXPECT_EQ(item.domain.format_requirements(), "When basis_type==pw: require ks_solver in [cg, dav]"); -} + item.add_choice_requirement("fixed", "count==2 and enabled==true"); + item.add_choice_requirement("alternatives", "count in [2, 3] and (enabled==true or weight>0)"); + ModuleIO::InputValues values = { + {"mode", ModuleIO::InputValue(std::string("fixed"))}, + {"count", ModuleIO::InputValue(0)}, {"enabled", ModuleIO::InputValue(false)}, + {"weight", ModuleIO::InputValue(0.0)}}; + const std::vector defaults = item.domain.choice_defaults(values); + ASSERT_EQ(defaults.size(), 2); + EXPECT_EQ(defaults[0].to_string(), "count==2"); + EXPECT_EQ(defaults[1].to_string(), "enabled==true"); + values["count"] = ModuleIO::InputValue(2); + values["enabled"] = ModuleIO::InputValue(true); + EXPECT_TRUE(item.domain.choice_defaults(values).empty()); + EXPECT_TRUE(item.domain.validate_requirements(item.label, values).empty()); -TEST(InputDomain, ChoiceRequirementQuotesTheSelectedValue) -{ - ModuleIO::Input_Item item("mode"); - item.add_choice_requirement("x==y", "flag==true"); - const ModuleIO::InputValues values = { - {"mode", ModuleIO::InputValue(std::string("x==y"))}, {"flag", ModuleIO::InputValue(false)}}; - const std::string error = item.domain.validate_requirements(item.label, values); - EXPECT_NE(error.find("When mode = \"x==y\", the following is required:\n flag = true"), std::string::npos); + values["mode"] = ModuleIO::InputValue(std::string("alternatives")); + values["count"] = ModuleIO::InputValue(0); + values["enabled"] = ModuleIO::InputValue(false); + EXPECT_TRUE(item.domain.choice_defaults(values).empty()); + EXPECT_FALSE(item.domain.validate_requirements(item.label, values).empty()); + values["mode"] = ModuleIO::InputValue(std::string("inactive")); + EXPECT_TRUE(item.domain.choice_defaults(values).empty()); + EXPECT_TRUE(item.domain.validate_requirements(item.label, values).empty()); } diff --git a/source/source_io/unittests/test_input_domain_reader.cpp b/source/source_io/unittests/test_input_domain_reader.cpp index b3c1a9206b7..890caa4bdb2 100644 --- a/source/source_io/unittests/test_input_domain_reader.cpp +++ b/source/source_io/unittests/test_input_domain_reader.cpp @@ -133,6 +133,90 @@ TEST_F(InputDomainReaderTest, RejectsMalformedAndOutOfDomainExplicitValues) EXPECT_NE(exx_output.find("Expected one String from {cpu, gpu}."), std::string::npos); } +TEST_F(InputDomainReaderTest, CalculationRequirementsSupplyForcesAndRejectExplicitConflicts) +{ + for (const std::pair& mode : std::vector>{ + {"md", true}, {"relax", true}, {"cell-relax", true}, + {"get_wf", false}, {"get_pchg", false}, {"get_s", false}}) + { + SCOPED_TRACE(mode.first); + const std::string context = "calculation " + mode.first + "\nmd_tfirst 300\n"; + const std::string basis = mode.second ? "pw" : "lcao"; + const std::string required = mode.second ? "true" : "false"; + const std::string conflict = mode.second ? "false" : "true"; + for (const bool explicit_value : {false, true}) + { + const std::string force = explicit_value ? "cal_force " + required + "\n" : ""; + const std::string fields = force + context; + write_input(fields, basis); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.cal_force, mode.second); + EXPECT_EQ(reader.is_explicit("cal_force"), explicit_value); + } + const std::string fields = context + "cal_force " + conflict + "\n"; + const std::string error = reject_input(fields, basis); + EXPECT_NE(error.find("calculation=" + mode.first), std::string::npos); + EXPECT_NE(error.find("cal_force=" + conflict), std::string::npos); + EXPECT_NE(error.find("Requires cal_force==" + required), std::string::npos); + EXPECT_NE(error.find("https://abacus.deepmodeling.com/en/latest/advanced/input_files/input-main.html#calculation"), + std::string::npos); + } +} + +TEST_F(InputDomainReaderTest, BseRequirementsAcceptDefaultsAndRejectExplicitConflicts) +{ + for (const std::string& fields : {"bse_mem_save true\n", + "bse_continue 0\nbse_ri_hartree true\nbse_mem_save true\n"}) + { + write_input(fields); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.bse_continue, 0); + EXPECT_TRUE(input.inp.bse_ri_hartree); + } + for (const std::string& conflict : {"bse_continue 2\n", "bse_ri_hartree false\n"}) + { + const std::string fields = conflict + "bse_mem_save true\n"; + const std::string error = reject_input(fields); + EXPECT_NE(error.find("bse_mem_save=true"), std::string::npos); + EXPECT_NE(error.find("Requires bse_continue==0 and bse_ri_hartree==true"), std::string::npos); + EXPECT_NE(error.find("input-main.html#bse-mem-save"), std::string::npos); + } +} + +TEST_F(InputDomainReaderTest, InactiveRequirementsPreserveValuesAndExplicitPresence) +{ + for (const std::string& force : {"0", "1"}) + { + const std::string fields = "socket_driver true\ncal_force " + force + + "\nbse_mem_save false\nbse_continue 2\nbse_ri_hartree false\n"; + write_input(fields); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.cal_force, force == "1"); + EXPECT_EQ(input.inp.bse_continue, 2); + EXPECT_FALSE(input.inp.bse_ri_hartree); + EXPECT_TRUE(reader.is_explicit("cal_force")); + EXPECT_TRUE(reader.is_explicit("bse_mem_save")); + reader.clear(); + EXPECT_FALSE(reader.is_explicit("cal_force")); + write_input("calculation md\nmd_tfirst 300\n"); + Parameter next; + reader.read_parameters(next, filename); + EXPECT_TRUE(next.inp.cal_force); + EXPECT_FALSE(reader.is_explicit("cal_force")); + } + const std::string error = reject_input("calculation md\ncal_force\n"); + EXPECT_NE(error.find("Invalid INPUT parameter 'cal_force': supplied ''. Expected one Boolean"), std::string::npos); +} + TEST_F(InputDomainReaderTest, ReportsIndependentErrorsTogether) { const std::string output = reject_input("nspin 3\ngga_grad -1\n"); @@ -409,7 +493,7 @@ TEST_F(InputDomainReaderTest, RejectsMissingStringChoiceAtEndOfFile) TEST_F(InputDomainReaderTest, RetainsExistingSpinDependencyCheck) { const std::string output = reject_input("nspin 2\nnoncolin 1\n"); - EXPECT_NE(output.find("the following is required:\n nspin = 4"), std::string::npos); + EXPECT_NE(output.find("Requires nspin==4"), std::string::npos); } TEST_F(InputDomainReaderTest, RejectsPrivateSentinelsBeforeDefaultResolution) @@ -455,15 +539,13 @@ TEST_F(InputDomainReaderTest, ChecksTypesRangesAndDependenciesThroughOnePath) for (const std::pair& example : invalid) { const std::string output = reject_input(example.first + "\n"); - const bool domain_error = output.find("Invalid INPUT parameter") != std::string::npos; - const bool requirement_error = output.find("ERROR: INPUT requirement not satisfied for") != std::string::npos; - EXPECT_TRUE(domain_error || requirement_error) << example.first; + EXPECT_NE(output.find("Invalid INPUT parameter"), std::string::npos) << example.first; EXPECT_NE(output.find("input-main.html#" + example.second), std::string::npos) << example.first; } // The legacy nupdown reset used to erase this conflicting explicit value. const std::string output = reject_input("nupdown 1\nnspin 1\n"); - EXPECT_NE(output.find("nupdown = 1"), std::string::npos); - EXPECT_NE(output.find("the following is required:\n nupdown = 0"), std::string::npos); + EXPECT_NE(output.find("nupdown=1"), std::string::npos); + EXPECT_NE(output.find("Requires nupdown==0"), std::string::npos); } TEST_F(InputDomainReaderTest, PreservesDisabledModesNegativePhysicsAndInactiveSwitches) @@ -492,34 +574,13 @@ TEST_F(InputDomainReaderTest, PreservesDisabledModesNegativePhysicsAndInactiveSw EXPECT_EQ(restored.mdp.md_plast, -1); } -TEST_F(InputDomainReaderTest, ChoiceRequirementsReportTheSelectingParameter) -{ - const std::string solver = reject_input("ks_solver lapack\n"); - EXPECT_NE(solver.find("INPUT requirement not satisfied for 'basis_type'"), std::string::npos); - EXPECT_NE(solver.find("When basis_type = pw, the following is required:\n ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"), - std::string::npos); - EXPECT_NE(solver.find("ks_solver = lapack"), std::string::npos); - EXPECT_NE(solver.find("input-main.html#basis-type"), std::string::npos); - EXPECT_NE(solver.find("input-main.html#ks-solver"), std::string::npos); - - const std::string precision = reject_input("precision single\n", "lcao"); - EXPECT_NE(precision.find("When precision = single, the following is required:\n basis_type != lcao"), - std::string::npos); - const std::string calculation = reject_input("calculation get_wf\n"); - EXPECT_NE(calculation.find("When calculation = get_wf, the following is required:\n basis_type != pw"), - std::string::npos); - - write_input("ks_solver dav\nprecision double\n"); - ModuleIO::ReadInput reader(0); - reader.check_ntype_flag = false; - Parameter input; - reader.read_parameters(input, filename); - EXPECT_EQ(input.inp.ks_solver, "dav"); - EXPECT_EQ(input.inp.precision, "double"); -} - TEST(InputDomainHelp, ExportsTheRuntimeRules) { + const ModuleIO::ParameterMetadata calculation = ModuleIO::ParameterHelp::get_metadata("calculation"); + EXPECT_NE(calculation.requirements.find("When calculation==md: require cal_force==true"), std::string::npos); + const ModuleIO::ParameterMetadata bse = ModuleIO::ParameterHelp::get_metadata("bse_mem_save"); + EXPECT_NE(bse.requirements.find("When bse_mem_save==true: require bse_continue==0 and bse_ri_hartree==true"), + std::string::npos); const ModuleIO::ParameterMetadata spin = ModuleIO::ParameterHelp::get_metadata("nspin"); EXPECT_EQ(spin.allowed_values, "1, 2, 4"); std::ostringstream help; @@ -536,12 +597,6 @@ TEST(InputDomainHelp, ExportsTheRuntimeRules) const ModuleIO::ParameterMetadata criterion = ModuleIO::ParameterHelp::get_metadata("scf_thr_type"); EXPECT_EQ(criterion.allowed_values, "1, 2"); EXPECT_NE(spin.requirements.find("nspin==4"), std::string::npos); - const ModuleIO::ParameterMetadata basis = ModuleIO::ParameterHelp::get_metadata("basis_type"); - EXPECT_NE(basis.requirements.find("When basis_type==pw: require ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"), - std::string::npos); - EXPECT_NE(dump.find(basis.requirements), std::string::npos); - const ModuleIO::ParameterMetadata solver = ModuleIO::ParameterHelp::get_metadata("ks_solver"); - EXPECT_EQ(solver.requirements, "When ks_solver==genelpa: require device==cpu"); } } // namespace diff --git a/source/source_io/unittests/test_read_input.cmake b/source/source_io/unittests/test_read_input.cmake index 56489ec280d..861619a98cc 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -29,8 +29,19 @@ elseif(INPUT_CASE STREQUAL "invalid_value") set(expected_manual "input-main.html#nspin") elseif(INPUT_CASE STREQUAL "invalid_dependency") string(APPEND contents "nspin 2\nnoncolin true\n") - set(expected "the following is required:\n nspin = 4") + set(expected "Requires nspin==4") set(expected_manual "input-main.html#nspin") +elseif(INPUT_CASE STREQUAL "md_force_conflict") + string(APPEND contents "calculation md\ncal_force false\n") + set(expected "calculation=md'. Requires cal_force==true") + set(expected_manual "input-main.html#calculation") +elseif(INPUT_CASE STREQUAL "bse_requirement_conflict") + string(APPEND contents "bse_mem_save true\nbse_continue 2\n") + set(expected "Requires bse_continue==0 and bse_ri_hartree==true") + set(expected_manual "input-main.html#bse-mem-save") +elseif(INPUT_CASE STREQUAL "md_force_default") + string(APPEND contents "suffix force_bcast\ncalculation md\nmd_tfirst 300\n") + set(expected_exit 0) elseif(INPUT_CASE STREQUAL "unsupported_libxc_cuda") string(APPEND contents "device gpu\ndevice_xc gpu\n") set(expected @@ -154,3 +165,12 @@ if(DEFINED expected_dc) "Only ${received_count} of 4 ranks received ${expected_dc}:\n${output}") endif() endif() +if(INPUT_CASE STREQUAL "md_force_default") + string(REGEX MATCHALL "Force received: 1[\r\n]" received "${output}") + list(LENGTH received received_count) + if(NOT received_count EQUAL 4) + message( + FATAL_ERROR + "Only ${received_count} of 4 ranks received cal_force=true:\n${output}") + endif() +endif() diff --git a/source/source_io/unittests/test_read_input.cpp b/source/source_io/unittests/test_read_input.cpp index 7c8f3f17239..602f9190e8a 100644 --- a/source/source_io/unittests/test_read_input.cpp +++ b/source/source_io/unittests/test_read_input.cpp @@ -43,6 +43,10 @@ int main(int argc, char** argv) reader.check_ntype_flag = false; Parameter input; reader.read_parameters(input, filename); + if (input.inp.suffix == "force_bcast") + { + std::printf("Force received: %d\n", input.inp.cal_force); + } if (input.inp.suffix == "dftu_dc_bcast") { std::printf("DFTU DC received: %s %.17g\n", input.inp.dftu_dc.c_str(), input.inp.dftu_alpha); diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 377e03763f1..557d2596610 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -130,6 +130,50 @@ TEST_F(InputTest, InvalidExplicitDomainDoesNotReachReadOrResetHooks) EXPECT_FALSE(reset_called); } +TEST_F(InputTest, ChoiceRequirementsFillOnlyOmittedParameters) +{ + for (const bool explicit_values : {false, true}) + { + ModuleIO::ReadInput reader(0); + Parameter param; + Input_para& input = TestParameters::input(param); + input.basis_type = "pw"; + input.ntype = 1; + input.bse_mem_save = true; + input.bse_continue = 2; + input.bse_ri_hartree = false; + for (const std::string& label : {"cal_force", "bse_mem_save"}) + { + EXPECT_FALSE(find_label(label, reader.input_lists)->second.reset_value); + } + if (explicit_values) + { + for (const std::pair& supplied : + std::vector>{{"bse_continue", "2"}, {"bse_ri_hartree", "false"}}) + { + ModuleIO::Input_Item& item = find_label(supplied.first, reader.input_lists)->second; + item.str_values = {supplied.second}; + reader.readvalue_items.push_back(&item); + } + } + const std::string error = reader.prepare_input(param); + if (explicit_values) + { + EXPECT_THAT(error, testing::HasSubstr("Requires bse_continue==0 and bse_ri_hartree==true")); + EXPECT_EQ(input.bse_continue, 2); + EXPECT_FALSE(input.bse_ri_hartree); + } + else + { + EXPECT_TRUE(error.empty()) << error; + EXPECT_EQ(input.bse_continue, 0); + EXPECT_TRUE(input.bse_ri_hartree); + } + EXPECT_EQ(reader.is_explicit("bse_continue"), explicit_values); + EXPECT_EQ(reader.is_explicit("bse_ri_hartree"), explicit_values); + } +} + TEST_F(InputTest, MdThermoFrequencyUsesOnlyOutName) { ModuleIO::ReadInput reader(0); @@ -336,18 +380,18 @@ TEST_F(InputTest, RejectInvalidMemSaver) testing::internal::CaptureStdout(); EXPECT_EXIT(reader.read_parameters(param, filename), testing::ExitedWithCode(1), ""); const std::string diagnostic = testing::internal::GetCapturedStdout(); + const std::string invalid_value = "Invalid INPUT parameter 'mem_saver'"; + EXPECT_THAT(diagnostic, testing::HasSubstr(invalid_value)); EXPECT_THAT(diagnostic, testing::HasSubstr("input-main.html#mem-saver")); if (value == 1) { - EXPECT_THAT(diagnostic, testing::HasSubstr("INPUT requirement not satisfied for 'mem_saver'")); - EXPECT_THAT(diagnostic, testing::HasSubstr("mem_saver = 1")); - const std::string invalid_mode = "calculation = " + calculation; + EXPECT_THAT(diagnostic, testing::HasSubstr("mem_saver=1")); + const std::string invalid_mode = "calculation=" + calculation; EXPECT_THAT(diagnostic, testing::HasSubstr(invalid_mode)); - EXPECT_THAT(diagnostic, testing::HasSubstr("the following is required:\n mem_saver = 0")); + EXPECT_THAT(diagnostic, testing::HasSubstr("Requires mem_saver==0")); } else { - EXPECT_THAT(diagnostic, testing::HasSubstr("Invalid INPUT parameter 'mem_saver'")); const std::string supplied = "supplied '" + std::to_string(value) + "'"; EXPECT_THAT(diagnostic, testing::HasSubstr(supplied)); EXPECT_THAT(diagnostic, testing::HasSubstr("from {0, 1}")); @@ -598,26 +642,6 @@ TEST_F(InputTest, Item_test) it->second.reset_value(it->second, param); EXPECT_EQ(TestParameters::input(param).diago_proc, 1); } - { // cal_force - std::vector>::iterator it = find_label("cal_force", readinput.input_lists); - TestParameters::input(param).calculation = "cell-relax"; - TestParameters::input(param).cal_force = false; - TestParameters::input(param).socket_driver = false; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).cal_force, true); - - TestParameters::input(param).calculation = "get_wf"; - TestParameters::input(param).cal_force = true; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).cal_force, false); - - TestParameters::input(param).calculation = "scf"; - TestParameters::input(param).socket_driver = true; - TestParameters::input(param).cal_force = false; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).cal_force, false); - TestParameters::input(param).socket_driver = false; - } { // ecutrho std::vector>::iterator it = find_label("ecutrho", readinput.input_lists); TestParameters::input(param).ecutwfc = 1; @@ -1192,7 +1216,7 @@ TEST_F(InputTest, Item_test) testing::internal::CaptureStdout(); EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); - EXPECT_THAT(output, testing::HasSubstr("the following is required:\n device = cpu")); + EXPECT_THAT(output, testing::HasSubstr("Requires device==cpu")); #ifdef __ELPA TestParameters::input(param).towannier90 = true; TestParameters::input(param).basis_type = "lcao_in_pw"; @@ -1218,19 +1242,17 @@ TEST_F(InputTest, Item_test) TestParameters::input(param).ks_solver = "genelpa"; TestParameters::input(param).basis_type = "pw"; - std::vector>::iterator basis - = find_label("basis_type", readinput.input_lists); testing::internal::CaptureStdout(); - EXPECT_EXIT(check_item(basis->second, param), ::testing::ExitedWithCode(1), ""); + EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); - EXPECT_THAT(output, testing::HasSubstr("When basis_type = pw, the following is required:")); + EXPECT_THAT(output, testing::HasSubstr("NOTICE")); TestParameters::input(param).ks_solver = "cg"; TestParameters::input(param).basis_type = "lcao"; testing::internal::CaptureStdout(); - EXPECT_EXIT(check_item(basis->second, param), ::testing::ExitedWithCode(1), ""); + EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); - EXPECT_THAT(output, testing::HasSubstr("When basis_type = lcao, the following is required:")); + EXPECT_THAT(output, testing::HasSubstr("NOTICE")); TestParameters::input(param).ks_solver = "scalapack_gvx"; TestParameters::input(param).basis_type = "lcao"; diff --git a/source/source_io/unittests/test_read_input_serial.cpp b/source/source_io/unittests/test_read_input_serial.cpp index 3654e67c296..68e3cc08172 100644 --- a/source/source_io/unittests/test_read_input_serial.cpp +++ b/source/source_io/unittests/test_read_input_serial.cpp @@ -319,13 +319,13 @@ TEST_F(InputTest, ValidateNoncollinearSpin) expect_invalid_input("noncolin_missing_nspin_INPUT", "noncolin 1\n", - "the following is required:\n nspin = 4"); + "Requires nspin==4"); expect_invalid_input("noncolin_invalid_nspin_INPUT", "noncolin 1\nnspin 2\n", - "the following is required:\n nspin = 4"); + "Requires nspin==4"); expect_invalid_input("soc_missing_nspin_INPUT", "lspinorb 1\n", - "the following is required:\n nspin = 4"); + "Requires nspin==4"); } TEST_F(InputTest, ValidateSdftStochasticBands) @@ -408,7 +408,7 @@ TEST_F(InputTest, RejectComplexLrForcesBeforeSCF) const std::string reason = "currently require gamma_only=1"; const std::string cg = base + "cal_force 1\nlr_grad_solver cg\n"; const std::string lapack = base + "cal_force 1\nlr_grad_solver lapack\n"; - const std::string relax = base + "calculation relax\ncal_force 0\n"; + const std::string relax = base + "calculation relax\n"; expect_invalid_input("complex_force_cg_INPUT", cg, reason); expect_invalid_input("complex_force_lapack_INPUT", lapack, reason); expect_invalid_input("complex_relax_INPUT", relax, reason); @@ -435,7 +435,7 @@ TEST_F(InputTest, ValidateDeepksOutputFrequency) "Invalid INPUT parameter 'deepks_out_freq_elec': supplied '-1'. Expected one Integer satisfying value>=0."); expect_invalid_input("deepks_freq_missing_base_INPUT", "deepks_out_freq_elec 2\n", - "the following is required:\n deepks_out_base != none"); + "Requires deepks_out_base!=none"); Parameter enabled_param; testing::internal::CaptureStdout(); From f6e00d8c1ca561d98b7a81be799331c250f2fb9b Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Wed, 2 Dec 2026 22:43:24 +0800 Subject: [PATCH 03/11] refactor(input): declare shared choice requirements with lists --- docs/developers_guide/input_validation.md | 2 +- source/source_io/module_parameter/input_item.h | 8 ++++---- source/source_io/module_parameter/read_inp_bse.cpp | 2 +- source/source_io/module_parameter/read_inp_sys.cpp | 10 ++-------- source/source_io/unittests/test_input_domain.cpp | 4 ++-- .../source_io/unittests/test_input_domain_reader.cpp | 5 ++++- 6 files changed, 14 insertions(+), 17 deletions(-) diff --git a/docs/developers_guide/input_validation.md b/docs/developers_guide/input_validation.md index 6d67f25833b..c7883796798 100644 --- a/docs/developers_guide/input_validation.md +++ b/docs/developers_guide/input_validation.md @@ -9,7 +9,7 @@ with custom input syntax keep their own parsing rules. | A fixed set of choices | `item.domain.set_choices({"cpu", "gpu"});` | | A numerical range | `item.domain.set_rule("value>0");` | | A dependency on another parameter | `item.domain.add_requirement("device_xc==gpu", "device==gpu");` | -| A requirement of an option | `item.add_choice_requirement("md", "cal_force==true");` (in `calculation`) | +| A requirement shared by options | `item.add_choice_requirement({"md", "relax", "cell-relax"}, "cal_force==true");` (in `calculation`) | For choice requirements, the reader fills omitted values from fixed scalar equalities (including `and`); explicit conflicts use the existing requirement diff --git a/source/source_io/module_parameter/input_item.h b/source/source_io/module_parameter/input_item.h index c04cd485641..6ec2644ce25 100644 --- a/source/source_io/module_parameter/input_item.h +++ b/source/source_io/module_parameter/input_item.h @@ -53,13 +53,13 @@ class Input_Item std::string unit; ///< unit of measurement (empty if none) InputDomain domain; ///< shared runtime validation and legal-value metadata - /// Require a configuration for this choice; fixed equalities fill omitted values. - void add_choice_requirement(const std::string& choice, const std::string& require) + /// Require a configuration for any listed choice; fixed equalities fill omitted values. + void add_choice_requirement(const std::vector& choices, const std::string& require) { AvailabilityCondition selected; selected.param = label; - selected.op = "=="; - selected.values = {choice}; + selected.op = choices.size() == 1 ? "==" : "in"; + selected.values = choices; const std::string when = selected.to_string(); domain.add_requirement(when, require, true); } diff --git a/source/source_io/module_parameter/read_inp_bse.cpp b/source/source_io/module_parameter/read_inp_bse.cpp index 52b5ba53a28..05dc162c32d 100644 --- a/source/source_io/module_parameter/read_inp_bse.cpp +++ b/source/source_io/module_parameter/read_inp_bse.cpp @@ -42,7 +42,7 @@ void ReadInput::item_bse() } { Input_Item item("bse_mem_save"); - item.add_choice_requirement("true", "bse_continue==0 and bse_ri_hartree==true"); + item.add_choice_requirement({"true"}, "bse_continue==0 and bse_ri_hartree==true"); item.annotation = "whether to save memory by adding V and W to BSE matrix directly"; item.category = "Bethe-Salpeter Equation"; item.type = "Boolean"; diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index 8b3f47b3d92..4ed7c74e1c4 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -146,14 +146,8 @@ void ReadInput::item_system() { Input_Item item("calculation"); item.domain.set_choices({"scf", "relax", "md", "cell-relax", "nscf", "get_s", "get_wf", "get_pchg", "gen_bessel", "gen_opt_abfs", "test_memory", "test_neighbour"}); - for (const std::string& choice : {"md", "relax", "cell-relax"}) - { - item.add_choice_requirement(choice, "cal_force==true"); - } - for (const std::string& choice : {"get_wf", "get_pchg", "get_s"}) - { - item.add_choice_requirement(choice, "cal_force==false"); - } + item.add_choice_requirement({"md", "relax", "cell-relax"}, "cal_force==true"); + item.add_choice_requirement({"get_wf", "get_pchg", "get_s"}, "cal_force==false"); item.domain.add_requirement("calculation in [get_pchg, get_wf]", "basis_type!=pw"); item.domain.add_requirement("calculation==gen_bessel", "basis_type==pw"); item.annotation = "scf; relax; md; cell-relax; nscf; get_s; get_wf; get_pchg; gen_bessel; gen_opt_abfs; test_memory; test_neighbour"; diff --git a/source/source_io/unittests/test_input_domain.cpp b/source/source_io/unittests/test_input_domain.cpp index b5dbdb82318..d0757f5442b 100644 --- a/source/source_io/unittests/test_input_domain.cpp +++ b/source/source_io/unittests/test_input_domain.cpp @@ -147,8 +147,8 @@ TEST(InputDomain, RejectsNonfiniteRuleLiteralsAndVectorScalarComparisons) TEST(InputDomain, ChoiceRequirementsDeriveOnlyFixedEqualities) { ModuleIO::Input_Item item("mode"); - item.add_choice_requirement("fixed", "count==2 and enabled==true"); - item.add_choice_requirement("alternatives", "count in [2, 3] and (enabled==true or weight>0)"); + item.add_choice_requirement({"fixed"}, "count==2 and enabled==true"); + item.add_choice_requirement({"alternatives"}, "count in [2, 3] and (enabled==true or weight>0)"); ModuleIO::InputValues values = { {"mode", ModuleIO::InputValue(std::string("fixed"))}, {"count", ModuleIO::InputValue(0)}, {"enabled", ModuleIO::InputValue(false)}, diff --git a/source/source_io/unittests/test_input_domain_reader.cpp b/source/source_io/unittests/test_input_domain_reader.cpp index 890caa4bdb2..a537747e110 100644 --- a/source/source_io/unittests/test_input_domain_reader.cpp +++ b/source/source_io/unittests/test_input_domain_reader.cpp @@ -577,7 +577,10 @@ TEST_F(InputDomainReaderTest, PreservesDisabledModesNegativePhysicsAndInactiveSw TEST(InputDomainHelp, ExportsTheRuntimeRules) { const ModuleIO::ParameterMetadata calculation = ModuleIO::ParameterHelp::get_metadata("calculation"); - EXPECT_NE(calculation.requirements.find("When calculation==md: require cal_force==true"), std::string::npos); + EXPECT_NE(calculation.requirements.find("When calculation in [md, relax, cell-relax]: require cal_force==true"), + std::string::npos); + EXPECT_NE(calculation.requirements.find("When calculation in [get_wf, get_pchg, get_s]: require cal_force==false"), + std::string::npos); const ModuleIO::ParameterMetadata bse = ModuleIO::ParameterHelp::get_metadata("bse_mem_save"); EXPECT_NE(bse.requirements.find("When bse_mem_save==true: require bse_continue==0 and bse_ri_hartree==true"), std::string::npos); From 1838ff7b5596bcb06c8ccea01d4774dbad2c91f8 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Wed, 2 Dec 2026 22:56:37 +0800 Subject: [PATCH 04/11] chore(input): drop unrelated CMake formatting from the draft --- source/source_io/unittests/CMakeLists.txt | 6 ++--- .../source_io/unittests/test_read_input.cmake | 26 +++++-------------- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/source/source_io/unittests/CMakeLists.txt b/source/source_io/unittests/CMakeLists.txt index 2b379f4b897..4a36fd9e387 100644 --- a/source/source_io/unittests/CMakeLists.txt +++ b/source/source_io/unittests/CMakeLists.txt @@ -32,9 +32,9 @@ addtest(TARGET MODULE_IO_parse_command_line_test addtest(TARGET MODULE_IO_spin_tag SOURCES test_spin_tag.cpp) -addtest(TARGET MODULE_IO_dftu_dc_check - SOURCES test_dftu_dc_check.cpp - ../../source_lcao/module_dftu/dftu_dc_check.cpp) +addtest( + TARGET MODULE_IO_dftu_dc_check + SOURCES test_dftu_dc_check.cpp ../../source_lcao/module_dftu/dftu_dc_check.cpp) addtest(TARGET MODULE_IO_libxc_r_suffix SOURCES test_libxc_r_suffix.cpp ../module_chgpot/libxc_r_suffix.cpp) diff --git a/source/source_io/unittests/test_read_input.cmake b/source/source_io/unittests/test_read_input.cmake index 861619a98cc..f77561d04ea 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -44,26 +44,19 @@ elseif(INPUT_CASE STREQUAL "md_force_default") set(expected_exit 0) elseif(INPUT_CASE STREQUAL "unsupported_libxc_cuda") string(APPEND contents "device gpu\ndevice_xc gpu\n") - set(expected - "device_xc gpu requires ABACUS built with -DENABLE_LIBXC_CUDA=ON.") + set(expected "device_xc gpu requires ABACUS built with -DENABLE_LIBXC_CUDA=ON.") set(expected_manual "input-main.html#device-xc") elseif(INPUT_CASE STREQUAL "out_dmk_zero_precision") string(APPEND contents "out_dmk 1 0\n") - set(expected - "Invalid INPUT parameter 'out_dmk': precision must be a positive integer." - ) + set(expected "Invalid INPUT parameter 'out_dmk': precision must be a positive integer.") set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_hsk_zero_precision") string(APPEND contents "out_hsk 1 0\n") - set(expected - "Invalid INPUT parameter 'out_hsk': precision must be a positive integer." - ) + set(expected "Invalid INPUT parameter 'out_hsk': precision must be a positive integer.") set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_tk_zero_precision") string(APPEND contents "out_mat_tk 1 0\n") - set(expected - "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer." - ) + set(expected "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer.") set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_p_invalid_boolean") string(APPEND contents "out_mat_p maybe\n") @@ -93,9 +86,7 @@ elseif(INPUT_CASE MATCHES "^dftu_alpha_") set(expected "Invalid INPUT parameter 'dftu_alpha'") set(expected_manual "input-main.html#dftu-alpha") elseif(INPUT_CASE MATCHES "^dftu_") - set(contents - "INPUT_PARAMETERS\nsuffix dftu_dc_bcast\nntype 1\nbasis_type lcao\nks_solver genelpa\ndft_functional PBE\nsymmetry 0\ndft_plus_u 1\norbital_corr 2\nhubbard_u 2\nnspin 2\necutwfc 100\n" - ) + set(contents "INPUT_PARAMETERS\nsuffix dftu_dc_bcast\nntype 1\nbasis_type lcao\nks_solver genelpa\ndft_functional PBE\nsymmetry 0\ndft_plus_u 1\norbital_corr 2\nhubbard_u 2\nnspin 2\necutwfc 100\n") if(INPUT_CASE STREQUAL "dftu_default") set(expected_dc "fll 1") elseif(INPUT_CASE STREQUAL "dftu_fll") @@ -156,13 +147,10 @@ if(expected_exit EQUAL 1) endforeach() endif() if(DEFINED expected_dc) - string(REGEX MATCHALL "DFTU DC received: ${expected_dc}[\r\n]" received - "${output}") + string(REGEX MATCHALL "DFTU DC received: ${expected_dc}[\r\n]" received "${output}") list(LENGTH received received_count) if(NOT received_count EQUAL 4) - message( - FATAL_ERROR - "Only ${received_count} of 4 ranks received ${expected_dc}:\n${output}") + message(FATAL_ERROR "Only ${received_count} of 4 ranks received ${expected_dc}:\n${output}") endif() endif() if(INPUT_CASE STREQUAL "md_force_default") From d280de1b2b6347576481f49375d14bef76c3973e Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Wed, 2 Dec 2026 23:18:12 +0800 Subject: [PATCH 05/11] test(input): keep behavioral coverage and direct dependencies --- source/source_io/unittests/test_input_domain.cpp | 1 + source/source_io/unittests/test_read_input_item.cpp | 4 ---- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/source/source_io/unittests/test_input_domain.cpp b/source/source_io/unittests/test_input_domain.cpp index d0757f5442b..21b3812dff6 100644 --- a/source/source_io/unittests/test_input_domain.cpp +++ b/source/source_io/unittests/test_input_domain.cpp @@ -1,5 +1,6 @@ #include "source_io/module_parameter/input_domain.h" #include "source_io/module_parameter/input_item.h" +#include "source_io/module_parameter/input_parameter.h" #include #include diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 557d2596610..482843bff29 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -142,10 +142,6 @@ TEST_F(InputTest, ChoiceRequirementsFillOnlyOmittedParameters) input.bse_mem_save = true; input.bse_continue = 2; input.bse_ri_hartree = false; - for (const std::string& label : {"cal_force", "bse_mem_save"}) - { - EXPECT_FALSE(find_label(label, reader.input_lists)->second.reset_value); - } if (explicit_values) { for (const std::pair& supplied : From 27b47ead4eda2d814d398beb46b9f85269f024c1 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Wed, 2 Dec 2026 23:50:42 +0800 Subject: [PATCH 06/11] refactor(input): migrate fixed scalar reset requirements --- docs/developers_guide/input_validation.md | 15 +- .../module_parameter/input_domain.cpp | 7 + .../source_io/module_parameter/input_domain.h | 2 + .../source_io/module_parameter/input_item.h | 8 +- .../module_parameter/read_inp_deepks.cpp | 8 +- .../module_parameter/read_inp_estruc.cpp | 18 +- .../module_parameter/read_inp_exx_dftu.cpp | 28 +-- .../module_parameter/read_inp_ofdft.cpp | 21 +-- .../module_parameter/read_inp_other.cpp | 11 +- .../module_parameter/read_inp_out.cpp | 12 -- .../module_parameter/read_inp_sys.cpp | 41 ++--- .../source_io/module_parameter/read_input.cpp | 66 +++---- .../module_parameter/read_input_item_md.cpp | 7 +- source/source_io/unittests/support/INPUT | 4 +- .../unittests/test_input_domain_reader.cpp | 97 ++++++++++ .../source_io/unittests/test_read_input.cmake | 9 +- .../source_io/unittests/test_read_input.cpp | 3 +- .../unittests/test_read_input_item.cpp | 168 ++++++++++-------- 18 files changed, 285 insertions(+), 240 deletions(-) diff --git a/docs/developers_guide/input_validation.md b/docs/developers_guide/input_validation.md index c7883796798..4a2b2e8c4a3 100644 --- a/docs/developers_guide/input_validation.md +++ b/docs/developers_guide/input_validation.md @@ -10,13 +10,20 @@ with custom input syntax keep their own parsing rules. | A numerical range | `item.domain.set_rule("value>0");` | | A dependency on another parameter | `item.domain.add_requirement("device_xc==gpu", "device==gpu");` | | A requirement shared by options | `item.add_choice_requirement({"md", "relax", "cell-relax"}, "cal_force==true");` (in `calculation`) | +| A conditional fixed requirement | `item.add_requirement("of_wt_rho0!=0", "of_hold_rho0==true");` (in `of_wt_rho0`) | -For choice requirements, the reader fills omitted values from fixed scalar +For these two `Input_Item` requirement methods, the reader fills omitted values from fixed scalar equalities (including `and`); explicit conflicts use the existing requirement diagnostic. `in`, ranges and `or` only validate, without choosing a default. -Rules are selected once after legacy defaults, before final validation; this -does not resolve chains of dependent defaults. Existing `add_requirement` -declarations remain validation-only. `ReadInput::is_explicit(label)` queries +Register each rule on its controlling parameter. In registration order, the +reader runs that parameter's remaining reset callback, selects its rules from +one effective-value snapshot, then supplies omitted values. Keep the controller +before callbacks that consume those values (for example, `calculation` before +`out_freq_elec`); there is no dependency sorting or repeated resolution. +Final validation checks these rules after automatic values and aliases have +been resolved. Existing `domain.add_requirement` declarations remain +validation-only and also check original explicit values. +`ReadInput::is_explicit(label)` queries keyword presence on the parsing rank, including explicit `0` and `false`. Use `item.set_availability(...)` to describe when a parameter applies. Use diff --git a/source/source_io/module_parameter/input_domain.cpp b/source/source_io/module_parameter/input_domain.cpp index 9a64d70eb5f..b49f1806440 100644 --- a/source/source_io/module_parameter/input_domain.cpp +++ b/source/source_io/module_parameter/input_domain.cpp @@ -356,10 +356,17 @@ std::string InputDomain::validate_resolved(const std::string& label, const Input } std::string InputDomain::validate_requirements(const std::string& label, const InputValues& values) const +{ + return validate_requirements(label, values, true); +} + +std::string InputDomain::validate_requirements(const std::string& label, const InputValues& values, + const bool include_default_rules) const { std::string errors; for (const InputRequirement& rule : requirements_) { + if (rule.resolve_defaults && !include_default_rules) { continue; } if (evaluate_input_condition(rule.when, values) && !evaluate_input_condition(rule.require, values)) { const std::string actual = describe_values(values, rule); diff --git a/source/source_io/module_parameter/input_domain.h b/source/source_io/module_parameter/input_domain.h index 7fce168dc79..7f7325cd039 100644 --- a/source/source_io/module_parameter/input_domain.h +++ b/source/source_io/module_parameter/input_domain.h @@ -70,6 +70,8 @@ class InputDomain std::string validate_explicit(const std::string& label, const std::vector& tokens) const; std::string validate_resolved(const std::string& label, const InputValues& values) const; std::string validate_requirements(const std::string& label, const InputValues& values) const; + std::string validate_requirements(const std::string& label, const InputValues& values, + bool include_default_rules) const; private: AvailabilityValueKind kind_ = AvailabilityValueKind::Unknown; diff --git a/source/source_io/module_parameter/input_item.h b/source/source_io/module_parameter/input_item.h index 6ec2644ce25..4773ae3fedb 100644 --- a/source/source_io/module_parameter/input_item.h +++ b/source/source_io/module_parameter/input_item.h @@ -53,6 +53,12 @@ class Input_Item std::string unit; ///< unit of measurement (empty if none) InputDomain domain; ///< shared runtime validation and legal-value metadata + /// Require a configuration when the condition holds; fill omitted fixed values. + void add_requirement(const std::string& when, const std::string& require) + { + domain.add_requirement(when, require, true); + } + /// Require a configuration for any listed choice; fixed equalities fill omitted values. void add_choice_requirement(const std::vector& choices, const std::string& require) { @@ -61,7 +67,7 @@ class Input_Item selected.op = choices.size() == 1 ? "==" : "in"; selected.values = choices; const std::string when = selected.to_string(); - domain.add_requirement(when, require, true); + add_requirement(when, require); } /// Set and validate the canonical availability expression. An empty value diff --git a/source/source_io/module_parameter/read_inp_deepks.cpp b/source/source_io/module_parameter/read_inp_deepks.cpp index 8d3c4443b18..97ffa5fa062 100644 --- a/source/source_io/module_parameter/read_inp_deepks.cpp +++ b/source/source_io/module_parameter/read_inp_deepks.cpp @@ -275,6 +275,7 @@ void ReadInput::item_deepks() } { Input_Item item("deepks_out_unittest"); + item.add_choice_requirement({"true"}, "deepks_out_labels==1 and deepks_scf==true"); item.annotation = "if set 1, prints intermediate quantities that shall " "be used for making unit test"; item.category = "DeePKS"; @@ -285,13 +286,6 @@ void ReadInput::item_deepks() item.default_value = "False"; item.unit = ""; read_sync_bool(input.deepks_out_unittest); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.deepks_out_unittest) - { - para.input.deepks_out_labels = 1; - para.input.deepks_scf = true; - } - }; item.check_value = [](const Input_Item& item, const Parameter& para) { if (para.input.deepks_out_unittest) { diff --git a/source/source_io/module_parameter/read_inp_estruc.cpp b/source/source_io/module_parameter/read_inp_estruc.cpp index ce58dd9caab..a65d526eb6a 100644 --- a/source/source_io/module_parameter/read_inp_estruc.cpp +++ b/source/source_io/module_parameter/read_inp_estruc.cpp @@ -13,6 +13,7 @@ void ReadInput::item_elec_stru() { Input_Item item("basis_type"); item.domain.set_choices({"pw", "lcao", "lcao_in_pw"}); + item.add_choice_requirement({"pw", "lcao_in_pw"}, "bx==1 and by==1 and bz==1"); item.annotation = "PW; LCAO in pw; LCAO"; item.category = "Electronic structure"; item.type = "String"; @@ -294,6 +295,8 @@ Then the user has to correct the input file and restart the calculation.)"; } { Input_Item item("dft_functional"); + item.add_choice_requirement({"hf", "pbe0"}, "rdmft_power_alpha==1"); + item.add_choice_requirement({"muller"}, "rdmft_power_alpha==0.5"); item.annotation = "exchange correlation functional"; item.category = "Electronic structure"; item.type = "String"; @@ -830,12 +833,6 @@ Note: If gamma_only is set to 1, the KPT file will be overwritten. So make sure item.default_value = "100"; item.unit = ""; read_sync_int(input.scf_nmax); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.calculation == "nscf") - { - para.input.scf_nmax = 1; - } - }; this->add_item(item); } { @@ -1226,15 +1223,6 @@ Use case: When experimental or high-level theoretical results suggest that the S item.default_value = "0"; item.unit = ""; read_sync_int(input.bx); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.basis_type == "pw" || para.input.basis_type == "lcao_in_pw" - || para.input.calculation == "get_wf") - { - para.input.bx = 1; - para.input.by = 1; - para.input.bz = 1; - } - }; this->add_item(item); } { diff --git a/source/source_io/module_parameter/read_inp_exx_dftu.cpp b/source/source_io/module_parameter/read_inp_exx_dftu.cpp index a61cc5b47f3..2da08393170 100644 --- a/source/source_io/module_parameter/read_inp_exx_dftu.cpp +++ b/source/source_io/module_parameter/read_inp_exx_dftu.cpp @@ -173,13 +173,6 @@ void ReadInput::item_exx() * True: A two-step method is employed, i.e. in the inner iterations, density matrix is updated, while in the outer iterations, is calculated based on density matrix that converges in the inner iteration.)"; item.default_value = "True"; item.unit = ""; - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.esolver_type == "tddft" && para.input.exx_separate_loop) - { - GlobalV::ofs_running << "For RT-TDDFT with hybrid functionals, only exx_separate_loop = 0 is supported" << std::endl; - para.input.exx_separate_loop = false; - } - }; read_sync_bool(input.exx_separate_loop); this->add_item(item); } @@ -500,6 +493,7 @@ masking is unsupported.)"; } { Input_Item item("exx_singularity_correction"); + item.add_requirement("exx_singularity_correction==limits and basis_type==pw", "exx_gamma_extra==false"); item.annotation = "set the scheme of Coulomb singularity correction"; item.category = "Exact Exchange (Common)"; item.type = "String"; @@ -513,7 +507,7 @@ Use the same scheme for consistent SCF and NSCF bands. A source configuration mi item.default_value = "default"; item.unit = ""; read_sync_string(input.exx_singularity_correction); - item.reset_value = [this](const Input_Item& item, Parameter& para) { + item.reset_value = [](const Input_Item& item, Parameter& para) { if (para.input.exx_singularity_correction == "default") { std::string& dft_functional = para.input.dft_functional; @@ -544,17 +538,6 @@ Use the same scheme for consistent SCF and NSCF bands. A source configuration mi para.input.exx_singularity_correction = "limits"; } } - if (para.input.basis_type == "pw" && para.input.exx_singularity_correction == "limits") - { - const std::vector>::iterator gamma_item = std::find_if(this->input_lists.begin(), this->input_lists.end(), - [](const std::pair& entry) { - return entry.first == "exx_gamma_extra"; - }); - if (gamma_item != this->input_lists.end() && !gamma_item->second.is_read()) - { - para.input.exx_gamma_extra = false; - } - } }; item.check_value = [](const Input_Item& item, const Parameter& para) { const std::string& scheme = para.input.exx_singularity_correction; @@ -571,10 +554,10 @@ Use the same scheme for consistent SCF and NSCF bands. A source configuration mi { has_fock = has_fock || std::stod(alpha) != 0.0; } - if (has_fock || para.input.exx_gamma_extra) + if (has_fock) { ModuleBase::WARNING_QUIT("ReadInput", - "PW limits requires screened exchange and exx_gamma_extra=false"); + "PW limits requires screened exchange"); } } } @@ -653,9 +636,6 @@ For multi-k calculations, D(k) is averaged over the unitary little group of each item.unit = ""; item.set_availability("symmetry==1 and (dft_functional in [hse, hf, pbe0, scan0] or (basis_type==lcao and rpa==true))"); read_sync_bool(input.exx_symmetry_realspace); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.symmetry != "1") { para.input.exx_symmetry_realspace = false; } - }; this->add_item(item); } { diff --git a/source/source_io/module_parameter/read_inp_ofdft.cpp b/source/source_io/module_parameter/read_inp_ofdft.cpp index ce9d8bd5f32..cbf6a4645b1 100644 --- a/source/source_io/module_parameter/read_inp_ofdft.cpp +++ b/source/source_io/module_parameter/read_inp_ofdft.cpp @@ -12,6 +12,7 @@ void ReadInput::item_ofdft() // Please preserve this ordering when adding new parameters. { Input_Item item("of_kinetic"); + item.add_requirement("of_kinetic!=wt", "of_read_kernel==false"); item.annotation = "kinetic energy functional, such as tf, vw, wt"; item.category = "OFDFT: orbital free density functional theory"; item.type = "String"; @@ -231,6 +232,7 @@ void ReadInput::item_ofdft() } { Input_Item item("of_wt_rho0"); + item.add_requirement("of_wt_rho0!=0", "of_hold_rho0==true"); item.annotation = "the average density of system, used in WT KEDF, in Bohr^-3"; item.category = "OFDFT: orbital free density functional theory"; item.type = "Real"; @@ -255,12 +257,6 @@ void ReadInput::item_ofdft() item.unit = ""; item.set_availability("esolver_type==ofdft and of_kinetic==wt"); read_sync_bool(input.of_hold_rho0); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.of_wt_rho0 != 0) - { - para.input.of_hold_rho0 = true; // sunliang add 2022-06-17 - } - }; this->add_item(item); } { @@ -313,12 +309,6 @@ void ReadInput::item_ofdft() item.unit = ""; item.set_availability("esolver_type==ofdft and of_kinetic==wt"); read_sync_bool(input.of_read_kernel); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.of_kinetic != "wt") - { - para.input.of_read_kernel = false; // sunliang add 2022-09-12 - } - }; this->add_item(item); } { @@ -335,6 +325,7 @@ void ReadInput::item_ofdft() } { Input_Item item("of_full_pw"); + item.add_choice_requirement({"false"}, "of_full_pw_dim==0"); item.annotation = "If set to 1, ecut will be ignored when collect " "planewaves, so that all planewaves will be used"; item.category = "OFDFT: orbital free density functional theory"; @@ -365,12 +356,6 @@ Note: Even dimensions may cause slight errors in FFT. It should be ignorable in item.unit = ""; item.set_availability("esolver_type==ofdft and of_full_pw==true"); read_sync_int(input.of_full_pw_dim); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (!para.input.of_full_pw) - { - para.input.of_full_pw_dim = 0; // sunliang add 2022-08-31 - } - }; this->add_item(item); } { diff --git a/source/source_io/module_parameter/read_inp_other.cpp b/source/source_io/module_parameter/read_inp_other.cpp index 473945f3686..0b5002b8767 100644 --- a/source/source_io/module_parameter/read_inp_other.cpp +++ b/source/source_io/module_parameter/read_inp_other.cpp @@ -200,6 +200,7 @@ When false (default), both the direction and magnitude of the magnetic moment ar // Quasiatomic Orbital analysis { Input_Item item("qo_switch"); + item.add_choice_requirement({"true"}, "out_wfc_lcao==1"); item.annotation = "switch to control quasiatomic orbital analysis"; item.category = "Quasiatomic Orbital (QO) analysis"; item.type = "Boolean"; @@ -804,16 +805,6 @@ When false (default), both the direction and magnitude of the magnetic moment ar item.default_value = "0.656"; item.unit = ""; read_sync_double(input.rdmft_power_alpha); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if( para.input.dft_functional == "hf" || para.input.dft_functional == "pbe0" ) - { - para.input.rdmft_power_alpha = 1.0; - } - else if( para.input.dft_functional == "muller" ) - { - para.input.rdmft_power_alpha = 0.5; - } - }; this->add_item(item); } diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index c519fa754cc..a5034321ea6 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -363,12 +363,6 @@ Also controled by out_freq_ion and out_app_flag. item.unit = ""; item.set_availability("basis_type==lcao"); read_sync_int(input.out_wfc_lcao); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.qo_switch) - { - para.input.out_wfc_lcao = 1; - } - }; this->add_item(item); } { @@ -506,12 +500,6 @@ The LDOS is evaluated once after all ionic steps finish; the cube header records item.default_value = "False"; item.unit = ""; read_sync_bool(input.out_proj_band); - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.calculation == "get_wf" || para.input.calculation == "get_pchg") - { - para.input.out_proj_band = false; - } - }; item.check_value = [](const Input_Item& item, const Parameter& para) { if (para.input.basis_type == "pw" && para.input.out_proj_band) { diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index 4ed7c74e1c4..208465e2ed8 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -148,6 +148,14 @@ void ReadInput::item_system() item.domain.set_choices({"scf", "relax", "md", "cell-relax", "nscf", "get_s", "get_wf", "get_pchg", "gen_bessel", "gen_opt_abfs", "test_memory", "test_neighbour"}); item.add_choice_requirement({"md", "relax", "cell-relax"}, "cal_force==true"); item.add_choice_requirement({"get_wf", "get_pchg", "get_s"}, "cal_force==false"); + item.add_choice_requirement({"cell-relax"}, "cal_stress==true"); + item.add_choice_requirement({"nscf"}, "scf_nmax==1"); + item.add_choice_requirement({"get_wf", "get_pchg"}, + "init_chg==atomic and chg_extrap==atomic and out_proj_band==false"); + item.add_choice_requirement({"get_wf"}, "bx==1 and by==1 and bz==1"); + item.add_requirement("calculation==md and (esolver_type in [lj, dp] or md_type in [msst, npt])", + "cal_stress==true"); + item.add_requirement("calculation==md and (md_tfirst<0 or md_restart==true)", "init_vel==true"); item.domain.add_requirement("calculation in [get_pchg, get_wf]", "basis_type!=pw"); item.domain.add_requirement("calculation==gen_bessel", "basis_type==pw"); item.annotation = "scf; relax; md; cell-relax; nscf; get_s; get_wf; get_pchg; gen_bessel; gen_opt_abfs; test_memory; test_neighbour"; @@ -237,6 +245,7 @@ Socket mode always computes energy. Force and stress extraction follows cal_forc } { Input_Item item("esolver_type"); + item.add_choice_requirement({"tddft"}, "exx_separate_loop==false"); item.annotation = "the energy solver: ksdft, sdft, ofdft, tdofdft, tddft, lj, dp, ks-lr, lr, dfpt"; item.category = "System variables"; item.type = "String"; @@ -330,6 +339,7 @@ Socket mode always computes energy. Force and stress extraction follows cal_forc { Input_Item item("symmetry"); item.domain.set_choices({"-1", "0", "1"}); + item.add_choice_requirement({"-1", "0"}, "exx_symmetry_realspace==false"); item.annotation = "the control of symmetry"; item.category = "System variables"; item.type = "String"; @@ -771,10 +781,6 @@ For `basis_type=lcao_in_pw`, `init_wfc` is automatically set to `nao`. item.default_value = "atomic"; read_sync_string(input.init_chg); item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.calculation == "get_pchg" || para.input.calculation == "get_wf") - { - para.input.init_chg = "atomic"; - } if (para.input.calculation == "nscf" || para.input.calculation == "get_s") { // dm and hr are valid options for nscf calculation (e.g., band structure, wannier90) @@ -806,15 +812,6 @@ For `basis_type=lcao_in_pw`, `init_wfc` is automatically set to `nao`. item.description = R"(* True: read the atom velocity (atomic unit : 1 a.u. = 21.877 Angstrom/fs) from the atom file (STRU) and determine the initial temperature md_tfirst. If md_tfirst is unset or less than zero, init_vel is autoset to be true. * False: assign value to atom velocity using Gaussian distributed random numbers.)"; item.default_value = "False"; - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.calculation == "md") - { - if (para.input.mdp.md_tfirst < 0 || para.input.mdp.md_restart) - { - para.input.init_vel = true; - } - } - }; read_sync_bool(input.init_vel); this->add_item(item); } @@ -845,20 +842,6 @@ Legal values are 0 and 1. For calculation=scf or relax, mem_saver must be 0; set item.description = R"(If set to True, calculate the stress at the end of the electronic iteration. In socket_driver mode, this flag independently controls whether the returned frame advertises stress/virial.)"; item.default_value = "False"; - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.calculation == "md") - { - if (para.input.esolver_type == "lj" || para.input.esolver_type == "dp" - || para.input.mdp.md_type == "msst" || para.input.mdp.md_type == "npt") - { - para.input.cal_stress = true; - } - } - else if (para.input.calculation == "cell-relax") - { - para.input.cal_stress = true; - } - }; read_sync_bool(input.cal_stress); this->add_item(item); } @@ -1197,10 +1180,6 @@ updates structures smoothly enough for second-order extrapolation.)"; { para.input.chg_extrap = "atomic"; } - if (para.input.calculation == "get_wf" || para.input.calculation == "get_pchg") - { - para.input.chg_extrap = "atomic"; - } }; this->add_item(item); } diff --git a/source/source_io/module_parameter/read_input.cpp b/source/source_io/module_parameter/read_input.cpp index 3d076ac5532..bd8287136c6 100644 --- a/source/source_io/module_parameter/read_input.cpp +++ b/source/source_io/module_parameter/read_input.cpp @@ -554,14 +554,40 @@ std::string ReadInput::prepare_input(Parameter& param) if (item->domain.bound()) { supplied_values[item->label] = item->domain.value(param); } } - // 2) reset this value when some conditions are met - // e.g. if (calulation_type == "nscf") then set "init_chg" to "file". + InputValues values; + const auto snapshot_values = [&]() { + for (const std::pair& entry : this->input_lists) + { + if (entry.second.domain.bound()) { values[entry.first] = entry.second.domain.value(param); } + } + }; + snapshot_values(); + + // Resolve each selector before applying its requirements, in registration order. + // For example, calculation supplies scf_nmax before out_freq_elec reads it; + // symmetry and EXX correction expand their automatic values before selecting rules. for (std::pair& input_item: this->input_lists) { Input_Item* resetvalue_item = &(input_item.second); if (resetvalue_item->reset_value != nullptr) { resetvalue_item->reset_value(*resetvalue_item, param); + snapshot_values(); + } + const std::vector defaults = resetvalue_item->domain.choice_defaults(values); + for (const AvailabilityCondition& required : defaults) + { + if (is_explicit(required.param)) { continue; } + const std::vector>::const_iterator target = std::find_if( + input_lists.begin(), input_lists.end(), + [&required](const std::pair& entry) { return entry.first == required.param; }); + Input_Item default_input(target->second); + default_input.str_values = required.values; + default_input.read_value(default_input, param); + const InputValue resolved = default_input.domain.value(param); + values[required.param] = resolved; + const std::string rendered = resolved.format(); + ModuleBase::GlobalFunc::AUTO_SET(required.param, rendered); } } @@ -603,12 +629,7 @@ std::string ReadInput::prepare_input(Parameter& param) errors += "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer.\n"; } - // Snapshot typed effective values once for shared domain and dependency checks. - InputValues values; - for (const std::pair& entry : this->input_lists) - { - if (entry.second.domain.bound()) { values[entry.first] = entry.second.domain.value(param); } - } + snapshot_values(); // Evaluate requirements with explicit values taking precedence over defaults, // so a reset cannot hide a conflicting user request. @@ -618,33 +639,12 @@ std::string ReadInput::prepare_input(Parameter& param) requested_values[supplied.first] = supplied.second; } - // Select rules from one snapshot, then fill omitted scalar values through - // their existing readers. Do not record these generated values as explicit. - std::vector defaults; - for (const std::pair& entry : this->input_lists) - { - const std::vector required = entry.second.domain.choice_defaults(requested_values); - defaults.insert(defaults.end(), required.begin(), required.end()); - } - for (const AvailabilityCondition& required : defaults) - { - if (is_explicit(required.param)) { continue; } - const std::vector>::const_iterator target = std::find_if( - input_lists.begin(), input_lists.end(), - [&required](const std::pair& entry) { return entry.first == required.param; }); - Input_Item default_input(target->second); - default_input.str_values = required.values; - default_input.read_value(default_input, param); - const InputValue resolved = default_input.domain.value(param); - values[required.param] = resolved; - requested_values[required.param] = resolved; - const std::string rendered = resolved.format(); - ModuleBase::GlobalFunc::AUTO_SET(required.param, rendered); - } - + // Legacy validation-only rules still inspect the original request. New rules + // preserve explicit targets above and validate the effective configuration below, + // allowing documented automatic values and aliases to finish normalizing. for (const std::pair& entry : this->input_lists) { - errors += entry.second.domain.validate_requirements(entry.first, requested_values); + errors += entry.second.domain.validate_requirements(entry.first, requested_values, false); } if (!errors.empty()) { return errors; } diff --git a/source/source_io/module_parameter/read_input_item_md.cpp b/source/source_io/module_parameter/read_input_item_md.cpp index e40190c7894..4148a7a88bb 100644 --- a/source/source_io/module_parameter/read_input_item_md.cpp +++ b/source/source_io/module_parameter/read_input_item_md.cpp @@ -252,6 +252,7 @@ Note: It is a system-dependent empirical parameter, ranging from 1/(40*md_dt) to } { Input_Item item("md_pmode"); + item.add_choice_requirement({"iso"}, "md_pcouple==xyz"); item.annotation = "NPT ensemble mode: iso, aniso, tri"; item.category = "Molecular dynamics"; item.type = "String"; @@ -312,12 +313,6 @@ Note: It is a system-dependent empirical parameter, ranging from 1/(40*md_dt) to * yz: Lattice vectors y and z scale proportionally.)"; item.default_value = "none"; item.unit = ""; - item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.mdp.md_pmode == "iso") - { - para.input.mdp.md_pcouple = "xyz"; - } - }; read_sync_string(input.mdp.md_pcouple); this->add_item(item); } diff --git a/source/source_io/unittests/support/INPUT b/source/source_io/unittests/support/INPUT index 8ffc59e437d..05738c31226 100644 --- a/source/source_io/unittests/support/INPUT +++ b/source/source_io/unittests/support/INPUT @@ -213,7 +213,7 @@ cal_syns 0 #calculate asynchronous overlap matrix to outpu dmax 0.01 #maximum displacement of all atoms in one step (bohr) md_tolerance 100 #tolerance for velocity rescaling (K) md_pmode iso #NPT ensemble mode: iso, aniso, tri -md_pcouple none #whether couple different components: xyz, xy, yz, xz, none +md_pcouple xyz #whether couple different components: xyz, xy, yz, xz, none md_pchain 1 #num of thermostats coupled with barostat md_pfirst -1 #initial target pressure md_plast -1 #final target pressure @@ -363,7 +363,7 @@ of_vw_weight 1 #weight of vW KEDF of_wt_alpha 0.833333 #parameter alpha of WT KEDF of_wt_beta 0.833333 #parameter beta of WT KEDF of_wt_rho0 1 #the average density of system, used in WT KEDF, in Bohr^-3 -of_hold_rho0 0 #If set to 1, the rho0 will be fixed even if the volume of system has changed, it will be set to 1 automaticly if of_wt_rho0 is not zero +of_hold_rho0 1 #If set to 1, the rho0 will be fixed even if the volume of system has changed, it will be set to 1 automaticly if of_wt_rho0 is not zero of_full_pw 0 #If set to 1, ecut will be ignored when collect planewaves, so that all planewaves will be used of_full_pw_dim 0 #If of_full_pw = true, dimention of FFT is testricted to be (0) either odd or even; (1) odd only; (2) even only of_read_kernel 0 #If set to 1, the kernel of WT KEDF will be filled from file of_kernel_file, not from formula. Only usable for WT KEDF diff --git a/source/source_io/unittests/test_input_domain_reader.cpp b/source/source_io/unittests/test_input_domain_reader.cpp index a537747e110..16da919611e 100644 --- a/source/source_io/unittests/test_input_domain_reader.cpp +++ b/source/source_io/unittests/test_input_domain_reader.cpp @@ -217,6 +217,103 @@ TEST_F(InputDomainReaderTest, InactiveRequirementsPreserveValuesAndExplicitPrese EXPECT_NE(error.find("Invalid INPUT parameter 'cal_force': supplied ''. Expected one Boolean"), std::string::npos); } +TEST_F(InputDomainReaderTest, NscfRequirementPrecedesOutputFrequencyDefault) +{ + for (const bool explicit_frequency : {false, true}) + { + const std::string fields = explicit_frequency ? "out_freq_elec 7\ncalculation nscf\n" + : "calculation nscf\n"; + write_input(fields); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.scf_nmax, 1); + const int expected_frequency = explicit_frequency ? 7 : 1; + EXPECT_EQ(input.inp.out_freq_elec, expected_frequency); + EXPECT_FALSE(reader.is_explicit("scf_nmax")); + EXPECT_EQ(reader.is_explicit("out_freq_elec"), explicit_frequency); + } +} + +TEST_F(InputDomainReaderTest, RequirementsUseNormalizedBasisAndAutomaticChargeExtrapolation) +{ + write_input("calculation nscf\ntowannier90 true\nbx 2\nby 3\nbz 4\n", "lcao_in_pw"); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.basis_type, "lcao"); + EXPECT_EQ(input.inp.bx, 2); + EXPECT_EQ(input.inp.by, 3); + EXPECT_EQ(input.inp.bz, 4); + + write_input("calculation get_wf\nchg_extrap default\n", "lcao"); + ModuleIO::ReadInput next_reader(0); + next_reader.check_ntype_flag = false; + Parameter next; + next_reader.read_parameters(next, filename); + EXPECT_EQ(next.inp.chg_extrap, "atomic"); + EXPECT_TRUE(next_reader.is_explicit("chg_extrap")); +} + +TEST_F(InputDomainReaderTest, SymmetryRequirementUsesResolvedValue) +{ + for (const bool md : {false, true}) + { + const std::string fields = md ? "calculation md\nmd_tfirst 300\nsymmetry 1\n" : ""; + write_input(fields); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + const std::string expected_symmetry = md ? "0" : "1"; + EXPECT_EQ(input.inp.symmetry, expected_symmetry); + EXPECT_EQ(input.inp.exx_symmetry_realspace, !md); + } + const std::string error = reject_input("symmetry default\n"); + EXPECT_NE(error.find("Expected one String from {-1, 0, 1}"), std::string::npos); +} + +TEST_F(InputDomainReaderTest, ExxRequirementFollowsAutomaticCorrectionSelection) +{ + for (const std::string& correction : {"", "exx_singularity_correction default\n", + "exx_singularity_correction limits\n"}) + { + const std::string fields = "dft_functional hse\n" + correction; + write_input(fields); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.inp.exx_singularity_correction, "limits"); + EXPECT_FALSE(input.inp.exx_gamma_extra); + EXPECT_FALSE(reader.is_explicit("exx_gamma_extra")); + const std::string conflict = fields + "exx_gamma_extra true\n"; + const std::string error = reject_input(conflict); + EXPECT_NE(error.find("exx_singularity_correction=limits"), std::string::npos); + EXPECT_NE(error.find("Requires exx_gamma_extra==false"), std::string::npos); + } +} + +TEST_F(InputDomainReaderTest, InactiveFixedRequirementsPreserveExplicitValues) +{ + write_input("md_pmode aniso\nmd_pcouple xy\ncal_stress false\ninit_vel false\n" + "of_wt_rho0 0\nof_hold_rho0 false\nof_kinetic wt\nof_read_kernel true\n" + "of_full_pw true\nof_full_pw_dim 1\nrdmft_power_alpha 0.75\n"); + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + Parameter input; + reader.read_parameters(input, filename); + EXPECT_EQ(input.mdp.md_pcouple, "xy"); + EXPECT_FALSE(input.inp.cal_stress); + EXPECT_FALSE(input.inp.init_vel); + EXPECT_FALSE(input.inp.of_hold_rho0); + EXPECT_TRUE(input.inp.of_read_kernel); + EXPECT_EQ(input.inp.of_full_pw_dim, 1); + EXPECT_DOUBLE_EQ(input.inp.rdmft_power_alpha, 0.75); +} + TEST_F(InputDomainReaderTest, ReportsIndependentErrorsTogether) { const std::string output = reject_input("nspin 3\ngga_grad -1\n"); diff --git a/source/source_io/unittests/test_read_input.cmake b/source/source_io/unittests/test_read_input.cmake index f77561d04ea..6d821d600c1 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -40,7 +40,8 @@ elseif(INPUT_CASE STREQUAL "bse_requirement_conflict") set(expected "Requires bse_continue==0 and bse_ri_hartree==true") set(expected_manual "input-main.html#bse-mem-save") elseif(INPUT_CASE STREQUAL "md_force_default") - string(APPEND contents "suffix force_bcast\ncalculation md\nmd_tfirst 300\n") + string(APPEND contents "suffix force_bcast\ncalculation md\nmd_tfirst 300\n" + "md_type npt\nmd_pmode iso\nof_wt_rho0 1\n") set(expected_exit 0) elseif(INPUT_CASE STREQUAL "unsupported_libxc_cuda") string(APPEND contents "device gpu\ndevice_xc gpu\n") @@ -154,11 +155,13 @@ if(DEFINED expected_dc) endif() endif() if(INPUT_CASE STREQUAL "md_force_default") - string(REGEX MATCHALL "Force received: 1[\r\n]" received "${output}") + string(REGEX MATCHALL "Required defaults received: 1 1 xyz 1[\r\n]" received + "${output}") list(LENGTH received received_count) if(NOT received_count EQUAL 4) message( FATAL_ERROR - "Only ${received_count} of 4 ranks received cal_force=true:\n${output}") + "Only ${received_count} of 4 ranks received the required defaults:\n${output}" + ) endif() endif() diff --git a/source/source_io/unittests/test_read_input.cpp b/source/source_io/unittests/test_read_input.cpp index 602f9190e8a..b6a563e6fd4 100644 --- a/source/source_io/unittests/test_read_input.cpp +++ b/source/source_io/unittests/test_read_input.cpp @@ -45,7 +45,8 @@ int main(int argc, char** argv) reader.read_parameters(input, filename); if (input.inp.suffix == "force_bcast") { - std::printf("Force received: %d\n", input.inp.cal_force); + std::printf("Required defaults received: %d %d %s %d\n", input.inp.cal_force, input.inp.cal_stress, + input.mdp.md_pcouple.c_str(), input.inp.of_hold_rho0); } if (input.inp.suffix == "dftu_dc_bcast") { diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 482843bff29..567b93e7021 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -170,6 +170,101 @@ TEST_F(InputTest, ChoiceRequirementsFillOnlyOmittedParameters) } } +TEST_F(InputTest, FixedRequirementsPreserveExplicitValuesInEitherOrder) +{ + struct RequirementCase + { + std::string fields; + std::string target; + std::string required; + std::string conflict; + std::string basis; + }; + const RequirementCase cases[] = { + {"calculation cell-relax\n", "cal_stress", "true", "false", "pw"}, + {"calculation md\nesolver_type lj\n", "cal_stress", "true", "false", "pw"}, + {"calculation md\nesolver_type dp\n", "cal_stress", "true", "false", "pw"}, + {"calculation md\nmd_type msst\n", "cal_stress", "true", "false", "pw"}, + {"calculation md\nmd_type npt\n", "cal_stress", "true", "false", "pw"}, + {"calculation md\n", "init_vel", "true", "false", "pw"}, + {"calculation md\nmd_tfirst 300\nmd_restart true\n", "init_vel", "true", "false", "pw"}, + {"calculation get_wf\n", "init_chg", "atomic", "file", "lcao"}, + {"calculation get_pchg\n", "init_chg", "atomic", "file", "lcao"}, + {"calculation get_wf\n", "chg_extrap", "atomic", "second-order", "lcao"}, + {"calculation get_pchg\n", "chg_extrap", "atomic", "second-order", "lcao"}, + {"calculation get_wf\n", "out_proj_band", "false", "true", "lcao"}, + {"calculation get_pchg\n", "out_proj_band", "false", "true", "lcao"}, + {"calculation nscf\n", "scf_nmax", "1", "20", "pw"}, + {"", "bx", "1", "2", "pw"}, + {"", "by", "1", "2", "pw"}, + {"", "bz", "1", "2", "pw"}, + {"", "bx", "1", "2", "lcao_in_pw"}, + {"", "by", "1", "2", "lcao_in_pw"}, + {"", "bz", "1", "2", "lcao_in_pw"}, + {"calculation get_wf\n", "bx", "1", "2", "lcao"}, + {"calculation get_wf\n", "by", "1", "2", "lcao"}, + {"calculation get_wf\n", "bz", "1", "2", "lcao"}, + {"md_pmode iso\n", "md_pcouple", "xyz", "none", "pw"}, + {"deepks_out_unittest true\n", "deepks_out_labels", "1", "0", "lcao"}, + {"deepks_out_unittest true\n", "deepks_scf", "true", "false", "lcao"}, + {"qo_switch true\n", "out_wfc_lcao", "1", "0", "lcao"}, + {"dft_functional hf\n", "rdmft_power_alpha", "1", "0.5", "lcao"}, + {"dft_functional pbe0\n", "rdmft_power_alpha", "1", "0.5", "lcao"}, + {"dft_functional muller\n", "rdmft_power_alpha", "0.5", "1", "lcao"}, + {"esolver_type tddft\n", "exx_separate_loop", "false", "true", "pw"}, + {"symmetry 0\n", "exx_symmetry_realspace", "false", "true", "lcao"}, + {"symmetry -1\n", "exx_symmetry_realspace", "false", "true", "lcao"}, + {"dft_functional hse\nexx_singularity_correction limits\n", "exx_gamma_extra", "false", "true", "pw"}, + {"of_wt_rho0 1\n", "of_hold_rho0", "true", "false", "pw"}, + {"of_kinetic tf\n", "of_read_kernel", "false", "true", "pw"}, + {"of_full_pw false\n", "of_full_pw_dim", "0", "1", "pw"}}; + const std::string filename = testing::TempDir() + "abacus_fixed_requirements_INPUT"; + for (const RequirementCase& rule : cases) + { + SCOPED_TRACE(rule.target); + SCOPED_TRACE(rule.fields); + SCOPED_TRACE(rule.basis); + const std::string solver = rule.basis == "pw" ? "cg" : "lapack"; + const std::string context = "basis_type " + rule.basis + "\nks_solver " + solver + + "\nntype 1\necutwfc 20\n" + rule.fields; + for (const std::string& supplied : {std::string(), rule.required, rule.conflict}) + { + SCOPED_TRACE(supplied); + const bool explicit_value = !supplied.empty(); + const std::string target_line = explicit_value ? rule.target + " " + supplied + "\n" : ""; + const int order_count = explicit_value ? 2 : 1; + for (int order = 0; order < order_count; ++order) + { + SCOPED_TRACE(order); + const std::string fields = order == 0 ? context + target_line : target_line + context; + { + std::ofstream input(filename.c_str()); + input << "INPUT_PARAMETERS\n" << fields; + ASSERT_TRUE(input.good()); + } + ModuleIO::ReadInput reader(0); + Parameter param; + const std::string error = reader.read_txt_input(param, filename); + std::remove(filename.c_str()); + if (supplied == rule.conflict) + { + EXPECT_THAT(error, testing::HasSubstr("Requires")); + EXPECT_THAT(error, testing::HasSubstr(rule.target)); + } + else + { + EXPECT_TRUE(error.empty()) << error; + } + const ModuleIO::Input_Item& target = find_label(rule.target, reader.input_lists)->second; + const std::string actual = target.domain.value(param).format(); + const std::string expected = explicit_value ? supplied : rule.required; + EXPECT_EQ(actual, expected); + EXPECT_EQ(reader.is_explicit(rule.target), explicit_value); + } + } + } +} + TEST_F(InputTest, MdThermoFrequencyUsesOnlyOutName) { ModuleIO::ReadInput reader(0); @@ -808,11 +903,6 @@ TEST_F(InputTest, Item_test) } { // init_chg std::vector>::iterator it = find_label("init_chg", readinput.input_lists); - TestParameters::input(param).init_chg = "get_pchg"; - TestParameters::input(param).init_chg = ""; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).init_chg, "atomic"); - TestParameters::input(param).init_chg = ""; TestParameters::input(param).calculation = "nscf"; it->second.reset_value(it->second, param); @@ -847,11 +937,6 @@ TEST_F(InputTest, Item_test) TestParameters::input(param).socket_driver = false; it->second.reset_value(it->second, param); EXPECT_EQ(TestParameters::input(param).chg_extrap, "atomic"); - - TestParameters::input(param).chg_extrap = "none"; - TestParameters::input(param).calculation = "get_wf"; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).chg_extrap, "atomic"); } { // out_chg std::vector>::iterator it = find_label("out_chg", readinput.input_lists); @@ -1067,11 +1152,6 @@ TEST_F(InputTest, Item_test) } { // out_proj_band std::vector>::iterator it = find_label("out_proj_band", readinput.input_lists); - TestParameters::input(param).calculation = "get_wf"; - TestParameters::input(param).out_proj_band = true; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).out_proj_band, false); - TestParameters::input(param).basis_type = "pw"; TestParameters::input(param).out_proj_band = true; testing::internal::CaptureStdout(); @@ -1293,14 +1373,6 @@ TEST_F(InputTest, Item_test) it->second.reset_value(it->second, param); EXPECT_EQ(TestParameters::input(param).out_stru, 0); } - { // cal_stress - std::vector>::iterator it = find_label("cal_stress", readinput.input_lists); - TestParameters::input(param).calculation = "md"; - TestParameters::input(param).cal_stress = false; - TestParameters::input(param).esolver_type = "lj"; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).cal_stress, true); - } { // fixed_axes std::vector>::iterator it = find_label("fixed_axes", readinput.input_lists); TestParameters::input(param).fixed_axes = "shape"; @@ -1913,11 +1985,6 @@ TEST_F(InputTest, Item_test2) } { // out_wfc_lcao std::vector>::iterator it = find_label("out_wfc_lcao", readinput.input_lists); - TestParameters::input(param).out_wfc_lcao = false; - TestParameters::input(param).qo_switch = true; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).out_wfc_lcao, true); - TestParameters::input(param).out_wfc_lcao = -1; testing::internal::CaptureStdout(); EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); @@ -1938,13 +2005,6 @@ TEST_F(InputTest, Item_test2) EXPECT_EXIT(check_item(it->second, param), ::testing::ExitedWithCode(1), ""); output = testing::internal::GetCapturedStdout(); EXPECT_THAT(output, testing::HasSubstr("NOTICE")); - - TestParameters::input(param).bx = 2; - TestParameters::input(param).basis_type = "pw"; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).bx, 1); - EXPECT_EQ(TestParameters::input(param).by, 1); - EXPECT_EQ(TestParameters::input(param).bz, 1); } { // by std::vector>::iterator it = find_label("by", readinput.input_lists); @@ -2314,18 +2374,8 @@ TEST_F(InputTest, Item_test2) TestParameters::input(param).dft_functional = "HSE"; TestParameters::input(param).exx_singularity_correction = "default"; - TestParameters::input(param).exx_gamma_extra = true; it->second.reset_value(it->second, param); EXPECT_EQ(TestParameters::input(param).exx_singularity_correction, "limits"); - EXPECT_FALSE(TestParameters::input(param).exx_gamma_extra); - - std::vector>::iterator gamma = find_label("exx_gamma_extra", readinput.input_lists); - gamma->second.str_values = {"true"}; - TestParameters::input(param).exx_gamma_extra = true; - it->second.reset_value(it->second, param); - EXPECT_TRUE(TestParameters::input(param).exx_gamma_extra); - gamma->second.str_values.clear(); - TestParameters::input(param).exx_gamma_extra = false; } { // exx_ccp_rmesh_times std::vector>::iterator it = find_label("exx_ccp_rmesh_times", readinput.input_lists); @@ -2376,13 +2426,6 @@ TEST_F(InputTest, Item_test2) output = testing::internal::GetCapturedStdout(); EXPECT_THAT(output, testing::HasSubstr("NOTICE")); } - { // exx_symmetry_realspace - std::vector>::iterator it = find_label("exx_symmetry_realspace", readinput.input_lists); - TestParameters::input(param).exx_symmetry_realspace = true; - TestParameters::input(param).symmetry="0"; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).exx_symmetry_realspace, false); - } { // rpa_ccp_rmesh_times std::vector>::iterator it = find_label("rpa_ccp_rmesh_times", readinput.input_lists); TestParameters::input(param).rpa_ccp_rmesh_times = 0; @@ -2489,27 +2532,6 @@ TEST_F(InputTest, Item_test2) it->second.reset_value(it->second, param); EXPECT_EQ(TestParameters::input(param).wannier_method, 1); } - { // of_hold_rho0 - std::vector>::iterator it = find_label("of_hold_rho0", readinput.input_lists); - TestParameters::input(param).of_wt_rho0 = 1; - TestParameters::input(param).of_hold_rho0 = false; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).of_hold_rho0, true); - } - { // of_full_pw_dim - std::vector>::iterator it = find_label("of_full_pw_dim", readinput.input_lists); - TestParameters::input(param).of_full_pw = false; - TestParameters::input(param).of_full_pw_dim = 1; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).of_full_pw_dim, 0); - } - { // of_read_kernel - std::vector>::iterator it = find_label("of_read_kernel", readinput.input_lists); - TestParameters::input(param).of_read_kernel = true; - TestParameters::input(param).of_kinetic = "none"; - it->second.reset_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).of_read_kernel, false); - } { // of_ml_gene_data std::vector>::iterator it = find_label("of_ml_gene_data", readinput.input_lists); From 51301dc0f6d85be4d4f5b1ff593555a4098c97b9 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Thu, 3 Dec 2026 04:25:21 +0800 Subject: [PATCH 07/11] refactor(input): attach MD requirements to their direct controls --- docs/developers_guide/input_validation.md | 21 +++++++------------ .../module_parameter/read_inp_sys.cpp | 4 +--- .../module_parameter/read_input_item_md.cpp | 3 +++ .../unittests/test_input_domain_reader.cpp | 13 ++++++++++++ 4 files changed, 25 insertions(+), 16 deletions(-) diff --git a/docs/developers_guide/input_validation.md b/docs/developers_guide/input_validation.md index 4a2b2e8c4a3..2d6bb5f84f3 100644 --- a/docs/developers_guide/input_validation.md +++ b/docs/developers_guide/input_validation.md @@ -12,19 +12,14 @@ with custom input syntax keep their own parsing rules. | A requirement shared by options | `item.add_choice_requirement({"md", "relax", "cell-relax"}, "cal_force==true");` (in `calculation`) | | A conditional fixed requirement | `item.add_requirement("of_wt_rho0!=0", "of_hold_rho0==true");` (in `of_wt_rho0`) | -For these two `Input_Item` requirement methods, the reader fills omitted values from fixed scalar -equalities (including `and`); explicit conflicts use the existing requirement -diagnostic. `in`, ranges and `or` only validate, without choosing a default. -Register each rule on its controlling parameter. In registration order, the -reader runs that parameter's remaining reset callback, selects its rules from -one effective-value snapshot, then supplies omitted values. Keep the controller -before callbacks that consume those values (for example, `calculation` before -`out_freq_elec`); there is no dependency sorting or repeated resolution. -Final validation checks these rules after automatic values and aliases have -been resolved. Existing `domain.add_requirement` declarations remain -validation-only and also check original explicit values. -`ReadInput::is_explicit(label)` queries -keyword presence on the parsing rank, including explicit `0` and `false`. +The two `Input_Item` methods fill omitted values from fixed scalar equalities +(including `and`) and reject explicit conflicts. `in`, ranges and `or` only +validate; `domain.add_requirement` is always validation-only. +Register a rule on the parameter that directly triggers it: an MD restart +requirement belongs to `md_restart`, with `calculation==md` as its scope. +Keep controlling parameters before defaults that depend on their requirements. +Use `ReadInput::is_explicit(label)` to query keyword presence, including explicit +`0` and `false`. Use `item.set_availability(...)` to describe when a parameter applies. Use `add_requirement(...)` when an incompatible combination should produce an diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index 208465e2ed8..70e1de354c9 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -153,9 +153,6 @@ void ReadInput::item_system() item.add_choice_requirement({"get_wf", "get_pchg"}, "init_chg==atomic and chg_extrap==atomic and out_proj_band==false"); item.add_choice_requirement({"get_wf"}, "bx==1 and by==1 and bz==1"); - item.add_requirement("calculation==md and (esolver_type in [lj, dp] or md_type in [msst, npt])", - "cal_stress==true"); - item.add_requirement("calculation==md and (md_tfirst<0 or md_restart==true)", "init_vel==true"); item.domain.add_requirement("calculation in [get_pchg, get_wf]", "basis_type!=pw"); item.domain.add_requirement("calculation==gen_bessel", "basis_type==pw"); item.annotation = "scf; relax; md; cell-relax; nscf; get_s; get_wf; get_pchg; gen_bessel; gen_opt_abfs; test_memory; test_neighbour"; @@ -246,6 +243,7 @@ Socket mode always computes energy. Force and stress extraction follows cal_forc { Input_Item item("esolver_type"); item.add_choice_requirement({"tddft"}, "exx_separate_loop==false"); + item.add_requirement("esolver_type in [lj, dp] and calculation==md", "cal_stress==true"); item.annotation = "the energy solver: ksdft, sdft, ofdft, tdofdft, tddft, lj, dp, ks-lr, lr, dfpt"; item.category = "System variables"; item.type = "String"; diff --git a/source/source_io/module_parameter/read_input_item_md.cpp b/source/source_io/module_parameter/read_input_item_md.cpp index 4148a7a88bb..853fd0ca546 100644 --- a/source/source_io/module_parameter/read_input_item_md.cpp +++ b/source/source_io/module_parameter/read_input_item_md.cpp @@ -13,6 +13,7 @@ void ReadInput::item_md() { Input_Item item("md_type"); item.domain.set_choices({"fire", "nve", "nvt", "npt", "langevin", "msst"}); + item.add_requirement("md_type in [msst, npt] and calculation==md", "cal_stress==true"); item.annotation = "choose ensemble"; item.category = "Molecular dynamics"; item.type = "String"; @@ -91,6 +92,7 @@ void ReadInput::item_md() } { Input_Item item("md_tfirst"); + item.add_requirement("md_tfirst<0 and calculation==md", "init_vel==true"); item.annotation = "temperature first"; item.category = "Molecular dynamics"; item.type = "Real"; @@ -155,6 +157,7 @@ Note that md_tlast is only used in NVT/NPT simulations. If md_tlast is unset or } { Input_Item item("md_restart"); + item.add_requirement("md_restart==true and calculation==md", "init_vel==true"); item.annotation = "whether restart"; item.category = "Molecular dynamics"; item.type = "Boolean"; diff --git a/source/source_io/unittests/test_input_domain_reader.cpp b/source/source_io/unittests/test_input_domain_reader.cpp index 16da919611e..a6ae010d438 100644 --- a/source/source_io/unittests/test_input_domain_reader.cpp +++ b/source/source_io/unittests/test_input_domain_reader.cpp @@ -678,6 +678,19 @@ TEST(InputDomainHelp, ExportsTheRuntimeRules) std::string::npos); EXPECT_NE(calculation.requirements.find("When calculation in [get_wf, get_pchg, get_s]: require cal_force==false"), std::string::npos); + EXPECT_EQ(calculation.requirements.find("md_type"), std::string::npos); + EXPECT_EQ(calculation.requirements.find("md_tfirst"), std::string::npos); + EXPECT_EQ(calculation.requirements.find("md_restart"), std::string::npos); + for (const std::pair& rule : + std::vector>{ + {"esolver_type", "When esolver_type in [lj, dp] and calculation==md: require cal_stress==true"}, + {"md_type", "When md_type in [msst, npt] and calculation==md: require cal_stress==true"}, + {"md_tfirst", "When md_tfirst<0 and calculation==md: require init_vel==true"}, + {"md_restart", "When md_restart==true and calculation==md: require init_vel==true"}}) + { + const ModuleIO::ParameterMetadata owner = ModuleIO::ParameterHelp::get_metadata(rule.first); + EXPECT_NE(owner.requirements.find(rule.second), std::string::npos) << rule.first; + } const ModuleIO::ParameterMetadata bse = ModuleIO::ParameterHelp::get_metadata("bse_mem_save"); EXPECT_NE(bse.requirements.find("When bse_mem_save==true: require bse_continue==0 and bse_ri_hartree==true"), std::string::npos); From 12f41e9fab1a8ffc8f26f778fd42da25e62162a1 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Thu, 3 Dec 2026 04:37:07 +0800 Subject: [PATCH 08/11] docs(input): group complete option requirements in tables --- docs/generate_input_main.py | 45 ++++++++++++++++++++++++++++-- docs/test_generate_input_main.py | 48 ++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/docs/generate_input_main.py b/docs/generate_input_main.py index deff16ef74c..cb68777b83a 100755 --- a/docs/generate_input_main.py +++ b/docs/generate_input_main.py @@ -162,6 +162,43 @@ def replace(match): ) return re.sub(left_parameter, replace, availability) + +def format_requirements(name: str, requirements: str, + name_anchors: Dict[str, str]) -> str: + """Group options by their complete requirements, retaining compound conditions.""" + option_rules = OrderedDict() + condition_rules = OrderedDict() + for rule in requirements.split('; '): + when, required = rule[5:].split(': require ', 1) if rule.startswith('When ') else ('Always', rule) + selected = re.fullmatch(re.escape(name) + r'(?:==([-\w.]+)| in \[([-\w., ]+)\])', when) + if selected: + options = (selected.group(1) or selected.group(2)).split(', ') + rows = option_rules + else: + options = [when] + rows = condition_rules + for option in options: + collected = rows.setdefault(option, []) + if required not in collected: + collected.append(required) + + groups = OrderedDict() + for option, required in option_rules.items(): + groups.setdefault(frozenset(required), []).append(option) + rows = [(', '.join(f'`{option}`' for option in options), option_rules[options[0]]) + for options in groups.values()] + rows.extend(condition_rules.items()) + + def cell(text): + return escape_md_text(link_availability(text, name_anchors)).replace('|', r'\|') + + heading = 'Option / condition' if condition_rules else 'Option' + lines = ['**Requirements**', '', f'| {heading} | Requirements |', '| --- | --- |'] + for condition, required in rows: + lines.append(f'| {cell(condition)} | ' + '
'.join(cell(item) for item in required) + ' |') + return '\n'.join(lines) + + def generate_parameter_markdown(param: Dict[str, str], name_anchors: Dict[str, str]) -> str: """ @@ -179,9 +216,11 @@ def generate_parameter_markdown(param: Dict[str, str], choices = ', '.join(escape_md_text(value) for value in param['allowed_values']) lines.append(f"- **Allowed values**: {choices}") - for key, title in [('value_rule', 'Legal range'), ('requirements', 'Requirements')]: - if param.get(key): - lines.append(f"- **{title}**: " + link_availability(str(param[key]), name_anchors)) + if param.get('value_rule'): + lines.append('- **Legal range**: ' + link_availability(str(param['value_rule']), name_anchors)) + + if param.get('requirements'): + lines.extend(['', format_requirements(param['name'], str(param['requirements']), name_anchors), '']) # Availability (before description, as in original format) if param.get('availability', '') != '': diff --git a/docs/test_generate_input_main.py b/docs/test_generate_input_main.py index 0b8ab0ac3ef..a727411d6fc 100644 --- a/docs/test_generate_input_main.py +++ b/docs/test_generate_input_main.py @@ -26,6 +26,54 @@ def test_undeclared_domain_is_not_an_empty_restriction(self): rendered = generate_parameter_markdown({"name": "legacy", "type": "Real"}, {}) self.assertNotIn("Allowed values", rendered) + def test_overlapping_option_groups_collect_complete_requirements(self): + rendered = generate_parameter_markdown( + {"name": "mode", "requirements": + "When mode in [fast, precise]: require forces==true; " + "When mode in [precise, extended]: require stress==true"}, {}, + ) + rows = [line for line in rendered.splitlines() if line.startswith("|")][2:] + self.assertEqual(rows, [ + "| `fast` | forces==true |", + "| `precise` | forces==true
stress==true |", + "| `extended` | stress==true |", + ]) + + def test_equivalent_complete_sets_merge_despite_rule_order_and_duplicates(self): + rendered = generate_parameter_markdown( + {"name": "mode", "requirements": + "When mode==alpha: require forces==true; " + "When mode==beta: require stress==true; " + "When mode==alpha: require stress==true; " + "When mode==beta: require forces==true; " + "When mode==alpha: require forces==true"}, {}, + ) + rows = [line for line in rendered.splitlines() if line.startswith("|")][2:] + self.assertEqual(rows, ["| `alpha`, `beta` | forces==true
stress==true |"]) + + def test_compound_conditions_keep_context_and_render_linked_table_cells(self): + rendered = generate_parameter_markdown( + {"name": "calculation", "default_value": "scf", "requirements": + "When calculation==md and (ensemble in [npt, msst] or solver==lj): " + "require stress==true and (pressure<0 or automatic==true); " + "When calculation==md: require forces==true; " + "When calculation==md: require limit<10"}, + {name: "#" + name for name in + ("calculation", "ensemble", "solver", "stress", "pressure", + "automatic", "forces", "limit", "md")}, + ) + self.assertIn("**Requirements**\n\n| Option / condition | Requirements |", rendered) + rows = [line for line in rendered.splitlines() if line.startswith("|")][2:] + self.assertEqual(rows, [ + "| `md` | [`forces`](#forces)==true
[`limit`](#limit)<10 |", + "| [`calculation`](#calculation)==md and " + "([`ensemble`](#ensemble) in [npt, msst] or [`solver`](#solver)==lj) | " + "[`stress`](#stress)==true and " + "([`pressure`](#pressure)<0 or [`automatic`](#automatic)==true) |", + ]) + self.assertNotIn("[`md`](#md)", rendered) + self.assertIn(rows[-1] + "\n\n- **Default**: scf", rendered) + if __name__ == "__main__": unittest.main() From dc2262f66a8b3785916c8dd4f051db4ea27d8a33 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Thu, 3 Dec 2026 04:43:19 +0800 Subject: [PATCH 09/11] docs(input): join displayed requirements with and --- docs/generate_input_main.py | 4 +++- docs/test_generate_input_main.py | 11 ++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/generate_input_main.py b/docs/generate_input_main.py index cb68777b83a..4536e683ff5 100755 --- a/docs/generate_input_main.py +++ b/docs/generate_input_main.py @@ -195,7 +195,9 @@ def cell(text): heading = 'Option / condition' if condition_rules else 'Option' lines = ['**Requirements**', '', f'| {heading} | Requirements |', '| --- | --- |'] for condition, required in rows: - lines.append(f'| {cell(condition)} | ' + '
'.join(cell(item) for item in required) + ' |') + clauses = [f'({item})' if len(required) > 1 and ' or ' in item else item for item in required] + requirement = ' and '.join(clauses) + lines.append(f'| {cell(condition)} | {cell(requirement)} |') return '\n'.join(lines) diff --git a/docs/test_generate_input_main.py b/docs/test_generate_input_main.py index a727411d6fc..09b76269ed3 100644 --- a/docs/test_generate_input_main.py +++ b/docs/test_generate_input_main.py @@ -35,7 +35,7 @@ def test_overlapping_option_groups_collect_complete_requirements(self): rows = [line for line in rendered.splitlines() if line.startswith("|")][2:] self.assertEqual(rows, [ "| `fast` | forces==true |", - "| `precise` | forces==true
stress==true |", + "| `precise` | forces==true and stress==true |", "| `extended` | stress==true |", ]) @@ -49,7 +49,7 @@ def test_equivalent_complete_sets_merge_despite_rule_order_and_duplicates(self): "When mode==alpha: require forces==true"}, {}, ) rows = [line for line in rendered.splitlines() if line.startswith("|")][2:] - self.assertEqual(rows, ["| `alpha`, `beta` | forces==true
stress==true |"]) + self.assertEqual(rows, ["| `alpha`, `beta` | forces==true and stress==true |"]) def test_compound_conditions_keep_context_and_render_linked_table_cells(self): rendered = generate_parameter_markdown( @@ -57,15 +57,16 @@ def test_compound_conditions_keep_context_and_render_linked_table_cells(self): "When calculation==md and (ensemble in [npt, msst] or solver==lj): " "require stress==true and (pressure<0 or automatic==true); " "When calculation==md: require forces==true; " - "When calculation==md: require limit<10"}, + "When calculation==md: require limit<10 or unlimited==true"}, {name: "#" + name for name in ("calculation", "ensemble", "solver", "stress", "pressure", - "automatic", "forces", "limit", "md")}, + "automatic", "forces", "limit", "unlimited", "md")}, ) self.assertIn("**Requirements**\n\n| Option / condition | Requirements |", rendered) rows = [line for line in rendered.splitlines() if line.startswith("|")][2:] self.assertEqual(rows, [ - "| `md` | [`forces`](#forces)==true
[`limit`](#limit)<10 |", + "| `md` | [`forces`](#forces)==true and " + "([`limit`](#limit)<10 or [`unlimited`](#unlimited)==true) |", "| [`calculation`](#calculation)==md and " "([`ensemble`](#ensemble) in [npt, msst] or [`solver`](#solver)==lj) | " "[`stress`](#stress)==true and " From 618031a969b4cd62d3fedd9cb1e9bdc389683b0a Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Thu, 3 Dec 2026 07:56:24 +0800 Subject: [PATCH 10/11] test(input): omit explicit values overridden by fixed requirements --- tests/01_PW/051_PW_OBOD_MemSaver/INPUT | 1 - tests/01_PW/101_PW_W90/INPUT | 1 - tests/01_PW/nscf_hse_path/INPUT | 1 - tests/01_PW/nscf_hse_same/INPUT | 1 - tests/01_PW/nscf_out_pot/INPUT | 1 - tests/02_NAO_Gamma/get_wf_spin2/INPUT | 3 --- tests/03_NAO_multik/get_wf/INPUT | 4 ---- tests/03_NAO_multik/get_wf0/INPUT | 4 ---- tests/03_NAO_multik/nscf_out_band_pband/INPUT | 1 - tests/03_NAO_multik/nscf_out_dos/INPUT | 1 - tests/03_NAO_multik/nscf_out_pot1/INPUT | 1 - tests/04_FF/102_SNAP_base/INPUT | 1 - tests/04_FF/103_SNAP_pbc/INPUT | 1 - tests/04_FF/104_SNAP_inner/INPUT | 1 - tests/04_FF/105_SNAP_quad/INPUT | 1 - tests/05_rtTDDFT/21_PW_len_TDDFT/INPUT | 1 - tests/05_rtTDDFT/22_PW_vel_TDDFT/INPUT | 1 - tests/05_rtTDDFT/23_PW_spin_TDDFT/INPUT | 1 - tests/05_rtTDDFT/24_PW_cgs_TDDFT/INPUT | 1 - tests/05_rtTDDFT/25_PW_noprec_TDDFT/INPUT | 1 - tests/05_rtTDDFT/26_PW_single_TDDFT/INPUT | 1 - tests/05_rtTDDFT/27_PW_gmres_recycle_TDDFT/INPUT | 1 - tests/05_rtTDDFT/28_PW_gmres_subspace_TDDFT/INPUT | 1 - tests/05_rtTDDFT/29_PW_soc_len_TDDFT/INPUT | 1 - tests/05_rtTDDFT/30_PW_soc_onsite_TDDFT/INPUT | 1 - tests/05_rtTDDFT/31_PW_retry_TDDFT/INPUT | 1 - tests/05_rtTDDFT/32_PW_ETRS_lanczos_TDDFT/INPUT | 1 - tests/05_rtTDDFT/33_PW_ETRS_taylor_TDDFT/INPUT | 1 - tests/05_rtTDDFT/34_PW_ETRS_retry_TDDFT/INPUT | 1 - tests/06_SDFT/18_PW_NSCF_KG_100/INPUT | 1 - tests/08_RI/nscf_hse_multik/INPUT | 1 - tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT | 1 - tests/08_RI/rt_tddft_hse_spin2/INPUT | 1 - tests/09_DeePKS/05_NO_GO_deepks_nscf/INPUT | 1 - tests/09_DeePKS/06_NO_KP_deepks_nscf/INPUT | 1 - 35 files changed, 43 deletions(-) diff --git a/tests/01_PW/051_PW_OBOD_MemSaver/INPUT b/tests/01_PW/051_PW_OBOD_MemSaver/INPUT index 68a11d9f272..51818e971b4 100644 --- a/tests/01_PW/051_PW_OBOD_MemSaver/INPUT +++ b/tests/01_PW/051_PW_OBOD_MemSaver/INPUT @@ -11,7 +11,6 @@ read_file_dir ./ #Parameters (2.Iteration) ecutwfc 20 scf_thr 1e-8 -scf_nmax 100 pw_diag_nmax 30 init_chg file diff --git a/tests/01_PW/101_PW_W90/INPUT b/tests/01_PW/101_PW_W90/INPUT index b9aab68e5c4..00a20933eb1 100644 --- a/tests/01_PW/101_PW_W90/INPUT +++ b/tests/01_PW/101_PW_W90/INPUT @@ -7,7 +7,6 @@ ecutwfc 50 smearing_method fixed nbands 4 calculation nscf -scf_nmax 50 pw_diag_thr 1.0e-12 pw_diag_nmax 30 scf_thr 1.0e-15 diff --git a/tests/01_PW/nscf_hse_path/INPUT b/tests/01_PW/nscf_hse_path/INPUT index 907cc77a8b6..9d029579c43 100644 --- a/tests/01_PW/nscf_hse_path/INPUT +++ b/tests/01_PW/nscf_hse_path/INPUT @@ -8,7 +8,6 @@ symmetry -1 #Parameters (2.Iteration) ecutwfc 10 scf_thr 1e-9 -scf_nmax 100 pw_diag_thr 1e-10 pw_seed 1 diff --git a/tests/01_PW/nscf_hse_same/INPUT b/tests/01_PW/nscf_hse_same/INPUT index 77a5298dbe7..7c0eb06266b 100644 --- a/tests/01_PW/nscf_hse_same/INPUT +++ b/tests/01_PW/nscf_hse_same/INPUT @@ -8,7 +8,6 @@ symmetry -1 #Parameters (2.Iteration) ecutwfc 10 scf_thr 1e-9 -scf_nmax 100 pw_diag_thr 1e-10 pw_diag_nmax 30 pw_seed 1 diff --git a/tests/01_PW/nscf_out_pot/INPUT b/tests/01_PW/nscf_out_pot/INPUT index 3afecb93938..ca50531ab7a 100644 --- a/tests/01_PW/nscf_out_pot/INPUT +++ b/tests/01_PW/nscf_out_pot/INPUT @@ -10,7 +10,6 @@ out_pot 1 3 #Parameters (2.Iteration) ecutwfc 5 scf_thr 1e-9 -scf_nmax 100 #Parameters (3.Basis) basis_type pw diff --git a/tests/02_NAO_Gamma/get_wf_spin2/INPUT b/tests/02_NAO_Gamma/get_wf_spin2/INPUT index 45823327387..9325c24589b 100644 --- a/tests/02_NAO_Gamma/get_wf_spin2/INPUT +++ b/tests/02_NAO_Gamma/get_wf_spin2/INPUT @@ -15,9 +15,6 @@ gamma_only 1 nspin 2 read_file_dir ./ -bx 2 -by 2 -bz 2 #--------------------------------- # this line if for generting wave diff --git a/tests/03_NAO_multik/get_wf/INPUT b/tests/03_NAO_multik/get_wf/INPUT index dd1632b1526..3e06746f052 100644 --- a/tests/03_NAO_multik/get_wf/INPUT +++ b/tests/03_NAO_multik/get_wf/INPUT @@ -15,7 +15,3 @@ read_file_dir ./ out_wfc_norm 1 out_wfc_re_im 1 - -bx 2 -by 2 -bz 2 diff --git a/tests/03_NAO_multik/get_wf0/INPUT b/tests/03_NAO_multik/get_wf0/INPUT index 8e5a3867c10..dd263cd9105 100644 --- a/tests/03_NAO_multik/get_wf0/INPUT +++ b/tests/03_NAO_multik/get_wf0/INPUT @@ -15,7 +15,3 @@ read_file_dir ../get_wf/ out_wfc_norm 1 out_wfc_re_im 1 - -bx 2 -by 2 -bz 2 diff --git a/tests/03_NAO_multik/nscf_out_band_pband/INPUT b/tests/03_NAO_multik/nscf_out_band_pband/INPUT index 8abc5597e43..9a8feddf218 100644 --- a/tests/03_NAO_multik/nscf_out_band_pband/INPUT +++ b/tests/03_NAO_multik/nscf_out_band_pband/INPUT @@ -13,7 +13,6 @@ gamma_only 0 #Parameters (2.Iteration) ecutwfc 20 scf_thr 1e-8 -scf_nmax 100 #out_chg 1 init_chg file diff --git a/tests/03_NAO_multik/nscf_out_dos/INPUT b/tests/03_NAO_multik/nscf_out_dos/INPUT index 67c7a598d72..784466731fa 100644 --- a/tests/03_NAO_multik/nscf_out_dos/INPUT +++ b/tests/03_NAO_multik/nscf_out_dos/INPUT @@ -13,7 +13,6 @@ gamma_only 0 #Parameters (2.Iteration) ecutwfc 20 scf_thr 1e-8 -scf_nmax 100 init_chg file out_dos 1 diff --git a/tests/03_NAO_multik/nscf_out_pot1/INPUT b/tests/03_NAO_multik/nscf_out_pot1/INPUT index ef6e916a6bf..f7639e6b9a3 100644 --- a/tests/03_NAO_multik/nscf_out_pot1/INPUT +++ b/tests/03_NAO_multik/nscf_out_pot1/INPUT @@ -10,7 +10,6 @@ out_pot 1 5 #Parameters (2.Iteration) ecutwfc 5 scf_thr 1e-6 -scf_nmax 100 #Parameters (3.Basis) basis_type lcao diff --git a/tests/04_FF/102_SNAP_base/INPUT b/tests/04_FF/102_SNAP_base/INPUT index 59b27db4ddc..6cf51f4512d 100644 --- a/tests/04_FF/102_SNAP_base/INPUT +++ b/tests/04_FF/102_SNAP_base/INPUT @@ -9,4 +9,3 @@ cal_stress 1 md_nstep 1 md_type nve md_dt 1 -init_vel 0 diff --git a/tests/04_FF/103_SNAP_pbc/INPUT b/tests/04_FF/103_SNAP_pbc/INPUT index 2eee0601b68..4f027aa44e1 100644 --- a/tests/04_FF/103_SNAP_pbc/INPUT +++ b/tests/04_FF/103_SNAP_pbc/INPUT @@ -9,4 +9,3 @@ cal_stress 1 md_nstep 1 md_type nve md_dt 1 -init_vel 0 diff --git a/tests/04_FF/104_SNAP_inner/INPUT b/tests/04_FF/104_SNAP_inner/INPUT index 57c29805ee8..20d1d3bb578 100644 --- a/tests/04_FF/104_SNAP_inner/INPUT +++ b/tests/04_FF/104_SNAP_inner/INPUT @@ -9,4 +9,3 @@ cal_stress 1 md_nstep 1 md_type nve md_dt 1 -init_vel 0 diff --git a/tests/04_FF/105_SNAP_quad/INPUT b/tests/04_FF/105_SNAP_quad/INPUT index 6b735a80ab4..d1134b92881 100644 --- a/tests/04_FF/105_SNAP_quad/INPUT +++ b/tests/04_FF/105_SNAP_quad/INPUT @@ -9,4 +9,3 @@ cal_stress 1 md_nstep 1 md_type nve md_dt 1 -init_vel 0 diff --git a/tests/05_rtTDDFT/21_PW_len_TDDFT/INPUT b/tests/05_rtTDDFT/21_PW_len_TDDFT/INPUT index 887db839324..a1c43407546 100644 --- a/tests/05_rtTDDFT/21_PW_len_TDDFT/INPUT +++ b/tests/05_rtTDDFT/21_PW_len_TDDFT/INPUT @@ -28,7 +28,6 @@ init_vel 1 td_dt 0.01 md_nstep 1 estep_per_md 8 -cal_force 0 cal_stress 0 td_stype 0 td_vext 1 diff --git a/tests/05_rtTDDFT/22_PW_vel_TDDFT/INPUT b/tests/05_rtTDDFT/22_PW_vel_TDDFT/INPUT index 180a0655b9a..a7484c08d84 100644 --- a/tests/05_rtTDDFT/22_PW_vel_TDDFT/INPUT +++ b/tests/05_rtTDDFT/22_PW_vel_TDDFT/INPUT @@ -28,7 +28,6 @@ init_vel 1 td_dt 0.01 md_nstep 3 estep_per_md 4 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/23_PW_spin_TDDFT/INPUT b/tests/05_rtTDDFT/23_PW_spin_TDDFT/INPUT index 38e07e61da4..917e138df56 100644 --- a/tests/05_rtTDDFT/23_PW_spin_TDDFT/INPUT +++ b/tests/05_rtTDDFT/23_PW_spin_TDDFT/INPUT @@ -27,7 +27,6 @@ md_type nve init_vel 1 md_dt 0.01 md_nstep 9 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/24_PW_cgs_TDDFT/INPUT b/tests/05_rtTDDFT/24_PW_cgs_TDDFT/INPUT index e5eb8edf56e..194e7d9c601 100644 --- a/tests/05_rtTDDFT/24_PW_cgs_TDDFT/INPUT +++ b/tests/05_rtTDDFT/24_PW_cgs_TDDFT/INPUT @@ -27,7 +27,6 @@ md_type nve init_vel 1 md_dt 0.01 md_nstep 9 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/25_PW_noprec_TDDFT/INPUT b/tests/05_rtTDDFT/25_PW_noprec_TDDFT/INPUT index 7d20e12cb9a..2360820d6f2 100644 --- a/tests/05_rtTDDFT/25_PW_noprec_TDDFT/INPUT +++ b/tests/05_rtTDDFT/25_PW_noprec_TDDFT/INPUT @@ -27,7 +27,6 @@ md_type nve init_vel 1 md_dt 0.01 md_nstep 9 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/26_PW_single_TDDFT/INPUT b/tests/05_rtTDDFT/26_PW_single_TDDFT/INPUT index b277a0a7810..584792c0877 100644 --- a/tests/05_rtTDDFT/26_PW_single_TDDFT/INPUT +++ b/tests/05_rtTDDFT/26_PW_single_TDDFT/INPUT @@ -27,7 +27,6 @@ md_type nve init_vel 1 md_dt 0.01 md_nstep 9 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/27_PW_gmres_recycle_TDDFT/INPUT b/tests/05_rtTDDFT/27_PW_gmres_recycle_TDDFT/INPUT index 95ef53a7944..f7172bda3f8 100644 --- a/tests/05_rtTDDFT/27_PW_gmres_recycle_TDDFT/INPUT +++ b/tests/05_rtTDDFT/27_PW_gmres_recycle_TDDFT/INPUT @@ -28,7 +28,6 @@ init_vel 1 td_dt 0.01 md_nstep 3 estep_per_md 5 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/28_PW_gmres_subspace_TDDFT/INPUT b/tests/05_rtTDDFT/28_PW_gmres_subspace_TDDFT/INPUT index bf181da9f7e..e68bb153d59 100644 --- a/tests/05_rtTDDFT/28_PW_gmres_subspace_TDDFT/INPUT +++ b/tests/05_rtTDDFT/28_PW_gmres_subspace_TDDFT/INPUT @@ -27,7 +27,6 @@ md_type nve init_vel 1 md_dt 0.01 md_nstep 9 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/29_PW_soc_len_TDDFT/INPUT b/tests/05_rtTDDFT/29_PW_soc_len_TDDFT/INPUT index f6a16c85b45..5a8ac5bc82d 100644 --- a/tests/05_rtTDDFT/29_PW_soc_len_TDDFT/INPUT +++ b/tests/05_rtTDDFT/29_PW_soc_len_TDDFT/INPUT @@ -35,7 +35,6 @@ init_vel 1 td_dt 0.002 md_nstep 1 estep_per_md 5 -cal_force 0 cal_stress 0 td_vext 1 td_vext_dire 1 diff --git a/tests/05_rtTDDFT/30_PW_soc_onsite_TDDFT/INPUT b/tests/05_rtTDDFT/30_PW_soc_onsite_TDDFT/INPUT index f1dd5bd5a4f..5a5e5b55dfd 100644 --- a/tests/05_rtTDDFT/30_PW_soc_onsite_TDDFT/INPUT +++ b/tests/05_rtTDDFT/30_PW_soc_onsite_TDDFT/INPUT @@ -37,7 +37,6 @@ init_vel 1 td_dt 0.002 md_nstep 1 estep_per_md 5 -cal_force 0 cal_stress 0 td_vext 1 td_vext_dire 1 diff --git a/tests/05_rtTDDFT/31_PW_retry_TDDFT/INPUT b/tests/05_rtTDDFT/31_PW_retry_TDDFT/INPUT index 81bb22df32e..d9873a21bce 100644 --- a/tests/05_rtTDDFT/31_PW_retry_TDDFT/INPUT +++ b/tests/05_rtTDDFT/31_PW_retry_TDDFT/INPUT @@ -28,7 +28,6 @@ init_vel 1 td_dt 0.01 md_nstep 1 estep_per_md 2 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/32_PW_ETRS_lanczos_TDDFT/INPUT b/tests/05_rtTDDFT/32_PW_ETRS_lanczos_TDDFT/INPUT index ce2aecf6502..739bea28046 100644 --- a/tests/05_rtTDDFT/32_PW_ETRS_lanczos_TDDFT/INPUT +++ b/tests/05_rtTDDFT/32_PW_ETRS_lanczos_TDDFT/INPUT @@ -35,7 +35,6 @@ init_vel 1 td_dt 0.002 md_nstep 1 estep_per_md 2 -cal_force 0 cal_stress 0 td_vext 1 td_vext_dire 1 diff --git a/tests/05_rtTDDFT/33_PW_ETRS_taylor_TDDFT/INPUT b/tests/05_rtTDDFT/33_PW_ETRS_taylor_TDDFT/INPUT index feb5e8743a1..04b9ddc9b0c 100644 --- a/tests/05_rtTDDFT/33_PW_ETRS_taylor_TDDFT/INPUT +++ b/tests/05_rtTDDFT/33_PW_ETRS_taylor_TDDFT/INPUT @@ -28,7 +28,6 @@ init_vel 1 td_dt 0.01 md_nstep 1 estep_per_md 2 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/05_rtTDDFT/34_PW_ETRS_retry_TDDFT/INPUT b/tests/05_rtTDDFT/34_PW_ETRS_retry_TDDFT/INPUT index 61031d1f79a..eaeb655c356 100644 --- a/tests/05_rtTDDFT/34_PW_ETRS_retry_TDDFT/INPUT +++ b/tests/05_rtTDDFT/34_PW_ETRS_retry_TDDFT/INPUT @@ -28,7 +28,6 @@ init_vel 1 td_dt 0.01 md_nstep 1 estep_per_md 2 -cal_force 0 cal_stress 0 td_stype 1 td_vext 1 diff --git a/tests/06_SDFT/18_PW_NSCF_KG_100/INPUT b/tests/06_SDFT/18_PW_NSCF_KG_100/INPUT index 94bac3bd357..6b14b24f910 100644 --- a/tests/06_SDFT/18_PW_NSCF_KG_100/INPUT +++ b/tests/06_SDFT/18_PW_NSCF_KG_100/INPUT @@ -13,7 +13,6 @@ init_chg file #Parameters (2.Iteration) ecutwfc 20 scf_thr 1e-6 -scf_nmax 50 #Parameters (3.Basis) diff --git a/tests/08_RI/nscf_hse_multik/INPUT b/tests/08_RI/nscf_hse_multik/INPUT index a3f80dc0fb7..7172a633ba7 100644 --- a/tests/08_RI/nscf_hse_multik/INPUT +++ b/tests/08_RI/nscf_hse_multik/INPUT @@ -16,7 +16,6 @@ ecutwfc 5 scf_thr 1e-7 #Parameters (Relaxation) -scf_nmax 100 #Parameters (LCAO) basis_type lcao diff --git a/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT b/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT index bf197c75908..1fe3af14a8d 100644 --- a/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT +++ b/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT @@ -27,7 +27,6 @@ exx_singularity_correction limits symmetry -1 suffix autotest fixed_atoms 1 -cal_force 0 scf_thr 1e-6 scf_nmax 150 md_restartfreq 1 diff --git a/tests/08_RI/rt_tddft_hse_spin2/INPUT b/tests/08_RI/rt_tddft_hse_spin2/INPUT index 18a0b0bb49b..659e9e7edcf 100644 --- a/tests/08_RI/rt_tddft_hse_spin2/INPUT +++ b/tests/08_RI/rt_tddft_hse_spin2/INPUT @@ -27,7 +27,6 @@ exx_singularity_correction limits symmetry -1 suffix autotest fixed_atoms 1 -cal_force 0 scf_thr 1e-7 scf_nmax 100 md_restartfreq 1 diff --git a/tests/09_DeePKS/05_NO_GO_deepks_nscf/INPUT b/tests/09_DeePKS/05_NO_GO_deepks_nscf/INPUT index f40c52235dd..b6235e8139d 100644 --- a/tests/09_DeePKS/05_NO_GO_deepks_nscf/INPUT +++ b/tests/09_DeePKS/05_NO_GO_deepks_nscf/INPUT @@ -13,7 +13,6 @@ read_file_dir ./ #Parameters (2.Iteration) ecutwfc 20 scf_thr 1e-7 -scf_nmax 50 #Parameters (3.Basis) basis_type lcao diff --git a/tests/09_DeePKS/06_NO_KP_deepks_nscf/INPUT b/tests/09_DeePKS/06_NO_KP_deepks_nscf/INPUT index 0a095a7e640..c3233cb2126 100644 --- a/tests/09_DeePKS/06_NO_KP_deepks_nscf/INPUT +++ b/tests/09_DeePKS/06_NO_KP_deepks_nscf/INPUT @@ -4,7 +4,6 @@ suffix autotest ecutwfc 50 scf_thr 1e-06 -scf_nmax 35 pseudo_dir ../../PP_ORB orbital_dir ../../PP_ORB read_file_dir ./ From 9470bf57ba853c434675e6a399a1a3aa31109fab Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Fri, 4 Dec 2026 17:57:48 +0800 Subject: [PATCH 11/11] test(io): validate the intended TDDFT dipole setup conflicts --- source/source_io/unittests/test_read_input_parallel.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 94158704ea0..a445eab9d61 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -597,6 +597,7 @@ Input_para dipole_input() { Input_para input; input.esolver_type = "tddft"; + input.exx_separate_loop = false; input.basis_type = "lcao"; input.calculation = "md"; input.mdp.md_nstep = 1; @@ -655,9 +656,14 @@ TEST(PeriodicDipoleInput, RejectUnsupportedAndMalformedInputs) const ModuleIO::InputValues values = {{"td_stype", ModuleIO::InputValue(input.td_stype)}, {"basis_type", ModuleIO::InputValue(input.basis_type)}, {"esolver_type", ModuleIO::InputValue(input.esolver_type)}, + {"exx_separate_loop", ModuleIO::InputValue(input.exx_separate_loop)}, {"init_vecpot", ModuleIO::InputValue(input.init_vecpot)}, {"calculation", ModuleIO::InputValue(input.calculation)}}; - EXPECT_FALSE(domain->validate_requirements(setup_labels[i], values).empty()) << "case " << i; + const std::string expected = setup_labels[i] == "esolver_type" + ? "Requires calculation==md and basis_type in [pw, lcao]." + : "Requires esolver_type==tddft and td_stype in [1, 2]."; + const std::string diagnostic = domain->validate_requirements(setup_labels[i], values); + EXPECT_THAT(diagnostic, testing::HasSubstr(expected)) << "case " << i; } }