Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/advanced/interface/Wannier90.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,16 @@ To construct the MLWFs using the wave functions of ABACUS generally requires fou
out_wannier_unk 0
```

There are seven interface-related parameters in the `INPUT` file:
The interface-related parameters in the `INPUT` file include:

- [towannier90](../input_files/input-main.md#towannier90): `1`, generate files for wannier90 code; `0`, do not generate.
- [nnkpfile](../input_files/input-main.md#nnkpfile) : the name of the file generated by running "wannier90 -pp ...".
- [wannier_spin](../input_files/input-main.md#wannier_spin): If you use nspin=2, `up`: calculate the Wannier functions for the spin up components ; `down`: calculate the Wannier functions spin down components.
- [out_wannier_mmn](../input_files/input-main.md#out_wannier_mmn): control whether to output the "*.mmn" file.
- [out_wannier_amn](../input_files/input-main.md#out_wannier_amn): control whether to output the "*.amn" file.
- [out_wannier_eig](../input_files/input-main.md#out_wannier_eig): control whether to output the "*.eig" file.
- [out_wannier_spn](../input_files/input-main.md#out_wannier_spn) writes formatted Pauli spin matrices to `<seedname>.spn`. It defaults to `1` for direct spinor LCAO Wannier90 exports (`towannier90=1`, `calculation=nscf`, `basis_type=lcao`, `wannier_method=2`, `nspin=4`) and `0` otherwise. Set it to `0` to skip spin output. Set `spinors = true` and `spn_formatted = true` in the Wannier90 input and place the file alongside `<seedname>.chk` for `postw90`.
The `abacusw90` Python workflow requires `out_wannier_mmn`, `out_wannier_amn` and `out_wannier_eig` to be enabled (their defaults) so that all four files come from the same NSCF run.
- [out_wannier_unk](../input_files/input-main.md#out_wannier_unk): control whether to output the "UNK.*" file.
- [out_wannier_wvfn_formatted](../input_files/input-main.md#out_wannier_wvfn_formatted): control what format of the Wannier function file to output, `true`: output the formatted text file; `false`: output the binary file. Note that the `wvfn_formatted` option in `*.win` file (input file of Wannier90) has to be set accordingly with this option.

Expand Down
46 changes: 40 additions & 6 deletions interfaces/Wannier90_interface/abacusw90/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ def __post_init__(self):
self.work_dir = Path(self.work_dir)
self.scf_dir = Path(self.scf_dir)

def _output_enabled(self, name: str, default: bool) -> bool:
params = self._abacus_input.params if self._abacus_input else {}
return str(params.get(name, default)).strip().lower() in (
"1", "true", "t", "yes", "y", "on", ".true."
)

def _spn_enabled(self) -> bool:
params = self._abacus_input.params if self._abacus_input else {}
if "out_wannier_spn" in params:
return self._output_enabled("out_wannier_spn", default=False)
return (
self._output_enabled("towannier90", default=False)
and str(params.get("calculation", "")).strip() == "nscf"
and str(params.get("basis_type", "")).strip() == "lcao"
and int(params.get("wannier_method", 1)) == 2
and int(params.get("nspin", 1)) == 4
)

# ----------------------------------------------------------------
# Public API: Configuration
# ----------------------------------------------------------------
Expand Down Expand Up @@ -159,6 +177,7 @@ def step0_run_scf(
"out_wannier_mmn",
"out_wannier_amn",
"out_wannier_eig",
"out_wannier_spn",
"out_wannier_unk",
}
scf_params = {
Expand Down Expand Up @@ -322,6 +341,9 @@ def step1_generate_wannier_win(self):
self.work_dir.mkdir(parents=True, exist_ok=True)
win_file = self.work_dir / "wannier90.win"
self._wannier_input.write(win_file, self.structure)
if self._spn_enabled():
with win_file.open("a") as stream:
stream.write("\nspn_formatted = true\n")
print(f" Written: {win_file}")

cmd = f"{self.wannier90_exe} -pp wannier90"
Expand Down Expand Up @@ -373,18 +395,30 @@ def step2_prepare_abacus_input(self):
self._copy_dep_files(self.work_dir)

def step3_run_abacus(self):
"""Run ABACUS to generate mmn, amn, eig."""
"""Run NSCF and collect the requested Wannier90 files."""
out_dir = self.work_dir / "OUT.ABACUS"
extensions = ["mmn", "amn", "eig"]
search_dirs = [self.work_dir, out_dir]
if self._spn_enabled():
# All four files must use the band gauge of the same NSCF run.
for ext in extensions:
flag = f"out_wannier_{ext}"
if not self._output_enabled(flag, default=True):
raise ValueError(
f"out_wannier_spn requires {flag} to be enabled in this workflow"
)
extensions.append("spn")
search_dirs = [out_dir]

print(">>> Step 3: Running ABACUS to generate overlap matrices...")
cmd = self.abacus_exe
log_file = self.work_dir / "abacus_nscf.log"
runner.run_command(
cmd, cwd=str(self.work_dir), log_file=str(log_file), label="abacus_nscf"
)

out_dir = self.work_dir / "OUT.ABACUS"
search_dirs = [self.work_dir, out_dir]

for fname in ["wannier90.mmn", "wannier90.amn", "wannier90.eig"]:
for ext in extensions:
fname = f"wannier90.{ext}"
found = False
for d in search_dirs:
src = d / fname
Expand All @@ -397,7 +431,7 @@ def step3_run_abacus(self):
break
if not found:
runner.check_file_exists(
self.work_dir / fname,
search_dirs[0] / fname,
hint=f"ABACUS did not produce {fname}. Check abacus_nscf.log.",
)
print(" ABACUS calculation finished. Matrix elements generated.")
Expand Down
125 changes: 125 additions & 0 deletions interfaces/Wannier90_interface/tests/check_wannier_spn.py
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."""
Comment thread
Stardust0831 marked this conversation as resolved.
Resolved

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:])
41 changes: 41 additions & 0 deletions interfaces/Wannier90_interface/tests/test_interface.py
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.*")), [])
4 changes: 4 additions & 0 deletions source/source_io/module_ctrl/ctrl_scf_lcao.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,10 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell,
orb);

wan.calculate(ucell, gd, pelec->ekb, kv, *psi, &pv);
if (inp.out_wannier_spn)
{
wan.write_spn(*psi, *p_hamilt->getSR(), kv, global_out_dir, ofs_running);
}
}
std::cout << FmtCore::format(" >> Finish %s.\n * * * * * *\n", "Wave function to Wannier90");
}
Expand Down
1 change: 1 addition & 0 deletions source/source_io/module_parameter/input_parameter.h
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,7 @@ struct Input_para
bool out_wannier_amn = true; ///< output .amn file or not
bool out_wannier_unk = false; ///< output UNK. file or not
bool out_wannier_eig = true; ///< output .eig file or not
bool out_wannier_spn = false; ///< output formatted spin matrices for Wannier90
bool out_wannier_wvfn_formatted = true; ///< output UNK. file in text format or in binary format

// ============== #Parameters (13.Model) ===========================
Expand Down
26 changes: 26 additions & 0 deletions source/source_io/module_parameter/read_inp_postproc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,32 @@ void ReadInput::item_postprocess()
read_sync_bool(input.out_wannier_eig);
this->add_item(item);
}
{
Input_Item item("out_wannier_spn");
item.annotation = "write Wannier90 spin matrices";
item.category = "Berry phase and wannier90 interface";
item.type = "Boolean";
item.description = "Write <seedname>.spn with the x, y, z Pauli matrix elements. "
"Set spinors=true and spn_formatted=true in the Wannier90 input.";
item.default_value = "1 when the output requirements are met, 0 otherwise";
item.domain.add_requirement("out_wannier_spn==true",
"towannier90==true and calculation==nscf and basis_type==lcao "
"and wannier_method==2 and nspin==4");
read_sync_bool(input.out_wannier_spn);
item.reset_value = [this](const Input_Item& item, Parameter& para) {
if (!item.is_read())
{
// The basis_type reset has already mapped lcao_in_pw to lcao for Wannier90.
const bool lcao = std::any_of(readvalue_items.begin(), readvalue_items.end(), [](const Input_Item* input) {
return input->label == "basis_type" && input->str_values.front() == "lcao";
Comment thread
Stardust0831 marked this conversation as resolved.
Resolved
});
const auto& inp = para.inp;
para.input.out_wannier_spn = inp.towannier90 && inp.calculation == "nscf" && lcao
&& inp.wannier_method == 2 && inp.nspin == 4;
}
};
this->add_item(item);
}
{
Input_Item item("out_wannier_unk");
item.annotation = "output UNK. file or not";
Expand Down
3 changes: 3 additions & 0 deletions source/source_io/module_wannier/to_w90_lcao.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ class toW90_LCAO : public toW90

void cal_Amn(const UnitCell& ucell, const K_Vectors& kv, const psi::Psi<std::complex<double>>& psi);
void cal_Mmn(const UnitCell& ucell, const K_Vectors& kv, const psi::Psi<std::complex<double>>& psi);
template <typename TK, typename TR>
void write_spn(const psi::Psi<TK>& psi, const hamilt::HContainer<TR>& sr, const K_Vectors& kv,
const std::string& out_dir, std::ostream& log) const;
void out_unk(const psi::Psi<std::complex<double>>& psi);

protected:
Expand Down
Loading
Loading