Repository navigation
Write formatted Wannier90 spin matrices for spinor LCAO calculations #8331
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Stardust0831
wants to merge
6
commits into
deepmodeling:develop
Choose a base branch
from
Stardust0831:feat/lcao-wannier-spn
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+449
−7
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
fadd322
Write formatted Wannier90 spin matrices for spinor LCAO calculations
Stardust0831 e2dd1b9
Validate Wannier spin companions and synchronize writer errors
Stardust0831 0aeffe5
Name Wannier spin-matrix rows and log the full SPN path
Stardust0831 b8e8342
Move the Wannier90 spin-matrix regression driver beside the interface…
Stardust0831 2734993
Default to writing SPN for supported spinor LCAO Wannier exports
Stardust0831 178f0e8
Merge branch 'develop' into feat/lcao-wannier-spn
ZhouXY-PKU File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 125 additions & 0 deletions
125
interfaces/Wannier90_interface/tests/check_wannier_spn.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| """Run the spinor LCAO interface and check its formatted Pauli matrices.""" | ||
|
|
||
| import re | ||
| import shutil | ||
| import struct | ||
| import subprocess | ||
| import sys | ||
| import tempfile | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
|
|
||
|
|
||
| def read_coefficients(path): | ||
| with path.open("rb") as stream: | ||
| _, _, _, _, bands, orbitals = struct.unpack("=i3d2i", stream.read(36)) | ||
| records = np.fromfile(stream, dtype=[("band", "=i4"), ("e", "=f8"), | ||
| ("occ", "=f8"), ("c", "=c16", (orbitals,))]) | ||
| np.testing.assert_array_equal(records["band"], np.arange(1, bands + 1)) | ||
| return records["c"].T | ||
|
|
||
|
|
||
| def read_overlap(path): | ||
| with path.open("rb") as stream: | ||
| size, = struct.unpack("=i", stream.read(4)) | ||
| overlap = np.zeros((size, size), dtype=complex) | ||
| overlap[np.triu_indices(size)] = np.fromfile(stream, dtype="=c16") | ||
| return overlap + np.triu(overlap, 1).conj().T | ||
|
|
||
|
|
||
| def check_spin(out): | ||
| pauli = [np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]), np.diag([1, -1])] | ||
| with (out / "oxygen.spn").open() as stream: | ||
| next(stream) | ||
| bands, kpoints = map(int, next(stream).split()) | ||
| assert (bands, kpoints) == (13, 2) | ||
| data = np.loadtxt(stream) | ||
| assert data.shape == (3 * kpoints * bands * (bands + 1) // 2, 2) | ||
| actual = data[:, 0] + 1j * data[:, 1] | ||
| expected = [] | ||
| overlaps = [] | ||
| for ik in range(1, kpoints + 1): | ||
| c = read_coefficients(next(out.rglob(f"wfk{ik}s4_nao.dat"))) | ||
| c = np.delete(c, 2, axis=1) # exclude_bands = 3 | ||
| s = read_overlap(next(out.rglob(f"sk{ik}_nao.dat")))[::2, ::2] | ||
| overlaps.append(s) | ||
| matrices = [c.conj().T @ np.kron(s, sigma) @ c for sigma in pauli] | ||
| for m in range(bands): | ||
| for n in range(m + 1): | ||
| expected.extend(mat[n, m] for mat in matrices) | ||
| assert np.max(abs(overlaps[0] - overlaps[1])) > 1e-4 | ||
| np.testing.assert_allclose(actual, expected, atol=1e-10, rtol=0, equal_nan=False) | ||
| print(f"Verified {actual.size} spin matrix elements, max error {max(abs(actual - expected)):.3e}") | ||
|
|
||
|
|
||
| def check_spn_io_failure(work, abacus, logs, error): | ||
| result = subprocess.run(abacus, cwd=work, capture_output=True, text=True, timeout=60) | ||
| assert result.returncode != 0, "ABACUS accepted an unwritable .spn file" | ||
| diagnostic = f"{error} OUT.ABACUS/oxygen.spn" | ||
| for log in logs: | ||
| assert diagnostic in log.read_text(), f"{log.name} missing '{diagnostic}'\n{result.stdout}{result.stderr}" | ||
| print(f"Verified '{diagnostic}' on {len(logs)} MPI rank(s)") | ||
|
|
||
|
|
||
| def main(work, wannier, postw90, abacus): | ||
| tests = Path(__file__).resolve().parents[3] / "tests" | ||
| case = tests / "03_NAO_multik" / "wannier_spn" | ||
| shutil.copy(case / "STRU", work) | ||
| shutil.copy(case / "KPT", work) | ||
| shutil.copy(case / "oxygen.win", work) | ||
| common = (case / "INPUT").read_text() + f"\npseudo_dir {tests}/PP_ORB\norbital_dir {tests}/PP_ORB\n" | ||
| subprocess.run([wannier, "-pp", "oxygen"], cwd=work, check=True) | ||
| scf = common + "calculation scf\nout_chg 1\n" | ||
| (work / "INPUT").write_text(scf + "out_wannier_spn 1\n") | ||
| result = subprocess.run(abacus, cwd=work, capture_output=True, text=True) | ||
| assert result.returncode != 0 and "Invalid INPUT parameter 'out_wannier_spn'" in result.stdout + result.stderr | ||
| (work / "INPUT").write_text(scf) | ||
| subprocess.run(abacus, cwd=work, check=True) | ||
| nscf = common + "calculation nscf\ninit_chg file\ntowannier90 1\nwannier_method 2\nnnkpfile oxygen.nnkp\n" | ||
| out = work / "OUT.ABACUS" | ||
| assert not (out / "oxygen.spn").exists() | ||
| (work / "INPUT").write_text(nscf + "out_wannier_spn 0\nout_wannier_mmn 0\nout_wannier_amn 0\n") | ||
| subprocess.run(abacus, cwd=work, check=True) | ||
| assert (out / "oxygen.eig").is_file() and not (out / "oxygen.spn").exists() | ||
| (work / "INPUT").write_text(nscf + "out_wfc_lcao 2\nout_hsk 2\n") | ||
| subprocess.run(abacus, cwd=work, check=True) | ||
| running_log = (out / "running_nscf.log").read_text() | ||
| match = re.search(r"^ Wrote Wannier90 spin matrices to (.+)$", running_log, re.MULTILINE) | ||
| assert match, "Missing .spn path in running_nscf.log" | ||
| logged_spn = Path(match.group(1)) | ||
| assert logged_spn.is_absolute() and logged_spn.samefile(out / "oxygen.spn"), logged_spn | ||
| check_spin(out) | ||
| for ext in ["eig", "mmn", "amn", "spn"]: | ||
| shutil.copy(out / f"oxygen.{ext}", work) | ||
| subprocess.run([wannier, "oxygen"], cwd=work, check=True) | ||
| subprocess.run([postw90, "oxygen"], cwd=work, check=True) | ||
| output = (work / "oxygen.wpout").read_text() | ||
| assert "Reading spin matrices from oxygen.spn" in output and "All done" in output | ||
| moment = [float(x) for x in re.findall(r"[xyz] component:\s+(\S+)", output)] | ||
| assert len(moment) == 3 and np.isfinite(moment).all() | ||
| print(f"postw90 spin moment (Bohr magnetons/cell): {moment}") | ||
|
|
||
| # Native ABACUS can export spin matrices independently of the Python workflow. | ||
| companions = [out / f"oxygen.{ext}" for ext in ("mmn", "amn", "eig")] | ||
| spn = out / "oxygen.spn" | ||
| for path in [spn, *companions]: | ||
| path.unlink() | ||
| (work / "INPUT").write_text(nscf + "out_wannier_spn 1\nout_wannier_mmn 0\n" | ||
| "out_wannier_amn 0\nout_wannier_eig 0\nout_alllog 1\n") | ||
| subprocess.run(abacus, cwd=work, check=True) | ||
| assert spn.stat().st_size > 0 and not any(path.exists() for path in companions) | ||
| logs = sorted(out.glob("running_nscf_*.log")) | ||
| assert logs, "out_alllog did not produce per-rank NSCF logs" | ||
| spn.unlink() | ||
| spn.mkdir() | ||
| check_spn_io_failure(work, abacus, logs, "Cannot open") | ||
| spn.rmdir() | ||
| if Path("/dev/full").is_char_device(): | ||
| spn.symlink_to("/dev/full") | ||
| check_spn_io_failure(work, abacus, logs, "Error writing") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| with tempfile.TemporaryDirectory() as scratch: | ||
| main(Path(scratch), sys.argv[1], sys.argv[2], sys.argv[3:]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
| from unittest.mock import patch | ||
|
|
||
| from abacusw90.interface import ABACUSWannier90 | ||
|
|
||
|
|
||
| class TestSpinOutput(unittest.TestCase): | ||
| def test_spn_default(self): | ||
| job = ABACUSWannier90() | ||
| for overrides, expected in ( | ||
| ({}, True), ({"out_wannier_spn": "0"}, False), | ||
| ({"towannier90": "no"}, False), ({"calculation": "scf"}, False), | ||
| ({"basis_type": "pw"}, False), ({"wannier_method": 1}, False), ({"nspin": 2}, False), | ||
| ): | ||
| with self.subTest(overrides=overrides): | ||
| params = {"basis_type": "lcao", **overrides} | ||
| job.set_abacus_parameters(ecutwfc=20, nbands=14, **params) | ||
| self.assertEqual(job._spn_enabled(), expected) | ||
|
|
||
| def test_disabled_companion_rejected_before_nscf(self): | ||
| with tempfile.TemporaryDirectory() as scratch: | ||
| work = Path(scratch) | ||
| out = work / "OUT.ABACUS" | ||
| out.mkdir() | ||
| for ext in ("mmn", "amn", "eig", "spn"): | ||
| (out / f"wannier90.{ext}").write_text("previous NSCF run") | ||
|
|
||
| job = ABACUSWannier90(work_dir=work) | ||
| with patch("abacusw90.interface.runner.run_command") as launch: | ||
| for ext, disabled in (("mmn", 0), ("amn", " .FALSE. "), ("eig", False)): | ||
| flag = f"out_wannier_{ext}" | ||
| with self.subTest(flag=flag): | ||
| job.set_abacus_parameters( | ||
| ecutwfc=20, nbands=14, out_wannier_spn="YES", **{flag: disabled} | ||
| ) | ||
| with self.assertRaisesRegex(ValueError, flag): | ||
| job.step3_run_abacus() | ||
| launch.assert_not_called() | ||
| self.assertEqual(list(work.glob("wannier90.*")), []) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.