Skip to content
Chronum94Public

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Nondiagonal-supercell phonons with ASE

Implements Lloyd-Williams & Monserrat, PRB 92, 184301 (2015), doi:10.1103/PhysRevB.92.184301. The paper isn't included here (APS copyright). For a q-point (m1/n1, m2/n2, m3/n3), a commensurate supercell needs only lcm(n1, n2, n3) primitive cells, not n1·n2·n3. So an N×N×N grid needs supercells of at most N cells instead of N³. The supplementary material only has timing tables; the Fortran code it mentions is not in this folder.

from ndsc import phonons
ph = phonons(prim, (4, 4, 4), EMT())   # ASE Phonons object, force constants from IBZ-only runs
ph.acoustic(ph.C_avNav)                # ASE's acoustic sum rule
bs = ph.get_band_structure(prim.cell.bandpath(npoints=100))
dos = ph.get_dos(kpts=(20, 20, 20))

calc is a calculator, or a function atoms -> calculator called once per displaced structure. DFT needs the function (see DFT test).

Install

pip install -e .            # ase>=3.30, numpy, spglib
pip install -e .[examples]  # + matplotlib for the plot scripts
python ndsc.py              # self-check against ASE's diagonal Phonons (EMT, ~15 s)

Files

File Contents
ndsc.py Implementation (about 140 lines) and STRAINS. python ndsc.py runs every check against ASE's diagonal Phonons (about 15 s).
plot_bands.py python plot_bands.py [cu|cuag] [relax] writes <key>[_relaxed]_bands.png.
plot_strained.py Strained, atoms-relaxed CuAg and diamond Cu; writes strained_bands.png.
distort.py Follows the most unstable mode in the commensurate supercell; writes distorted_bands.png.
bench_speed.py Counted cost of diagonal vs non-diagonal force constants (EMT).
gamma_asr_demo.py Γ for CuAg from displacing Cu only, using the acoustic sum rule.
dft_check.py GPAW check, ours vs diagonal (2×2×2 q-grid): PYTHONPATH=$PWD mpiexec -n 8 gpaw python dft_check.py [cu|sic].
*.png Plots, described below.

Environment: Python 3.11, ASE 3.30.0b1 (a70333dbc, editable at ~/ase), spglib 2.7.0, GPAW 25.7.1b1 (MPI, 16 cores), EMT for the fast tests.

Decisions

Decision Why
Rely on ASE wherever it can do the job (make_supercell, minkowski_reduce, prep_symmetry, Phonons) As requested; keeps the code small (ndsc.py is about 140 lines).
spglib for IBZ reduction, over GPAW Symmetry.reduce Your choice. ASE has no IBZ reducer.
Γ-centred q-grid The paper's grids include Γ. ASE's even-N Monkhorst-Pack grid is shifted, which doubles the denominators and the supercell size.
Find S by scanning HNF matrices, not the paper's closed form (Eqs. 7–12) Correct by construction and easier to read. 37 ms/q at N = 48 is negligible next to any DFT call (benchmark). The closed form is kept in the appendix.
Exact Fraction arithmetic for commensurability No float tolerance needed in S·q ∈ ℤ³.
minkowski_reduce on S Shortest supercell vectors (paper Sec. III A): fewer k-points and a faster calculator.
Lattice-vector phases in D(q) (paper Eq. 13) D(q) is then periodic in q, so unfold can match q modulo G, and the result lines up with ASE's C_avNav.
Pass the result through ASE Phonons rather than write our own band/DOS code ASE already has the sum rule, symmetrising, bands, DOS, modes and minimum-image phase averaging.
Brute-force ±x, ±y, ±z displacements of every atom Minimal code. Symmetry-reduced displacements are the obvious speedup (below).
Tests: EMT, Cu/Ag fcc plus primitive and cubic cells; later zincblende CuAg and diamond Cu; 4 strain levels Fast. They cover multi-atom bases, two species, no inversion, and non-symmorphic groups.
Scope ended at D(q) on the IBZ, then extended to the full pipeline Your choices, made in that order.
Compare signed ω² in tests, not ω Noise in ω² near ω = 0 gets inflated by √.
Force constants compared as a relative difference (bound 1e-4) The residual is O(δ²) anharmonicity, which scales with the force constants themselves.
ASE update: stash, pull, stash pop Your choice; see repo housekeeping.
DFT: GPAW plane waves 350 eV, 6³ primitive k-grid, mapped exactly into every supercell Your settings: first k-density 6 (19³, rounded up to 20³), then cut to 6³ because 20³ was too slow (about 5 min per 8000-k calculation). The grid has to be even to contain q = ½. A per-cell "same density" grid would add meV-level sampling error.
Fresh calculator per displaced structure GPAW fixes its symmetry at the first calculation (SymmetryBrokenError otherwise).
Not added yet: symmetry-reduced displacements, n − 1 displacements at Γ, closed-form S Each is only worth adding for expensive (DFT) runs.

