diff --git a/docs/advanced/md.md b/docs/advanced/md.md index 6960e8f72e5..1d7f0d4d28a 100644 --- a/docs/advanced/md.md +++ b/docs/advanced/md.md @@ -28,7 +28,7 @@ When [md_type](./input_files/input-main.md#md_type) is set to npt, [md_pmode](./ Furthermore, ABACUS also provides a [list of keywords](./input_files/input-main.md#molecular-dynamics) to control relevant parmeters used in MD simulations. -MD structure output is controlled by [`out_stru`](./input_files/input-main.md#out_stru), [`out_freq_ion`](./input_files/input-main.md#out_freq_ion), and [`out_app_flag`](./input_files/input-main.md#out_app_flag). Set `out_stru 1`, `out_freq_ion 1`, and `out_app_flag 1` to keep every MD step in the appended `STRU` trajectory. With `out_freq_ion 0`, only `STRU_FINAL` is written. Mode 0 overwrites the periodic `STRU`; mode 2 writes numbered files and `STRU_FINAL` under `STRUC/`. Set `out_stru 2` for CIF geometry: periodic output overwrites `STRU.cif` in modes 0 and 1 or writes numbered `STRU{step}.cif` files in mode 2, and the final geometry is `STRU_FINAL.cif`. CIF omits atomic forces and velocities; the separate `STRU_restart` checkpoint retains velocities for restarting MD. +MD structure output is controlled by [`out_stru`](./input_files/input-main.md#out_stru) and [`out_app_flag`](./input_files/input-main.md#out_app_flag). The optional second value of `out_stru` sets the MD structure interval and defaults to 1: for example, `out_stru 1 5` writes a STRU frame every 5 steps, while `out_stru 1 0` disables periodic frames but still writes `STRU_FINAL`. The structure cadence is independent of `out_freq_ion`, which continues to control electronic and other outputs. Mode 0 overwrites the periodic `STRU`; mode 2 writes numbered files and `STRU_FINAL` under `STRUC/`. Set `out_stru 2 5` for CIF geometry every 5 steps: periodic output overwrites `STRU.cif` in modes 0 and 1 or writes numbered `STRU{step}.cif` files in mode 2, and the final geometry is `STRU_FINAL.cif`. CIF omits atomic forces and velocities; the separate `STRU_restart` checkpoint retains velocities for restarting MD. Use `out_thermo_freq` to set the output interval for MD step, energy, temperature, and pressure information in `running_md.log` and on screen. The default is 1; set it to 0 to disable this thermodynamic output. The interval counts MD steps from 0, so a value of 10 selects steps 0, 10, 20, and so on, including after a restart. diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 5d21f6d7b61..b1fc6f2d904 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -464,6 +464,7 @@ struct Input_para int out_freq_elec = 0; ///< the frequency of electronic iter to output charge and wavefunction int out_freq_ion = 0; ///< the frequency ( >= 0 ) of ionic step to output charge density; ///< 0: output only when ion steps are finished + int out_freq_stru = 1; ///< MD structure cadence from optional out_stru second value int out_freq_td_compat = 0; ///< legacy alias out_freq_td for out_freq_ion in RT-TDDFT std::vector out_chg = {0, 3}; ///< output charge density. 0: no; 1: yes bool out_occ_mat = true; ///< output DFT+U occupation matrices; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 978228422b5..4de4b89404f 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -15,9 +15,9 @@ void ReadInput::item_output() item.annotation = "print information every few ionic steps"; item.category = "Output information"; item.type = "Integer"; - item.description = "Controls the output interval in ionic steps. When set to a positive integer, information such as charge density, local potential, electrostatic potential, Hamiltonian matrix, overlap matrix, density matrix, Mulliken population analysis, and periodic structure files (when out_stru is positive) is printed every n ionic steps." + item.description = "Controls the output interval in ionic steps. When set to a positive integer, information such as charge density, local potential, electrostatic potential, Hamiltonian matrix, overlap matrix, density matrix, and Mulliken population analysis is printed every n ionic steps. In MD, periodic structure frames are controlled by the optional second value of out_stru." "\n\nThis parameter only controls how often a write happens, not how many files are kept: with out_app_flag = 0 each write overwrites the same fixed filename, with out_app_flag = 1 records are appended to one fixed filename, and with out_app_flag = 2 each written step gets its own g{step} file." - "\n\nIn molecular dynamics calculations, positive out_freq_ion selects periodic structure frames starting at the first step. Zero disables periodic frames; STRU_FINAL or STRU_FINAL.cif is still written when out_stru is positive. MD checkpoints STRU_restart and Restart_md.txt follow md_restartfreq independently." + "\n\nIn molecular dynamics calculations, out_freq_ion does not control periodic structure frames. The optional second value of out_stru sets that cadence (default 1). MD writes STRU_FINAL or STRU_FINAL.cif when out_stru is positive. Checkpoints STRU_restart and Restart_md.txt follow md_restartfreq independently." "\n\nFor DFT+U calculations with out_occ_mat = 1, a separate occupation-matrix file occ_matg{geom_step}.txt is created for every output ionic step. The converged (or final, if not converged) electronic step is always recorded in that file; when out_freq_elec is set smaller than scf_nmax, additional electronic steps are appended as separate sections, each labelled only with the electronic-step number." "\n\nIn RT-TDDFT calculations, this parameter counts completed electronic evolution steps (`STEP OF ELECTRON EVOLVE`) instead, because one ionic step contains `estep_per_md` electronic steps. To write once per ionic step, set it to `estep_per_md`."; item.default_value = "0"; @@ -579,16 +579,17 @@ The LDOS is evaluated once after all ionic steps finish; the cube header records Input_Item item("out_stru"); item.annotation = "output the structure files per ion step"; item.category = "Output information"; - item.type = "Integer"; - item.description = "Controls ordinary structure output in scf/nscf/relax/cell-relax and md calculations. Files are written to OUT.{suffix}/, or to STRUC/ when out_app_flag=2. The relaxation header records version, time, energy and stress; MD frames use a one-based \"# MD step N\" marker. In relax, STRU_NOW is overwritten each step, STRU_FINAL is written at completion, and positive out_freq_ion selects additional periodic files when out_app_flag is 1 or 2. In MD, STRU_FINAL or STRU_FINAL.cif is written at completion and positive out_freq_ion selects periodic frames for all three output modes. For scf/nscf only STRU_FINAL (or STRU_FINAL.cif) is written.\n\n" + item.type = R"(Integer \[Integer\](optional))"; + item.description = "The first integer controls ordinary structure output in scf/nscf/relax/cell-relax and md calculations. Files are written to OUT.{suffix}/, or to STRUC/ when out_app_flag=2. The optional second integer controls the periodic MD structure-frame interval and defaults to 1. In MD, for example, 'out_stru 1 5' writes a STRU frame every 5 steps, while 'out_stru 1 0' disables periodic frames but still writes STRU_FINAL. The final STRU (or STRU_FINAL.cif) is written when out_stru is positive; STRU_restart and Restart_md.txt follow md_restartfreq independently. For relax, STRU_NOW is overwritten each step, STRU_FINAL is written at completion, and positive out_freq_ion selects additional periodic files when out_app_flag is 1 or 2. For scf/nscf only STRU_FINAL (or STRU_FINAL.cif) is written.\n\n" " - 0: No ordinary structure files are output. MD restart checkpoints remain controlled by md_restartfreq.\n" - " - 1: ABACUS STRU format files are output. In relax/cell-relax the latest structure is written to STRU_NOW (overwritten each step), periodic STRU files are written when out_freq_ion is positive and out_app_flag is 1 or 2, and the final structure is written to STRU_FINAL. For scf/nscf only STRU_FINAL is written. In MD, positive out_freq_ion selects periodic STRU files in modes 0, 1 and 2; STRU_FINAL is always written at completion. Mode 1 appends one structure block per selected step to fixed-name STRU.\n" - " - 2: CIF format files are output. In relax/cell-relax, STRU_NOW.cif is overwritten each step and STRU_FINAL.cif is written at completion; periodic CIF files are written with positive out_freq_ion when out_app_flag is 1 or 2. In MD, positive out_freq_ion selects periodic CIF files for all three modes and STRU_FINAL.cif is written at completion. Mode 2 writes numbered STRU{istep}.cif files; modes 0 and 1 overwrite one STRU.cif on each selected step. CIF contains geometry but no per-atom forces or velocities. MD restart checkpoints remain ABACUS STRU files.\n" - "[NOTE] MD writes STRU_FINAL or STRU_FINAL.cif at the end when out_stru is positive. With out_freq_ion>0 it also writes periodic frames from the first step. For ABACUS STRU, out_app_flag=0 overwrites STRU, mode 1 appends marked frames to STRU, and mode 2 writes numbered STRU{istep} files under STRUC/. With out_freq_ion=0 only the final structure is written. MD does not write STRU_NOW. Ordinary MD STRU structures include forces in eV/Angstrom and velocities in atomic units; STRU_restart keeps velocities but omits forces, and is written with Restart_md.txt according to md_restartfreq even when out_stru=0.\n" + " - 1: ABACUS STRU format files are output. In relax/cell-relax the latest structure is written to STRU_NOW (overwritten each step), periodic STRU files are written when out_freq_ion is positive and out_app_flag is 1 or 2, and the final structure is written to STRU_FINAL. For scf/nscf only STRU_FINAL is written. In MD, the optional second integer selects periodic STRU frames and defaults to every step. Mode 1 appends one structure block per selected step to fixed-name STRU.\n" + " - 2: CIF format files are output. In relax/cell-relax, STRU_NOW.cif is overwritten each step and STRU_FINAL.cif is written at completion; periodic CIF files are written with positive out_freq_ion when out_app_flag is 1 or 2. In MD, the optional second integer selects periodic CIF frames and defaults to every step. Mode 2 writes numbered STRU{istep}.cif files; modes 0 and 1 overwrite one STRU.cif on each selected step. CIF contains geometry but no per-atom forces or velocities. MD restart checkpoints remain ABACUS STRU files.\n" + "[NOTE] For MD with out_stru > 0, STRU_FINAL or STRU_FINAL.cif is written at the end. The optional second integer defaults to 1; set it to 0 to disable periodic structure frames while keeping the final structure. For ABACUS STRU, out_app_flag=0 overwrites STRU, mode 1 appends marked frames to STRU, and mode 2 writes numbered STRU{istep} files under STRUC/. MD does not write STRU_NOW. Ordinary MD STRU structures include forces in eV/Angstrom and velocities in atomic units; STRU_restart keeps velocities but omits forces, and is written with Restart_md.txt according to md_restartfreq even when out_stru=0.\n" "[NOTE] For backward compatibility, true/false (case insensitive) are accepted and converted to 1/0."; item.default_value = "1"; item.unit = ""; item.read_value = [](const Input_Item& item, Parameter& para) { + const size_t count = item.get_size(); const std::string val = FmtCore::lower(item.str_values[0]); if (val == "true" || val == "t" || val == "yes" || val == "y" || val == "on" || val == ".true.") { @@ -622,6 +623,11 @@ The LDOS is evaluated once after all ionic steps finish; the cube header records "out_stru must be one of 0, 1, 2. For backward compatibility, true/false are also accepted. Got: '" + item.str_values[0] + "'."); } } + para.input.out_freq_stru = 1; + if (count == 2) + { + para.input.out_freq_stru = std::stoi(item.str_values[1]); + } }; item.reset_value = [](const Input_Item& item, Parameter& para) { // For scf/nscf/get_s/get_pchg/get_wf the default is no structure @@ -641,6 +647,10 @@ The LDOS is evaluated once after all ionic steps finish; the cube header records } }; sync_int(input.out_stru); + item.get_final_value = [](Input_Item& item, const Parameter& para) { + item.final_value << para.input.out_stru << " " << para.input.out_freq_stru; + }; + add_int_bcast(input.out_freq_stru); 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 9515c8a7217..aec5d997f7b 100644 --- a/source/source_io/module_parameter/read_input.cpp +++ b/source/source_io/module_parameter/read_input.cpp @@ -494,15 +494,16 @@ std::string ReadInput::prepare_input(Parameter& param) errors += item->domain.validate_explicit(item->label, item->str_values); } - // out_dos, out_mat_xc, out_mat_p and out_mat_exx take one or two tokens. - // Their vector domains skip the whole-token validation of the scalar - // readers, so check that every supplied token is a complete value before - // any read hook runs. + // out_dos, out_mat_xc, out_mat_p, out_mat_exx, and out_stru take one or two + // tokens. Their vector domains skip the whole-token validation of the scalar + // readers, so check that every supplied token is a complete value before any + // read hook runs. for (const ModuleIO::Input_Item* item : this->readvalue_items) { const bool starts_with_boolean = item->label == "out_mat_xc" || item->label == "out_mat_p" || item->label == "out_mat_exx"; - if (!starts_with_boolean && item->label != "out_dos") + const bool is_out_stru = item->label == "out_stru"; + if (!starts_with_boolean && item->label != "out_dos" && !is_out_stru) { continue; } @@ -510,7 +511,9 @@ std::string ReadInput::prepare_input(Parameter& param) if (valid) { valid = starts_with_boolean ? is_boolean_token(item->str_values[0]) - : is_integer_token(item->str_values[0]); + : (is_out_stru + ? is_boolean_token(item->str_values[0]) || is_integer_token(item->str_values[0]) + : is_integer_token(item->str_values[0])); } if (valid && item->str_values.size() == 2) { @@ -518,9 +521,23 @@ std::string ReadInput::prepare_input(Parameter& param) } if (!valid) { - errors += input_diagnostic(item->label, longstring(item->str_values), "supplied", - starts_with_boolean ? "Expected a Boolean and an optional Integer." - : "Expected one Integer and an optional precision Integer."); + std::string expected_format_text; + if (starts_with_boolean) + { + expected_format_text = "Expected a Boolean and an optional Integer."; + } + else if (is_out_stru) + { + expected_format_text = "Expected 0, 1, 2 (or a Boolean) and an optional nonnegative Integer."; + } + else + { + expected_format_text = "Expected one Integer and an optional precision Integer."; + } + const std::string expected_format = expected_format_text; + const std::string diagnostic + = input_diagnostic(item->label, longstring(item->str_values), "supplied", expected_format); + errors += diagnostic; } } @@ -599,6 +616,10 @@ std::string ReadInput::prepare_input(Parameter& param) { errors += "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer.\n"; } + if (param.input.out_freq_stru < 0) + { + errors += "Invalid INPUT parameter 'out_stru': the optional second value must be >= 0.\n"; + } // Snapshot typed effective values once for shared domain and dependency checks. InputValues values; diff --git a/source/source_io/unittests/CMakeLists.txt b/source/source_io/unittests/CMakeLists.txt index 491a2e022b2..676411e594a 100644 --- a/source/source_io/unittests/CMakeLists.txt +++ b/source/source_io/unittests/CMakeLists.txt @@ -81,6 +81,7 @@ foreach( out_dmk_zero_precision out_hsk_zero_precision out_mat_tk_zero_precision + out_stru_negative_frequency out_mat_p_invalid_boolean out_mat_p_invalid_precision out_mat_p_extra_token diff --git a/source/source_io/unittests/test_read_input.cmake b/source/source_io/unittests/test_read_input.cmake index 78d13883fc2..d300a09b5eb 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -47,6 +47,10 @@ 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_manual "") +elseif(INPUT_CASE STREQUAL "out_stru_negative_frequency") + string(APPEND contents "out_stru 1 -1\n") + set(expected "Invalid INPUT parameter 'out_stru': the optional second value must be >= 0.") + set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_p_invalid_boolean") string(APPEND contents "out_mat_p maybe\n") set(expected "Invalid INPUT parameter 'out_mat_p': supplied 'maybe'") diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 09746666b08..f2c81178d41 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -3050,6 +3050,24 @@ TEST_F(InputTest, OutStru) it->second.str_values = {"2"}; it->second.read_value(it->second, param); EXPECT_EQ(TestParameters::input(param).out_stru, 2); + EXPECT_EQ(TestParameters::input(param).out_freq_stru, 1); + } + { + it->second.str_values = {"1", "5"}; + it->second.read_value(it->second, param); + EXPECT_EQ(TestParameters::input(param).out_stru, 1); + EXPECT_EQ(TestParameters::input(param).out_freq_stru, 5); + } + { + it->second.str_values = {"1", "0"}; + it->second.read_value(it->second, param); + EXPECT_EQ(TestParameters::input(param).out_freq_stru, 0); + check_item(it->second, param); + } + { + it->second.str_values = {"1", "-1"}; + it->second.read_value(it->second, param); + EXPECT_EQ(TestParameters::input(param).out_freq_stru, -1); } // --- Backward-compatible boolean aliases (true -> 1, false -> 0) --- diff --git a/source/source_md/run_md.cpp b/source/source_md/run_md.cpp index 7db7c341b24..2c3ee9055e2 100644 --- a/source/source_md/run_md.cpp +++ b/source/source_md/run_md.cpp @@ -106,7 +106,7 @@ void md_line( } }; - const int output_freq = param_in.inp.out_freq_ion; + const int output_freq = param_in.inp.out_freq_stru; const int restart_freq = param_in.mdp.md_restartfreq; const std::string stru_out_dir = param_in.globalv.global_stru_dir; const std::string restart_stru = param_in.globalv.global_out_dir + "STRU_restart"; @@ -148,7 +148,7 @@ void md_line( /// Mark the final ionic step on the cell passed to the solver. The /// output module then writes the final snapshot even when this step is - /// off the out_freq_ion cadence or its SCF did not converge. + /// off the out_stru cadence or its SCF did not converge. const bool is_final_step = is_last_step(md_step, mdp.md_nstep); if (mdcell.has_backing_unitcell()) { diff --git a/source/source_md/run_md.h b/source/source_md/run_md.h index 1655781f5ba..038a429b98b 100644 --- a/source/source_md/run_md.h +++ b/source/source_md/run_md.h @@ -25,9 +25,9 @@ namespace Run_MD inline bool is_cadence_step(const int current_step, const int freq) { return freq > 0 && current_step % freq == 0; } /// Periodic structure output is independent of the MD restart cadence. -inline bool is_structure_output_step(const int current_step, const int out_freq_ion, const bool out_stru) +inline bool is_structure_output_step(const int current_step, const int out_freq_stru, const bool out_stru) { - return out_stru && is_cadence_step(current_step, out_freq_ion); + return out_stru && is_cadence_step(current_step, out_freq_stru); } /// Returns true when `current_step` is the final ionic step of the run. diff --git a/tests/04_FF/21_LJ_cadence/INPUT b/tests/04_FF/21_LJ_cadence/INPUT deleted file mode 100644 index 2cc8158de65..00000000000 --- a/tests/04_FF/21_LJ_cadence/INPUT +++ /dev/null @@ -1,16 +0,0 @@ -INPUT_PARAMETERS -suffix cadence -calculation md -esolver_type lj -lj_rcut 8.5 -lj_epsilon 0.01032 -lj_sigma 3.405 -md_type nve -md_nstep 5 -md_dt 1 -md_tfirst 0 -md_restartfreq 3 -out_freq_ion 2 -out_app_flag 0 -out_stru 0 -init_vel 0 diff --git a/tests/04_FF/21_LJ_cadence/STRU b/tests/04_FF/21_LJ_cadence/STRU deleted file mode 100644 index 9403cca63de..00000000000 --- a/tests/04_FF/21_LJ_cadence/STRU +++ /dev/null @@ -1,19 +0,0 @@ -ATOMIC_SPECIES -He 4.0026 - -LATTICE_CONSTANT -1.889727 - -LATTICE_VECTORS -20.0 0.0 0.0 -0.0 20.0 0.0 -0.0 0.0 20.0 - -ATOMIC_POSITIONS -Cartesian - -He -0 -2 -0.0 0.0 0.0 m 1 1 1 v 0.0 0.0 0.0 -3.0 0.0 0.0 m 1 1 1 v 0.0 0.0 0.0 diff --git a/tests/04_FF/22_DP_rank_consistency/README.md b/tests/04_FF/22_DP_rank_consistency/README.md deleted file mode 100644 index 94d529a45b1..00000000000 --- a/tests/04_FF/22_DP_rank_consistency/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# DeePMD MPI rank comparison - -Use the `frozen_model_op.pth` attached to [issue #8310](https://github.com/deepmodeling/abacus-develop/issues/8310). The model is not copied into this repository. - -From the repository root, run: - -```sh -python3 tests/integrate/validation_tools/check_dp_rank_consistency.py \ - --abacus /absolute/path/to/abacus \ - --mpi /absolute/path/to/mpirun \ - --model /absolute/path/to/frozen_model_op.pth \ - --fixture tests/04_FF/22_DP_rank_consistency/STRU -``` - -The script runs one and four ranks for the original two-atom cell, a displaced atom, and an expanded lattice. It then compares consecutive evaluations in two-step `relax` and `cell-relax` runs on the displaced cell; these keep the same DP instance while coordinates or lattice geometry change. Four ranks guarantee at least two ranks without owned atoms. It compares energy, every force component, and every stress component using the integration-suite tolerances of `1e-5` eV, `1e-4` eV/Angstrom, and `1e-3` kbar. It also requires the coordinate displacement to produce nonzero force and each geometry update to change the energy. - -This is a manual model-backed check because the issue attachment is not vendored as a test fixture. The separate `04_FF_md_output_cadence` CTest check uses a fully committed LJ fixture. diff --git a/tests/04_FF/22_DP_rank_consistency/STRU b/tests/04_FF/22_DP_rank_consistency/STRU deleted file mode 100644 index 6f0f48bd7f2..00000000000 --- a/tests/04_FF/22_DP_rank_consistency/STRU +++ /dev/null @@ -1,19 +0,0 @@ -ATOMIC_SPECIES -Fe 55.8500 - -LATTICE_CONSTANT -1.8897261258 - -LATTICE_VECTORS -2.830954119825 0 0 -0 2.830954119825 0 -0 0 2.830954119825 - -ATOMIC_POSITIONS -Direct - -Fe -4.0 -2 -0.0 0.0 0.0 m 1 1 1 -0.5 0.5 0.5 m 1 1 1 diff --git a/tests/04_FF/CMakeLists.txt b/tests/04_FF/CMakeLists.txt index 92bc22ddb32..3041d6d389e 100644 --- a/tests/04_FF/CMakeLists.txt +++ b/tests/04_FF/CMakeLists.txt @@ -12,17 +12,3 @@ else() COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto WORKING_DIRECTORY ${ABACUS_TEST_DIR}/04_FF) endif() - -# Autotest checks numerical results; this existing driver also asserts the -# structure-file inventory for independent output and restart cadences. -find_program(ABACUS_CADENCE_PYTHON python3) -if(ABACUS_CADENCE_PYTHON AND NOT ENABLE_ASAN) - add_test( - NAME 04_FF_md_output_cadence - COMMAND - ${ABACUS_CADENCE_PYTHON} - ${ABACUS_TEST_DIR}/integrate/validation_tools/check_md_output_cadence.py - ${ABACUS_BIN_PATH} ${ABACUS_TEST_DIR}/04_FF/21_LJ_cadence) - set_tests_properties(04_FF_md_output_cadence - PROPERTIES TIMEOUT 300 ENVIRONMENT "OMP_NUM_THREADS=1") -endif() diff --git a/tests/integrate/validation_tools/check_dp_rank_consistency.py b/tests/integrate/validation_tools/check_dp_rank_consistency.py deleted file mode 100644 index 8cf03354e3b..00000000000 --- a/tests/integrate/validation_tools/check_dp_rank_consistency.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Compare complete DP outputs for one and four MPI ranks. - -Run with the DPA model from issue #8310, for example: - python3 check_dp_rank_consistency.py --abacus /path/to/abacus \ - --mpi mpirun --model /path/to/frozen_model_op.pth \ - --fixture tests/04_FF/22_DP_rank_consistency/STRU -""" - -import argparse -import os -from pathlib import Path -import re -import subprocess -import tempfile - - -NUMBER = r"[-+]?\d+(?:\.\d*)?(?:[Ee][-+]?\d+)?" - - -def read_observables(log_text): - energy = re.search(r"#TOTAL ENERGY#\s+(" + NUMBER + r")", log_text) - force_block = re.search( - r"#TOTAL-FORCE[^\n]*\n(.*?)#TOTAL-STRESS", log_text, re.S) - stress_block = re.search( - r"#TOTAL-STRESS[^\n]*\n(.*?)#TOTAL-PRESSURE", log_text, re.S) - if not energy or not force_block or not stress_block: - raise AssertionError("Missing DP energy, forces or stress in running log") - forces = [] - for line in force_block.group(1).splitlines(): - if re.match(r"\s*Fe\d+\s", line): - forces.extend(float(value) for value in re.findall(NUMBER, line)[1:]) - stress = [] - for line in stress_block.group(1).splitlines(): - values = re.findall(NUMBER, line) - if len(values) == 3: - stress.extend(float(value) for value in values) - if len(forces) != 6 or len(stress) != 9: - raise AssertionError("Incomplete DP force or stress matrix") - return [float(energy.group(1))] + forces + stress - - -def read_frames(log_text): - starts = [match.start() for match in re.finditer(r"#TOTAL ENERGY#", log_text)] - return [read_observables(log_text[start:stop]) - for start, stop in zip(starts, starts[1:] + [len(log_text)])] - - -def compare_frames(label, serial_frames, parallel_frames, minimum_frames): - if len(serial_frames) != len(parallel_frames) or len(serial_frames) < minimum_frames: - raise AssertionError("{} has {} one-rank and {} four-rank evaluations".format( - label, len(serial_frames), len(parallel_frames))) - tolerances = [1e-5] + [1e-4] * 6 + [1e-3] * 9 - for step, (serial, parallel) in enumerate(zip(serial_frames, parallel_frames)): - for index, (left, right) in enumerate(zip(serial, parallel)): - if abs(left - right) > tolerances[index]: - raise AssertionError("{} step {} observable {} differs: {} vs {}".format( - label, step, index, left, right)) - - -def run_case(args, structure, ranks, case_dir, calculation): - case_dir.mkdir() - (case_dir / "STRU").write_text(structure) - input_text = ( - "INPUT_PARAMETERS\n" - "suffix rank_check\n" - "calculation " + calculation + "\n" - "esolver_type dp\n" - "pot_file " + str(args.model.resolve()) + "\n" - "cal_force 1\n" - "cal_stress 1\n" - "device cpu\n") - if calculation != "scf": - input_text += "relax_nmax 2\nforce_thr_ev 1e-10\nstress_thr 1e-10\n" - (case_dir / "INPUT").write_text(input_text) - command = [args.mpi, args.mpi_np_flag, str(ranks), args.abacus] - env = os.environ.copy() - env["OMP_NUM_THREADS"] = "1" - result = subprocess.run( - command, cwd=str(case_dir), env=env, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, universal_newlines=True, timeout=180, - check=False) - if result.returncode: - raise AssertionError("DP run failed on {} ranks:\n{}".format( - ranks, result.stdout)) - log = case_dir / "OUT.rank_check" / ("running_" + calculation + ".log") - return read_frames(log.read_text()) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--abacus", required=True) - parser.add_argument("--mpi", required=True) - parser.add_argument("--mpi-np-flag", default="-np") - parser.add_argument("--model", type=Path, required=True) - parser.add_argument("--fixture", type=Path, required=True) - args = parser.parse_args() - structure = args.fixture.read_text() - structures = { - "original": structure, - "moved": structure.replace("0.5 0.5 0.5 m", "0.47 0.5 0.5 m"), - "expanded": structure.replace("2.830954119825", "2.900000000000"), - } - with tempfile.TemporaryDirectory(prefix="abacus-dp-ranks-") as scratch: - baseline = None - for label, variant in structures.items(): - serial_frames = run_case(args, variant, 1, Path(scratch) / (label + "_np1"), "scf") - parallel_frames = run_case(args, variant, 4, Path(scratch) / (label + "_np4"), "scf") - compare_frames(label, serial_frames, parallel_frames, 1) - serial = serial_frames[0] - print("{}: energy, 6 force components and 9 stress components agree; " - "energy={}, max_force={}".format(label, serial[0], max(abs(x) for x in serial[1:7]))) - if label == "original": - baseline = serial - elif abs(serial[0] - baseline[0]) < 1e-3: - raise AssertionError("{} geometry update did not change the DP energy".format(label)) - if label == "moved" and max(abs(x) for x in serial[1:7]) < 1e-3: - raise AssertionError("Coordinate update did not produce a measurable DP force") - - for calculation in ("relax", "cell-relax"): - variant = structures["moved"] - serial_frames = run_case(args, variant, 1, - Path(scratch) / (calculation + "_np1"), calculation) - parallel_frames = run_case(args, variant, 4, - Path(scratch) / (calculation + "_np4"), calculation) - compare_frames(calculation, serial_frames, parallel_frames, 2) - print("{}: {} consecutive evaluations agree at one and four ranks".format( - calculation, len(serial_frames))) - - -if __name__ == "__main__": - main() diff --git a/tests/integrate/validation_tools/check_md_output_cadence.py b/tests/integrate/validation_tools/check_md_output_cadence.py deleted file mode 100644 index 865a4d6e2be..00000000000 --- a/tests/integrate/validation_tools/check_md_output_cadence.py +++ /dev/null @@ -1,148 +0,0 @@ -"""Check MD structure output and restart cadences independently.""" - -import argparse -from pathlib import Path -import shutil -import subprocess -import tempfile - - -def run_case(executable, fixture, out_stru, out_freq_ion, out_app_flag, expected, - thermo_freq=1, legacy_stru_dir=False): - with tempfile.TemporaryDirectory(prefix="abacus-md-cadence-") as scratch: - work = Path(scratch) - shutil.copyfile(fixture / "STRU", work / "STRU") - input_text = (fixture / "INPUT").read_text() - input_text = input_text.replace("out_stru 0", "out_stru " + str(out_stru)) - input_text = input_text.replace("out_freq_ion 2", "out_freq_ion " + str(out_freq_ion)) - input_text = input_text.replace("out_app_flag 0", "out_app_flag " + str(out_app_flag)) - input_text += "\ncal_stress 1\n" - input_text += "out_thermo_freq {}\n".format(thermo_freq) - (work / "INPUT").write_text(input_text) - if legacy_stru_dir: - (work / "OUT.cadence" / "STRU").mkdir(parents=True) - result = subprocess.run( - [executable], cwd=str(work), stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, universal_newlines=True, - check=False) - if result.returncode: - raise AssertionError("ABACUS failed:\n" + result.stdout) - - output = work / "OUT.cadence" - if (output / "MD_dump").exists(): - raise AssertionError("Removed MD_dump was written") - running_log = (output / "running_md.log").read_text() - expected_thermo = 0 if thermo_freq == 0 else len(range(0, 5, thermo_freq)) - if running_log.count("VIRIAL (kbar):") != expected_thermo: - raise AssertionError("Unexpected virial output cadence") - if running_log.count("MD TOTAL STRESS (kbar):") != expected_thermo: - raise AssertionError("Unexpected total stress output cadence") - if "#TOTAL-STRESS" in running_log or "#TOTAL-FORCE" in running_log: - raise AssertionError("Solver wrote per-step force or stress outside MD output") - structure_dir = output / "STRUC" if out_app_flag == 2 else output - frames = {path.name for path in structure_dir.glob("STRU*") if path.is_file()} - frames.discard("STRU_restart") - if frames != expected: - raise AssertionError("out_stru={}, out_freq_ion={}, out_app_flag={} produced {}, expected {}\n{}".format( - out_stru, out_freq_ion, out_app_flag, sorted(frames), sorted(expected), result.stdout)) - restart = output / "Restart_md.txt" - if not restart.is_file() or restart.stat().st_size == 0: - raise AssertionError("Missing MD restart for out_stru={}".format(out_stru)) - restart_step = restart.read_text().splitlines()[0] - if restart_step != "3": - raise AssertionError("out_stru={} restart step is {}, expected 3".format( - out_stru, restart_step)) - checkpoint = output / "STRU_restart" - if not checkpoint.is_file(): - raise AssertionError("Missing STRU_restart") - checkpoint_text = checkpoint.read_text() - if "# MD step 4" not in checkpoint_text or " v " not in checkpoint_text or " f " in checkpoint_text: - raise AssertionError("Restart structure lacks matching step or velocities") - for filename in expected: - frame_text = (structure_dir / filename).read_text() - if out_stru == 2: - if "_atom_site_fract_x" not in frame_text or "_cell_length_a" not in frame_text: - raise AssertionError("CIF structure lacks cell or atomic positions: " + filename) - if " v " in frame_text or " f " in frame_text: - raise AssertionError("CIF structure unexpectedly contains STRU atom fields: " + filename) - elif "Cartesian_angstrom" not in frame_text or " v " not in frame_text or " f " not in frame_text: - raise AssertionError("Ordinary structure lacks coordinates, velocities or forces: " + filename) - - if legacy_stru_dir: - legacy_frame = output / "STRU" / "STRU" - if not legacy_frame.is_file() or "# MD step 5" not in legacy_frame.read_text(): - raise AssertionError("Legacy STRU directory blocked periodic MD output") - - if out_stru == 0: - restart_input = input_text.replace("md_nstep 5", "md_nstep 7") - restart_input = restart_input.replace("init_vel 0", "init_vel 1") - restart_input += "\nmd_restart 1\n" - (work / "INPUT").write_text(restart_input) - continuation = subprocess.run( - [executable], cwd=str(work), stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, universal_newlines=True, - check=False) - if continuation.returncode: - raise AssertionError("MD restart failed:\n" + continuation.stdout) - if restart.read_text().splitlines()[0] != "6": - raise AssertionError("MD continuation did not reach restart step 6") - if "# MD step 7" not in checkpoint.read_text(): - raise AssertionError("MD continuation did not update STRU_restart") - - -def run_legacy_restart_case(executable, fixture): - with tempfile.TemporaryDirectory(prefix="abacus-md-legacy-restart-") as scratch: - work = Path(scratch) - shutil.copyfile(fixture / "STRU", work / "STRU") - input_text = (fixture / "INPUT").read_text() - (work / "INPUT").write_text(input_text) - initial = subprocess.run([executable], cwd=work, capture_output=True, - text=True, check=False) - if initial.returncode: - raise AssertionError("Initial MD run failed:\n" + initial.stdout + initial.stderr) - output = work / "OUT.cadence" - legacy_dir = output / "STRU" - legacy_dir.mkdir() - (output / "STRU_restart").rename(legacy_dir / "STRU_MD_3") - restart_input = input_text.replace("md_nstep 5", "md_nstep 7") - restart_input = restart_input.replace("init_vel 0", "init_vel 1") - restart_input = restart_input.replace("out_stru 0", "out_stru 1") - restart_input = restart_input.replace("out_app_flag 0", "out_app_flag 1") - restart_input += "\nmd_restart 1\n" - (work / "INPUT").write_text(restart_input) - continuation = subprocess.run([executable], cwd=work, capture_output=True, - text=True, check=False) - if continuation.returncode: - raise AssertionError("Legacy MD restart failed:\n" + continuation.stdout + continuation.stderr) - if not (legacy_dir / "STRU").is_file() or not (output / "STRU_FINAL").is_file(): - raise AssertionError("Legacy STRU directory blocked current MD output") - running_log = (output / "running_md.log").read_text() - if "Read file: " not in running_log or "STRU_MD_3" not in running_log: - raise AssertionError("Restart source was not recorded in running_md.log") - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("executable") - parser.add_argument("fixture", type=Path) - args = parser.parse_args() - run_case(args.executable, args.fixture, 0, 2, 0, set()) - run_case(args.executable, args.fixture, 1, 0, 0, {"STRU_FINAL"}) - run_case(args.executable, args.fixture, 1, 0, 1, {"STRU_FINAL"}) - run_case(args.executable, args.fixture, 1, 0, 2, {"STRU_FINAL"}) - run_case(args.executable, args.fixture, 1, 2, 0, {"STRU", "STRU_FINAL"}) - run_case(args.executable, args.fixture, 1, 2, 1, {"STRU", "STRU_FINAL"}) - run_case(args.executable, args.fixture, 1, 2, 2, {"STRU1", "STRU3", "STRU5", "STRU_FINAL"}) - run_case(args.executable, args.fixture, 1, 2, 1, {"STRU", "STRU_FINAL"}, thermo_freq=3) - run_case(args.executable, args.fixture, 1, 2, 1, {"STRU", "STRU_FINAL"}, thermo_freq=0) - run_case(args.executable, args.fixture, 1, 2, 1, {"STRU_FINAL"}, legacy_stru_dir=True) - run_case(args.executable, args.fixture, 2, 0, 1, {"STRU_FINAL.cif"}) - run_case(args.executable, args.fixture, 2, 2, 0, {"STRU.cif", "STRU_FINAL.cif"}) - run_case(args.executable, args.fixture, 2, 2, 1, {"STRU.cif", "STRU_FINAL.cif"}) - run_case(args.executable, args.fixture, 2, 2, 2, - {"STRU1.cif", "STRU3.cif", "STRU5.cif", "STRU_FINAL.cif"}) - run_legacy_restart_case(args.executable, args.fixture) - - -if __name__ == "__main__": - main()