diff --git a/tests/01_PW/CASES_CPU.txt b/tests/01_PW/CASES_CPU.txt index c135aaa9fc..9a32f65501 100644 --- a/tests/01_PW/CASES_CPU.txt +++ b/tests/01_PW/CASES_CPU.txt @@ -136,3 +136,4 @@ scf_sccs_full relax_sccs scf_sccs_sa scf_sccs_sa_pcc_2d_lowpass +dfpt_si_g diff --git a/tests/01_PW/dfpt_si_g/INPUT b/tests/01_PW/dfpt_si_g/INPUT new file mode 100644 index 0000000000..3fc7519938 --- /dev/null +++ b/tests/01_PW/dfpt_si_g/INPUT @@ -0,0 +1,19 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +esolver_type dfpt +nbands 4 +symmetry -1 +pseudo_dir ../../PP_ORB +ecutwfc 8 +ecutrho 32 +scf_thr 1e-4 +smearing_method fixed +scf_nmax 50 +basis_type pw +dfpt_qfile QFILE +dfpt_conv_thr 1e-3 +dfpt_max_iter 30 +dfpt_compute_q0 false +dfpt_asr crystal +dfpt_loto false diff --git a/tests/01_PW/dfpt_si_g/KPT b/tests/01_PW/dfpt_si_g/KPT new file mode 100644 index 0000000000..c289c0158a --- /dev/null +++ b/tests/01_PW/dfpt_si_g/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/01_PW/dfpt_si_g/QFILE b/tests/01_PW/dfpt_si_g/QFILE new file mode 100644 index 0000000000..3feb9215d8 --- /dev/null +++ b/tests/01_PW/dfpt_si_g/QFILE @@ -0,0 +1,4 @@ +Q_POINTS +1 +Direct +0.0000000000 0.0000000000 0.0000000000 1.0 diff --git a/tests/01_PW/dfpt_si_g/README b/tests/01_PW/dfpt_si_g/README new file mode 100644 index 0000000000..6c79de04f1 --- /dev/null +++ b/tests/01_PW/dfpt_si_g/README @@ -0,0 +1 @@ +dfpt_si_g: 2-atom Si (a=10.2612 Bohr), ONCV PBE, 8/32 Ry, Gamma-only k, Gamma-only q. Smoke test: verifies DFPT phonon frequency output (~4s). diff --git a/tests/01_PW/dfpt_si_g/STRU b/tests/01_PW/dfpt_si_g/STRU new file mode 100644 index 0000000000..29b11e209b --- /dev/null +++ b/tests/01_PW/dfpt_si_g/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 28.0855 Si_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 diff --git a/tests/01_PW/dfpt_si_g/result.ref b/tests/01_PW/dfpt_si_g/result.ref new file mode 100644 index 0000000000..d6aabcf6cc --- /dev/null +++ b/tests/01_PW/dfpt_si_g/result.ref @@ -0,0 +1,9 @@ +etotref -196.0356347344235 +etotperatomref -98.0178173672 +dfpt_freq_q0_m0 -0.000005 +dfpt_freq_q0_m1 0.000003 +dfpt_freq_q0_m2 0.000006 +dfpt_freq_q0_m3 726.293102 +dfpt_freq_q0_m4 727.655079 +dfpt_freq_q0_m5 727.946529 +totaltimeref 4.31 diff --git a/tests/integrate/Autotest.sh b/tests/integrate/Autotest.sh index 601714403b..f2d901432d 100755 --- a/tests/integrate/Autotest.sh +++ b/tests/integrate/Autotest.sh @@ -242,6 +242,12 @@ check_out() { compare_thr=$descriptor_thr elif [[ $key == wfi*.cube || $key == *_wfc_fp_rms || $key == *_wfc_fp_power_* || $key == *_wfc_fp_cross_* ]]; then compare_thr=$wfc_thr + elif [[ $key == dfpt_freq_* || $key == dfpt_loto_* ]]; then + # DFPT phonon frequencies (cm^-1): same-binary reruns reproduce + # the six printed decimals exactly; the margin only absorbs + # last-digit rounding across toolchains. The case-wide default + # stays at 1e-7 so etot/force keys keep their strict bound. + compare_thr=0.0001 fi if [ $(check_deviation_pass $deviation $compare_thr) = 0 ]; then if [ $key == "totalforceref" ]; then @@ -354,6 +360,13 @@ run_case() { elif grep -qE '^[[:space:]]*of_ml_gene_data[[:space:]]+1([[:space:]]|$)' INPUT; then # of_ml_gene_data supports single-rank only. "$mpi_launcher" "$mpi_np_flag" 1 "${mpi_preflags[@]}" "$abacus" "${mpi_postflags[@]}" >log.txt + elif grep -qiE '^[[:space:]]*esolver_type[[:space:]]+dfpt([[:space:]]|$)' INPUT; then + # The DFPT esolver is currently a serial implementation; MPI + # domain decomposition is planned future work. Running more than + # one rank crashes in the response-solve FFT gather-scatter + # (MPI_Alltoallv with rank-inconsistent stick maps). Run + # single-rank like the of_ml_gene_data case above. + "$mpi_launcher" "$mpi_np_flag" 1 "${mpi_preflags[@]}" "$abacus" "${mpi_postflags[@]}" >log.txt else "$mpi_launcher" "$mpi_np_flag" $np "${mpi_preflags[@]}" "$abacus" "${mpi_postflags[@]}" >log.txt fi diff --git a/tests/integrate/CMakeLists.txt b/tests/integrate/CMakeLists.txt index c07cf70b4f..b3670710fd 100644 --- a/tests/integrate/CMakeLists.txt +++ b/tests/integrate/CMakeLists.txt @@ -32,4 +32,9 @@ if(LR_FORCE_TEST_PYTHON) COMMAND ${LR_FORCE_TEST_PYTHON} -m unittest discover -s ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools -p test_props_basic.py) set_tests_properties(md_force_collector PROPERTIES TIMEOUT 30) + add_test( + NAME dfpt_freq_collector + COMMAND ${LR_FORCE_TEST_PYTHON} -m unittest discover -s + ${CMAKE_CURRENT_SOURCE_DIR}/validation_tools -p test_props_dfpt.py) + set_tests_properties(dfpt_freq_collector PROPERTIES TIMEOUT 30) endif() diff --git a/tests/integrate/validation_tools/catch_properties.sh b/tests/integrate/validation_tools/catch_properties.sh index 1aa755c630..6add6375a6 100755 --- a/tests/integrate/validation_tools/catch_properties.sh +++ b/tests/integrate/validation_tools/catch_properties.sh @@ -20,6 +20,7 @@ source "$PROPS_SCRIPT_DIR/props_cube.sh" source "$PROPS_SCRIPT_DIR/props_ml.sh" source "$PROPS_SCRIPT_DIR/props_tddft.sh" source "$PROPS_SCRIPT_DIR/props_deepks.sh" +source "$PROPS_SCRIPT_DIR/props_dfpt.sh" # Property collectors run in the same order as the original monolithic # script so result files stay byte-identical; props_finalize() writes the @@ -28,6 +29,13 @@ source "$PROPS_SCRIPT_DIR/props_deepks.sh" run_lr_force_props run_basic_props || exit 1 +#--------------------------------------- +# dfpt collectors (props_dfpt.sh): phonon frequencies per q point; +# a DFPT case with no complete frequency block fails the collection +# instead of passing on etot alone +#--------------------------------------- +run_dfpt_props || exit 1 + #------------------------------- # matrix collectors: out_dm1 (props_mat.sh) #------------------------------- diff --git a/tests/integrate/validation_tools/props_common.sh b/tests/integrate/validation_tools/props_common.sh index 805ea7f9de..db735e1122 100644 --- a/tests/integrate/validation_tools/props_common.sh +++ b/tests/integrate/validation_tools/props_common.sh @@ -49,7 +49,7 @@ sum_file() { get_input_key_value() { key=$1 inputf=$2 - value=$(awk -v key=$key '{if($1==key) a=$2} END {print a}' $inputf) + value=$(awk -v key=$key 'BEGIN{key=toupper(key)} {if(toupper($1)==key) a=$2} END {print a}' $inputf) echo $value } diff --git a/tests/integrate/validation_tools/props_dfpt.sh b/tests/integrate/validation_tools/props_dfpt.sh new file mode 100644 index 0000000000..5c03fcb8e3 --- /dev/null +++ b/tests/integrate/validation_tools/props_dfpt.sh @@ -0,0 +1,143 @@ +#!/bin/bash + +# Property collectors for the PW DFPT esolver (esolver_type dfpt). +# +# The frequency blocks are printed to stdout by DFPT_PW (captured in the +# test's log file): one "DFPT phonon frequencies at q #" block per q +# point and, at Gamma, a "DFPT LO-TO corrected frequencies" block along +# the q->0 direction. Each block lists " : cm^-1" lines. +# Both blocks are collected so result.ref pins the analytic (TO) and the +# direction-dependent (LO) spectrum separately. +# +# Keys emitted: +# dfpt_freq_q_m plain (analytic) frequency of q point i, mode j +# dfpt_loto_q_m LO-TO corrected frequency (Gamma only) +# +# Completeness guard: the collection fails (returns 1) when the log is +# missing, contains no analytic frequency block, any block's mode set +# does not start at mode 0 and form a dense 0..N sequence, any freq +# block's total does not equal 3*natom (read from STRU), or a freq +# block header is followed by no mode rows at all. These checks apply +# on first-time reference generation as well as comparison runs. + +run_dfpt_props() { + if [ -z "$esolver_type" ] || [ "$esolver_type" != "dfpt" ]; then + return + fi + local dfpt_log="${1:-log.txt}" + if [ ! -f "$dfpt_log" ]; then + echo "ERROR: run_dfpt_props: $dfpt_log not found, DFPT frequencies not collected" >&2 + return 1 + fi + # count atoms from STRU: walk each species block in ATOMIC_POSITIONS + # (element name → magnetic moment → atom count → coordinate lines) and + # sum the counts; handles multi-species cells and single-letter elements + local natom=0 + local stru_present=0 + if [ -f "STRU" ]; then + stru_present=1 + natom=$(awk ' + function is_blank(s){ return s ~ /^[ ]*$/ } + function skip_blanks(){ while((getline line > 0) && is_blank(line)); return line } + /ATOMIC_POSITIONS/{found=1; next} + !found{next} + is_blank($0){next} + found && /^(Direct|Cartesian|direct|cartesian)/{next} + found && /^[ ]*[A-Za-z][A-Za-z0-9]*([ ].*)?$/{ + # skip blank lines before the magnetic moment line + line = skip_blanks() + if (line == "" || is_blank(line)) next + # skip blank lines before the atom count line + line = skip_blanks() + if (line == "" || is_blank(line)) next + split(line, fields) + cnt = fields[1] + 0 + if (cnt <= 0) next + natom += cnt + for(i=0; i/dev/null) + # STRU exists but atom count is unreadable: reject rather than + # silently skipping the mode-count validation (an incomplete + # spectrum could become the first reference) + if [ "$natom" -le 0 ] 2>/dev/null; then + echo "ERROR: run_dfpt_props: STRU exists but atom count is unreadable (natom=$natom); cannot derive 3*natom for mode validation" >&2 + return 1 + fi + fi + local expected_total=$((natom * 3)) + # emit one "key value" line per frequency; awk rewrites the block header + # into the key prefix and drops everything else. Mode 0 must open every + # block; indices are checked for dense 0..N; every freq block must end + # at exactly expected_total (3*natom from STRU); empty freq blocks fail. + if ! awk -v expected_total="$expected_total" ' + function fail(msg) { printf "ERROR: run_dfpt_props: %s\n", msg > "/dev/stderr"; bad = 1; exit 1 } + function close_block() { + if (seq == "") return # no previous block to close + if (nextmode[seq] == 0) { + fail(block_type[seq] " block " seq " has no mode rows") + } + if (expected_total > 0 && nextmode[seq] != expected_total) { + fail(block_type[seq] " block " seq " has " nextmode[seq] " modes; expected " expected_total " (3*natom from STRU)") + } + if (expected_total == 0 && expected_modes > 0 && nextmode[seq] != expected_modes) { + fail(block_type[seq] " block " seq " has " nextmode[seq] " modes; expected " expected_modes " (from first block)") + } + if (expected_modes == 0) expected_modes = nextmode[seq] + } + /^ *DFPT phonon frequencies at q #/ { + close_block() + match($0, /q #[0-9]+/); qi = substr($0, RSTART + 3, RLENGTH - 3); + block = "freq"; block_qi = qi; seq = "freq:" qi; nextmode[seq] = 0; block_type[seq] = "freq"; next + } + /^ *DFPT LO-TO corrected frequencies at q #/ { + close_block() + match($0, /q #[0-9]+/); qi = substr($0, RSTART + 3, RLENGTH - 3); + block = "loto"; block_qi = qi; seq = "loto:" qi; nextmode[seq] = 0; block_type[seq] = "loto"; next + } + /^ *mode +[0-9]+ :/ { + if (block == "") next + mi = $2 + if (mi != nextmode[seq]) { + fail("mode " mi " out of sequence in " seq " (expected " nextmode[seq] "): missing or dropped rows") + } + nextmode[seq] = mi + 1 + val = $4 + # reject empty or nonnumeric frequency tokens (format drift) + if (val !~ /^-?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?$/) { + fail("nonnumeric frequency token [" val "] in " seq " mode " mi) + } + printf "dfpt_%s_q%s_m%s %s\n", block, block_qi, mi, val + next + } + { if ($0 !~ /^ *mode/ && block != "" && $0 ~ /[^ ]/) block = "" } + END { + if (!bad) { + close_block() + if (NR == 0) fail("empty log") + if (expected_modes == 0) fail("no complete frequency block found") + } + } + ' "$dfpt_log" >> "$props_result_file"; then + echo "ERROR: run_dfpt_props: incomplete phonon frequency spectrum in $dfpt_log (truncated output or format drift); failing the collection" >&2 + return 1 + fi + # zero-key guard + if ! grep -q "^dfpt_freq_" "$props_result_file"; then + echo "ERROR: run_dfpt_props: no complete phonon frequency block found in $dfpt_log (truncated output or format drift); failing the collection" >&2 + return 1 + fi + # cross-reference guard (comparison mode only; first-time generation + # relies on the STRU-derived 3*natom check above) + local ref_file="result.ref" + if [ -f "$ref_file" ] && grep -q "^dfpt_freq_" "$ref_file"; then + local missing + missing=$(comm -23 <(grep -o "^dfpt_[a-z]*_q[0-9]*_m[0-9]*" "$ref_file" | sort -u) \ + <(grep -o "^dfpt_[a-z]*_q[0-9]*_m[0-9]*" "$props_result_file" | sort -u)) + if [ -n "$missing" ]; then + echo "ERROR: run_dfpt_props: collected spectrum is incomplete; missing keys (present in result.ref): $missing" >&2 + return 1 + fi + fi +} diff --git a/tests/integrate/validation_tools/test_props_dfpt.py b/tests/integrate/validation_tools/test_props_dfpt.py new file mode 100644 index 0000000000..b102f0097f --- /dev/null +++ b/tests/integrate/validation_tools/test_props_dfpt.py @@ -0,0 +1,214 @@ +"""Regression checks for DFPT phonon frequency collection.""" + +import os +from pathlib import Path +import shlex +import subprocess +import tempfile +import unittest + + +TOOLS = Path(__file__).resolve().parent + +# minimal STRU for 2-atom Si (the props_dfpt collector reads it for natom) +STRU_2SI = """ATOMIC_SPECIES +Si 28.0855 Si.upf + +LATTICE_CONSTANT +1.8897261255 + +LATTICE_VECTORS +0.00000000 2.71500000 2.71500000 +2.71500000 0.00000000 2.71500000 +2.71500000 2.71500000 0.00000000 + +ATOMIC_POSITIONS +Direct + +Si +0.0 +2 +0.00000000 0.00000000 0.00000000 1 1 1 +0.25000000 0.25000000 0.25000000 1 1 1 +""" + + +STRU_COMMENTED_MIXED = """ATOMIC_POSITIONS +Cartesian_angstrom + +Si # silicon +0.0 +1 +2.715 0.0 0.0 1 1 1 + +Ge # germanium +0.0 +1 +2.715 2.715 0.0 1 1 1 +""" + +STRU_INDENTED = """ATOMIC_POSITIONS +Direct + + Si + 0.0 + 2 + 0.0 0.0 0.0 1 1 1 + 0.25 0.25 0.25 1 1 1 +""" + +STRU_BLANK_LINES = """ATOMIC_POSITIONS +Direct + +Si + +0.0 + +2 +0.0 0.0 0.0 1 1 1 +0.25 0.25 0.25 1 1 1 +""" + +GOOD_FREQ_BLOCK = ( + " DFPT phonon frequencies at q #0 = (0.000000 0.000000 0.000000) (direct) in cm^-1:\n" + " mode 0 : -0.000001 cm^-1\n" + " mode 1 : 0.000002 cm^-1\n" + " mode 2 : 0.000003 cm^-1\n" + " mode 3 : 100.000000 cm^-1\n" + " mode 4 : 101.000000 cm^-1\n" + " mode 5 : 102.000000 cm^-1\n" +) + + +class DFPTFrequencyCollectorTest(unittest.TestCase): + def run_collector(self, log_text, stru_text=STRU_2SI): + with tempfile.TemporaryDirectory(prefix="abacus-dfpt-collector-") as scratch: + case = Path(scratch) + (case / "log.txt").write_text(log_text, encoding="utf-8") + if stru_text is not None: + (case / "STRU").write_text(stru_text, encoding="utf-8") + command = ( + 'source "$1"; esolver_type=dfpt; ' + 'props_result_file=result.out; ' + '> $props_result_file; run_dfpt_props log.txt' + ) + result = subprocess.run( + ["bash", "-c", command, "dfpt-collector-test", + str(TOOLS / "props_dfpt.sh")], + cwd=case, capture_output=True, text=True, check=False, + ) + output = (case / "result.out").read_text(encoding="utf-8") if (case / "result.out").exists() else "" + return result, output + + # --- successful scenarios --- + + def test_complete_block_passes(self): + result, output = self.run_collector(GOOD_FREQ_BLOCK) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(output.strip().splitlines()), 6) + self.assertIn("dfpt_freq_q0_m3 100.000000", output) + self.assertIn("dfpt_freq_q0_m5 102.000000", output) + + def test_freq_and_loto_blocks_pass(self): + loto = GOOD_FREQ_BLOCK.replace( + "phonon frequencies", "LO-TO corrected frequencies") + result, output = self.run_collector(GOOD_FREQ_BLOCK + loto) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(output.strip().splitlines()), 12) + self.assertIn("dfpt_loto_q0_m0 -0.000001", output) + + # --- missing mode 0 --- + + def test_missing_mode_zero_fails(self): + log = GOOD_FREQ_BLOCK.replace(" mode 0 :", " mode 99 :", 1) + result, output = self.run_collector(log) + self.assertNotEqual(result.returncode, 0) + + def test_block_starting_at_mode_one_fails(self): + lines = GOOD_FREQ_BLOCK.strip().splitlines() + lines = [ln for ln in lines if "mode 0" not in ln] + log = "\n".join(lines) + "\n" + result, output = self.run_collector(log) + self.assertNotEqual(result.returncode, 0) + + # --- empty blocks --- + + def test_empty_freq_block_fails(self): + # freq header with no mode rows followed by another block + log = (" DFPT phonon frequencies at q #0 = test\n" + + GOOD_FREQ_BLOCK) + result, output = self.run_collector(log) + self.assertNotEqual(result.returncode, 0) + + def test_empty_loto_block_fails(self): + loto_header = (" DFPT LO-TO corrected frequencies at q #0 = test\n") + result, output = self.run_collector(GOOD_FREQ_BLOCK + loto_header) + self.assertNotEqual(result.returncode, 0) + + # --- truncated blocks --- + + def test_truncated_freq_block_fails(self): + # only 3 of 6 modes (STRU says 2 atoms → 6 modes) + lines = GOOD_FREQ_BLOCK.strip().splitlines() + log = "\n".join(lines[:4]) + "\n" # header + modes 0,1,2 + result, output = self.run_collector(log) + self.assertNotEqual(result.returncode, 0) + + def test_truncated_loto_block_fails(self): + loto = GOOD_FREQ_BLOCK.replace( + "phonon frequencies", "LO-TO corrected frequencies") + lines = loto.strip().splitlines() + loto_short = "\n".join(lines[:4]) + "\n" # header + modes 0,1,2 + result, output = self.run_collector(GOOD_FREQ_BLOCK + loto_short) + self.assertNotEqual(result.returncode, 0) + + # --- nonnumeric token --- + + def test_nonnumeric_token_fails(self): + log = GOOD_FREQ_BLOCK.replace("100.000000", "abc") + result, output = self.run_collector(log) + self.assertNotEqual(result.returncode, 0) + + # --- empty log --- + + def test_empty_log_fails(self): + result, output = self.run_collector("") + self.assertNotEqual(result.returncode, 0) + + # --- no STRU → expected_total=0 → falls back to first-block count --- + + def test_no_stru_uses_first_block_count(self): + result, output = self.run_collector(GOOD_FREQ_BLOCK, stru_text=None) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(output.strip().splitlines()), 6) + + + # --- STRU parser edge cases --- + + def test_commented_mixed_species_stru_passes(self): + """Si/Ge with comments, Cartesian, first coordinate 2.715 (x > atom count).""" + result, output = self.run_collector(GOOD_FREQ_BLOCK, stru_text=STRU_COMMENTED_MIXED) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(output.strip().splitlines()), 6) + + def test_indented_element_label_stru_passes(self): + """Indented element names (leading whitespace) are valid STRU.""" + result, output = self.run_collector(GOOD_FREQ_BLOCK, stru_text=STRU_INDENTED) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(output.strip().splitlines()), 6) + + def test_blank_lines_in_species_block_stru_passes(self): + """Blank lines within a species block (before mag/count) are valid STRU.""" + result, output = self.run_collector(GOOD_FREQ_BLOCK, stru_text=STRU_BLANK_LINES) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(output.strip().splitlines()), 6) + + def test_unreadable_stru_fails(self): + """STRU exists but atom count cannot be parsed → reject.""" + bad_stru = "ATOMIC_POSITIONS\nDirect\n\nGarbageData\n" + result, output = self.run_collector(GOOD_FREQ_BLOCK, stru_text=bad_stru) + self.assertNotEqual(result.returncode, 0) + + +if __name__ == "__main__": + unittest.main()