Pipeline (ndsc.phonons(prim, mesh, calc))

  1. Positions. Work on a copy whose scaled positions are exactly get_scaled_positions(wrap=True). That's ASE's convention for phases, and it avoids the wrap bug.
  2. ibz_qpoints. spglib get_ir_reciprocal_mesh on a Γ-centred grid. Returns the IBZ points, their weights, the full grid and the full-grid→IBZ map.
  3. supercell_matrix.
    • Convert q to Fractions and set n = lcm(denominators).
    • Scan the HNF matrices with determinant n (paper Eq. 5) and take the first S with S·q integer. The paper proves one exists.
    • Apply minkowski_reduce and update S ← op·S. Keep det S > 0 (right-handed).
  4. dynamical_matrix.
    • make_supercell(prim, S).
    • Displace each primitive atom by ±δ along x, y and z.
    • D(q)[a, b] = Σ over the images b′ of b of C(a, b′)·e^{−2πi q·R(b′)}/√(m_a m_b).
    • This is exact because q is commensurate with the supercell, and wrapping atoms into the supercell doesn't change it (e^{iq·L} = 1 for supercell vectors L).
  5. unfold. Maps D(q) from each IBZ point onto the whole grid.
    • D(Sq)[k′, l′] = S·D(q)[k, l]·Sᵀ·exp(−2πi Sq·(L_l − L_k)), where L_k = r·f_k + t − f_{k′} is the lattice vector the operation adds to atom k.
    • Time reversal: D(−q) = D(q)*.
    • The operations come from prep_symmetry(symprec=1e-5), the same tolerance spglib's IBZ step uses.
  6. Fourier transform. On ASE's own lattice_vectors_array, then un-mass-scale and reshape into Phonons.C_avNav (with use_mean_minimum_images=True).

Who does what

Step Who
q-grid → IBZ points + map spglib. ASE's ase.dft.kpoints bz2ibz only interpolates scalar values.
Symmetry operations + atom permutation ASE ase.spacegroup.symmetrize.prep_symmetry
Supercell building / vector reduction ASE make_supercell, minkowski_reduce
IBZ → full grid for D(q) ours (unfold); nothing in ASE rotates matrices
Fourier transform to C(R) ours (one line)
Acoustic sum rule, symmetrising, bands, DOS, modes ASE Phonons

Verification (python ndsc.py)

Structures and grids:

  • fcc Cu 4×4×4 and 4×3×2; fcc Ag 3×3×3.
  • Conventional cubic Cu 2×2×2 and Ag 3×3×3.
  • Zincblende CuAg 4×4×4 and 3×3×3: two species, no inversion.
  • Diamond Cu 4×4×4: non-symmorphic, so it tests t in unfold.

Each is run under 4 strains of 2–4 % (STRAINS): none (cubic), orthorhombic, monoclinic and triclinic. The space groups change as follows:

  • Fm-3m → Fmmm → C2/m → P-1
  • F-43m → F222 → C2 → P1
  • Fd-3m → Fddd → C2/c → P-1

Atoms-only LBFGS relaxation (fmax 1e-5) runs in each strained cell first. Atoms move only where the strain leaves a site free:

Structure Strain Starting max force Largest displacement
CuAg zincblende C2 0.08 eV/Å 0.1 Å
CuAg zincblende P1 0.1 eV/Å 0.3 Å
Diamond Cu C2/c 0.04 eV/Å 0.05 Å
Diamond Cu P-1 0.05 eV/Å 0.1 Å

Every space group survives the relaxation.

Check What it catches Worst case (32 cases)
det S = lcm(nᵢ) ≤ lcm(mesh) the supercell-size claim holds: 4 vs 64 cells on 4×4×4; 12 vs 24 on 4×3×2
Star check: ASE's ω over the full grid is constant within each spglib star a wrongly detected symmetry ≤ 1e-8 eV
Force constants vs ASE's diagonal reference (raw: no sum rule, no symmetrising) D(q), unfolding, Fourier transform 9e-5 relative (CuAg); 5e-6 (fcc)
ω² along a 60-point path (off-grid) interpolation ≤ 2e-8 eV²
Regression: an atom at fractional −8e-17 vs 0 the wrap bug ≤ 1e-6 eV (the bug gives about 1e-2)

Findings / bugs

  1. Reciprocal-vector transpose (ours, fixed). cell.reciprocal() returns rows, so Cartesian q is q @ B, not B @ q. The fcc and cubic cell matrices are symmetric, so this only showed up under strain: up to 5e-4 eV off, independent of δ.
  2. The residual is O(δ²) anharmonicity. Halving δ cuts it 4×. For Cu with δ = 0.02 / 0.01 / 0.005 Å, the largest |Δω| is 0.86 / 0.22 / 0.054 µeV. Displacing an atom also moves all its periodic images, and supercells of different shape place those images differently. ΔC is a few real-space terms, so Δω(q) is a short Fourier series and therefore smooth. The difference is 10–30× larger for CuAg and diamond Cu, which are unstable and strongly anharmonic in EMT.
  3. Δω spikes appear only where a branch crosses ω = 0: √ amplifies the difference in ω². It's a plotting artefact, not a method error.
  4. ASE Phonons wrap bug (upstream; worked around; issue draft). After the cell+atoms relaxation of CuAg, Cu sat at fractional (−8.5e-17, −7.1e-17, 6.8e-17).
    • Phonons.run() builds the supercell from raw coordinates, but _get_atom2atom_vectors computes phases from get_scaled_positions(wrap=True).
    • That calls x % 1, which turns −8e-17 into 0.9999999999999999: one lattice vector away.
    • Result: correct on the supercell grid, wrong between grid points (16 meV for CuAg). ASE's own diagonal reference is affected too.
    • Atoms.wrap() doesn't help: its 1e-7 buffer leaves −8e-17 alone.
    • −1e-17 doesn't trigger it, because −1e-17 % 1 rounds to exactly 1.0. That hid the bug from my first probe.
    • The proposed one-line upstream fix (wrap=False), applied at runtime, brings the MWE from 4.1e-3 to 5.5e-15 eV.
  5. Relaxed zincblende CuAg (EMT) is a saddle point. Cell relaxation under F-43m gives a = 5.880 Å (conventional). Both TA branches are imaginary across the zone, down to about −5.7i meV; the optical modes are at 18–20 meV. Unstrained diamond Cu is stable; every strained version is not.
  6. Γ has optical modes whenever there are 2+ atoms per cell. Only for 1-atom cells are the Γ displacements redundant (a pure translation, zero force). In general the acoustic sum rule saves one atom's displacements at Γ (below).

Plots (diagonal reference wide/orange, ours dashed/blue)

Plot Largest |Δω| Notes
cu_bands.png (4×4×4) 0.22 µeV smooth δ² curve; zero at Γ (acoustic sum rule)
cuag_bands.png (a = 6.28 Å, unrelaxed) 15.9 µeV spikes at ω = 0 crossings, about 1 µeV elsewhere
cuag_relaxed_bands.png 9.3 µeV after the wrap fix; it was 12.5 meV before
strained_bands.png (CuAg + diamond Cu × 4 strains, atoms relaxed) 0.8–48 µeV each lattice uses its own path; vertical jumps are path breaks
distorted_bands.png (after following an instability, 2×2×2) ≤ 31 µeV see below

Following the instabilities (distort.py)

Method: strained parent with atoms relaxed → most unstable ω on the 4×4×4 grid → S = supercell_matrix(q) → rattle 0.05 Å → atoms-only LBFGS → phonons on a 2×2×2 grid.

  • Rattling within the primitive cell gives ΔE = 0 wherever the instabilities are at the zone boundary, because primitive-cell distortions are q = 0 only. The exception is CuAg in C2 (−4.5 meV/atom), which also has an unstable Γ mode.
  • In the commensurate supercell (|S| = 2 or 4), the structures drop 146–474 meV/atom: the 4-coordinated cells collapse in EMT.
  • Afterwards: both triclinic cells are nearly stable (lowest modes −0.06 and −0.83 meV); the others still go down to −8 meV. Following one mode once isn't enough to reach a minimum.

Speed: diagonal vs non-diagonal (bench_speed.py, EMT)

Every force call is counted (N = atoms per call).

system grid diagonal: calls × max N non-diagonal: calls × max N EMT wall-time speedup ΣN² speedup ΣN³ speedup
Cu fcc 2×2×2 7 × 8 18 × 2 0.2 8 35
Cu fcc 4×4×4 7 × 64 48 × 4 0.1 54 908
Cu fcc 6×6×6 7 × 216 96 × 6 0.1 138 5207
Cu fcc 8×8×8 7 × 512 174 × 8 0.1 213 14121
CuAg zincblende 2×2×2 13 × 16 36 × 4 0.8 8 33
CuAg zincblende 4×4×4 13 × 128 96 × 8 0.7 50 843
CuAg zincblende 6×6×6 13 × 432 192 × 12 0.7 128 4835

How to read the speedup columns:

  • EMT wall time: the non-diagonal method is slower. EMT is O(N) and takes milliseconds, so per-call overhead dominates, and the non-diagonal method makes 7–25× more calls (6·nat per IBZ point, no symmetry reduction).
  • ΣN²: plane-wave DFT at fixed k-point density (O(N³) per k-point, about 1/N k-points). This is the realistic DFT estimate.
  • ΣN³: the large-cell limit; an upper bound.

The paper measured 15–17× for diamond at 4×4×4 and 6×6×6 (its Table I). Its diagonal side used several smaller diagonal supercells, and its non-diagonal supercells lose symmetry, which costs extra displacements.

DFT test (GPAW, dft_check.py)

PYTHONPATH=$PWD mpiexec -n 8 gpaw python dft_check.py [cu|sic], with output in dft/<system>/ (not in git). Both systems use a 2×2×2 q-grid (IBZ: Γ, X, L) and PBE. Every supercell gets the primitive Γ-centred k-grid mapped exactly into its own basis (k_s = S·k_p mod 1, integer arithmetic), so both methods sample identical points. The grid must be even so that it contains q = ½. Use 8 MPI ranks: the machine has 8 physical cores, and 16 ranks (hyperthreads) was 25–40% slower per calculation.

Cu (fcc) SiC (zincblende)
Settings a = 3.61 Å, PW 350 eV, Fermi-Dirac 0.1 eV, 6³ k-points a = 4.38 Å, PW 400 eV, Fermi-Dirac 0.01 eV, 4³ k-points
Non-diagonal 18 calculations, 1–2 atoms 36 calculations, 2–4 atoms: 17.5 min
Diagonal 2×2×2 7 calculations, 8 atoms 13 calculations, 16 atoms: undisplaced 6.2 min, then about 10.3 min per displacement, so about 130 min projected (about 7.5×)
Status Stopped to free the cores for SiC: 12 of 18 non-diagonal calculations done on 8 ranks. The ASE cache in dft/cu/diag lets the reference resume. Running. Frequency comparison pending.

Both runs converge to density=1e-6, forces=1e-5. The SiC speedup matches the ΣN² estimate (6–8× for 2×2×2). Cu's 6³ grid and SiC's 4³ grid are not k-converged, but both methods see identical sampling, so the comparison is still exact. SiC is polar: both methods miss the LO–TO splitting at Γ equally.

Gotchas hit and fixed:

Symptom Cause Fix
SymmetryBrokenError on the 2nd displacement GPAW fixes its symmetry at the first calculation Fresh calculator per displaced structure: calc may be a function (ndsc.py); FreshCalcPhonons overrides Phonons.__call__ for the reference
Duplicate kpoints detected float x % 1 leaves near-duplicates (1.1 % 1 != 0.1): 6880 points instead of 4000 Map the grid in integer indices
ModuleNotFoundError: ndsc under gpaw python it doesn't add the script's directory to the path PYTHONPATH=$PWD
Phonons cache split across MPI ranks tempfile gives each rank its own directory Fixed cache name dft/<system>/diag
pkill -f <pattern> killed my own shell the pattern also appeared in the shell's own command line pgrep -f 'name[.]py' | xargs -r kill, with nothing else matching in the same command

Γ: n − 1 displacements via the acoustic sum rule (gamma_asr_demo.py)

At Γ, a row of force constants (displace atom a) gives the matching column by symmetry (C_ba = C_abᵀ). The acoustic sum rule (Σ_a C_ab = 0) then gives the last diagonal block. So with n atoms, displacing n − 1 is enough. For CuAg, displacing Cu alone (6 calculations instead of 12) gives:

Cell ω(Γ), meV max |ΔD| max |Δω|
Relaxed cubic F-43m 0 ×3, 20.0135 ×3 2e-15 2.5e-6 meV
Monoclinic C2, atoms relaxed −5.18, −4.07, −3.94, ≈0 ×3 6e-7 2.3e-6 meV

The monoclinic case has a general (non-diagonal) Cu–Ag block, so the reconstruction doesn't depend on high symmetry. Not yet in ndsc.py (about 5 lines). It doesn't apply at q ≠ 0, where no sum rule constrains a single D(q).

Supercell matrix: HNF scan vs closed form (Eqs. 7–12)

Both were tested on 50 random q-points per N, and both always gave a commensurate S with det = lcm.

N scan (ms/q) closed form (ms/q)
4 0.42 0.05
12 2.7 0.04
24 11.5 0.06
48 37 0.08

Fewer displacements (not implemented)

Three things cut the number of displacements:

  • Displace only one atom per set of symmetry-equivalent atoms.
  • Generate the other directions with the operations that leave the displaced atom in place, until they span all three: Φ(Rκ, Rλ) = R Φ(κ, λ) Rᵀ.
  • Skip −u when an operation maps u to −u.

Phonopy does this, and accepts non-diagonal supercell matrices. A non-diagonal supercell keeps only the operations that also preserve the superlattice. Calculations per supercell for Cu:

Cell Brute force Diagonal, with symmetry Non-diagonal per IBZ q, with symmetry
1-atom fcc, 4×4×4 6 1 1, 1, 1, 3, 3, 3, 3, 2
4-atom cubic, 2×2×2 24 1 1, 2, 3, 1

Overall it's still about 17 calculations on ≤ 4-atom cells against 1 on a 64-atom cell.

Repo housekeeping

ASE was updated to master a70333dbc with stash → pull → pop. ~/ase/ase/gui/ui.py still has 3 unresolved conflict blocks: upstream rewrote the canvas drawing to reuse items, overlapping the local edits. Until they're resolved, ase.gui won't import. The original edits are saved in git stash ("gui-wip before pull 2026-10-05"). gui.py, images.py and view.py were restored cleanly.


ASE issue draft

Not posted. Drafted 2026-10-05 against ASE 3.30.0b1 (a70333dbc).

Title: Phonons: wrong band structure when a scaled position is a tiny negative number

Phonons.run() builds the supercell from raw positions (atoms * supercell), but _get_atom2atom_vectors takes the phases from get_scaled_positions(wrap=True). There, -8e-17 % 1 == 0.9999999999999999, so the atom is assigned to the next cell, and the force constants and phases disagree by a lattice vector. Frequencies on the supercell's q-grid are unaffected; everything between grid points is wrong. Such coordinates are common after a relaxation; the error was 16 meV for a 2-atom cell. It only matters with more than one atom per cell (for a single atom the offsets cancel). Atoms.wrap() doesn't help, because its 1e-7 buffer leaves −8e-17 unchanged.

import numpy as np
from ase.build import bulk
from ase.calculators.emt import EMT
from ase.phonons import Phonons

def omega(atoms, name):
    ph = Phonons(atoms, EMT(), supercell=(2, 2, 2), name=name,
                 use_mean_minimum_images=True)
    ph.run()
    ph.read(acoustic=False, symmetrize=0)
    return ph.band_structure(np.array([[0.25, 0, 0]]), verbose=False)

atoms = bulk('Cu', cubic=True)
nudged = atoms.copy()
spos = nudged.get_scaled_positions()
spos[0] = [-8e-17, 0, 0]  # e.g. left over after a relaxation
nudged.set_scaled_positions(spos)

print(omega(atoms, 'ref') - omega(nudged, 'nudged'))  # expected ~0

Output: differences up to 4.1e-3 eV, with use_mean_minimum_images either True or False.

Fix: in _get_atom2atom_vectors, use get_scaled_positions(wrap=False), so the phases come from the same positions run() uses. With that change, the MWE difference drops to 5.5e-15 eV in both modes.


Appendix: closed-form supercell matrix (paper Eqs. 7–12)

Benchmarked above, not used. Returns the upper-triangular HNF (before Minkowski reduction).

from fractions import Fraction as F
from math import gcd
import numpy as np

def closed(qf):  # qf: 3 Fractions
    qf = [f % 1 for f in qf]                       # paper assumes 0 <= k < 1
    (m1, m2, m3), (n1, n2, n3) = zip(*((f.numerator, f.denominator) for f in qf))
    g12, g23, g31, g123 = gcd(n1, n2), gcd(n2, n3), gcd(n3, n1), gcd(n1, n2, n3)
    p = next(p for p in range(g23) if (m2 + p * m3) % g23 == 0)                     # Eq. 10
    h = g12 // g123
    q = next(q for q in range(h) if ((g23 // g123) * m1 + q * (g31 // g123) * m2) % h == 0)
    S11, S12 = g123 * n1 // (g12 * g31), q * g123 * n2 // (g12 * g23)
    r = next(r for r in range(g31 * g23 // g123)                                      # Eq. 12
             if (S11 * qf[0] + S12 * qf[1] + F(r * g123 * n3 // (g31 * g23)) * qf[2]).denominator == 1)
    return np.array([[S11, S12, r * g123 * n3 // (g31 * g23)],
                     [0, n2 // g23, p * n3 // g23], [0, 0, n3]])

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages