Skip to content

Commit 48b2fdd

Browse files
Mancn-XuMancnpre-commit-ci[bot]njzjz-bot
authored
Enhance poscar_scale function (/data/gen.py)to detect Selective dynamics (#1439)
## Summary This pull request updates the `poscar_scale` function in the `gen.py` file to enhance its functionality by accurately detecting the presence of "Selective dynamics" in POSCAR files. The update ensures that the coordinate type determination is correctly handled based on whether the "Selective dynamics" line is present, improving the function's reliability and correctness in handling various POSCAR file configurations. ## Changes Made - Added a check to determine the presence of "Selective dynamics" in the POSCAR file. - Adjusted the coordinate type line index based on the presence of "Selective dynamics" to ensure correct parsing. - Ensured the coordinate type detection logic works accurately for both "Direct" and "Cartesian" coordinates following the presence of "Selective dynamics". - Included clear and concise comments to improve code readability and maintenance. ## Impact This enhancement allows users to work with a wider variety of POSCAR files, especially those that include the "Selective dynamics" setting, without manually adjusting the script for different file formats. It ensures that the `poscar_scale` function is more adaptable and accurate, providing a robust solution for scaling atomic positions in POSCAR files. ## Additional Notes This update assumes that the "Selective dynamics" line, if present, is directly above the coordinate type line in POSCAR files, which is the standard format. Users should ensure that their POSCAR files follow this format for the script to function correctly. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * POSCAR scaling now handles files with Selective Dynamics and preserves trailing coordinate flags. * Cartesian coordinates marked with `C`, `c`, `K`, or `k` are supported, alongside Direct coordinates. * Negative scale factors are interpreted as target volumes and converted to equivalent positive scaling factors. * Zero-volume lattice vectors and unrecognized coordinate styles now produce clear errors identifying the relevant line. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Mancn <mancn@MancndeMacBook-Pro.local> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: njzjz-bot <njzjz.bot@gmail.com>
1 parent 8de9497 commit 48b2fdd

2 files changed

Lines changed: 157 additions & 9 deletions

File tree

‎dpgen/data/gen.py‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,8 @@ def poscar_scale_direct(str_in, scale):
215215
return lines
216216

217217

218-
def poscar_scale_cartesian(str_in, scale):
218+
def poscar_scale_cartesian(str_in, scale, coordinate_start=8):
219+
"""Scale Cartesian coordinates while preserving Selective Dynamics flags."""
219220
lines = str_in.copy()
220221
numb_atoms = poscar_natoms(lines)
221222
# scale box
@@ -225,23 +226,48 @@ def poscar_scale_cartesian(str_in, scale):
225226
boxv = np.array(boxv) * scale
226227
lines[ii] = f"{boxv[0]:.16e} {boxv[1]:.16e} {boxv[2]:.16e}\n"
227228
# scale coord
228-
for ii in range(8, 8 + numb_atoms):
229-
cl = lines[ii].split()
230-
cv = [float(ii) for ii in cl]
229+
for ii in range(coordinate_start, coordinate_start + numb_atoms):
230+
fields = lines[ii].split()
231+
cv = [float(value) for value in fields[:3]]
231232
cv = np.array(cv) * scale
232-
lines[ii] = f"{cv[0]:.16e} {cv[1]:.16e} {cv[2]:.16e}\n"
233+
suffix = f" {' '.join(fields[3:])}" if len(fields) > 3 else ""
234+
lines[ii] = f"{cv[0]:.16e} {cv[1]:.16e} {cv[2]:.16e}{suffix}\n"
233235
return lines
234236

235237

236238
def poscar_scale(poscar_in, poscar_out, scale):
237239
with open(poscar_in) as fin:
238240
lines = list(fin)
239-
if "D" == lines[7][0] or "d" == lines[7][0]:
241+
242+
# VASP interprets a negative line-2 factor as the target cell volume;
243+
# convert it to the equivalent positive linear scaling factor first so both
244+
# Direct and Cartesian scaling scale volume by scale**3 consistently.
245+
pscale = float(lines[1])
246+
if pscale < 0:
247+
cell = np.array([[float(x) for x in lines[ii].split()] for ii in range(2, 5)])
248+
cell_vol = abs(np.linalg.det(cell))
249+
if cell_vol <= 0:
250+
raise RuntimeError("POSCAR lattice vectors have zero volume")
251+
lines[1] = f"{(abs(pscale) / cell_vol) ** (1.0 / 3.0):.16e}\n"
252+
253+
# Determine if "Selective dynamics" is present
254+
if lines[7].strip().lower().startswith("s"):
255+
coord_type_line = 8 # If present, coordinates type is on line 9
256+
else:
257+
coord_type_line = 7 # If not, coordinates type is on line 8
258+
259+
# Process according to the coordinate type (VASP accepts C/c/K/k for Cartesian)
260+
coord_type = lines[coord_type_line].strip().lower()
261+
if coord_type.startswith("d"):
240262
lines = poscar_scale_direct(lines, scale)
241-
elif "C" == lines[7][0] or "c" == lines[7][0]:
242-
lines = poscar_scale_cartesian(lines, scale)
263+
elif coord_type.startswith(("c", "k")):
264+
lines = poscar_scale_cartesian(lines, scale, coord_type_line + 1)
243265
else:
244-
raise RuntimeError(f"Unknow poscar style at line 7: {lines[7]}")
266+
raise RuntimeError(
267+
f"Unknown poscar style at line {coord_type_line + 1}: {lines[coord_type_line]}"
268+
)
269+
270+
# Write scaled positions back to output file
245271
with open(poscar_out, "w") as fout:
246272
fout.write("".join(lines))
247273

‎tests/data/test_poscar_scale.py‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import tempfile
2+
import unittest
3+
from pathlib import Path
4+
5+
from dpgen.data.gen import poscar_scale
6+
7+
8+
class TestPoscarScale(unittest.TestCase):
9+
def _run_scale(self, poscar: str, scale: float) -> list[str]:
10+
with tempfile.TemporaryDirectory() as tmpdir:
11+
source = Path(tmpdir) / "POSCAR.in"
12+
target = Path(tmpdir) / "POSCAR.out"
13+
source.write_text(poscar)
14+
poscar_scale(source, target, scale)
15+
return target.read_text().splitlines()
16+
17+
def test_selective_cartesian_coordinates_and_flags(self):
18+
"""Selective Dynamics moves the coordinate start and preserves T/F flags."""
19+
poscar = """Mg
20+
1.0
21+
1 0 0
22+
0 1 0
23+
0 0 1
24+
Mg
25+
1
26+
Selective dynamics
27+
Cartesian
28+
0.25 0.50 0.75 T F T
29+
"""
30+
scaled = self._run_scale(poscar, 2.0)
31+
self.assertEqual(scaled[8], "Cartesian")
32+
self.assertEqual(
33+
scaled[9],
34+
"5.0000000000000000e-01 1.0000000000000000e+00 "
35+
"1.5000000000000000e+00 T F T",
36+
)
37+
38+
def test_selective_direct_scales_lattice_factor(self):
39+
"""Direct coordinates scale via line 2 while leaving Selective Dynamics intact."""
40+
poscar = """Mg
41+
1.0
42+
1 0 0
43+
0 1 0
44+
0 0 1
45+
Mg
46+
1
47+
Selective dynamics
48+
direct
49+
0.25 0.50 0.75 T F T
50+
"""
51+
scaled = self._run_scale(poscar, 1.5)
52+
self.assertAlmostEqual(float(scaled[1]), 1.5)
53+
self.assertEqual(scaled[9], "0.25 0.50 0.75 T F T")
54+
55+
def test_cartesian_k_alias_and_whitespace(self):
56+
"""VASP accepts leading whitespace and 'K'/'k' as Cartesian."""
57+
poscar = """Mg
58+
1.0
59+
1 0 0
60+
0 1 0
61+
0 0 1
62+
Mg
63+
1
64+
Kartesian
65+
0.25 0.50 0.75
66+
"""
67+
scaled = self._run_scale(poscar, 2.0)
68+
self.assertEqual(
69+
scaled[8],
70+
"5.0000000000000000e-01 1.0000000000000000e+00 1.5000000000000000e+00",
71+
)
72+
73+
def test_unknown_coordinate_style_raises(self):
74+
poscar = """Mg
75+
1.0
76+
1 0 0
77+
0 1 0
78+
0 0 1
79+
Mg
80+
1
81+
Selective dynamics
82+
Invalid
83+
0.25 0.50 0.75 T F T
84+
"""
85+
with self.assertRaisesRegex(RuntimeError, "Unknown poscar style at line 9"):
86+
self._run_scale(poscar, 2.0)
87+
88+
def test_negative_target_volume_factor_scales_consistently(self):
89+
"""Negative line-2 target volume scales identically for Direct and Cartesian."""
90+
for selective in (False, True):
91+
sel_line = "Selective dynamics\n" if selective else ""
92+
flags = " T F T" if selective else ""
93+
for style in ("Direct", "Cartesian"):
94+
with self.subTest(selective=selective, style=style):
95+
poscar = (
96+
"Mg\n"
97+
"-8.0\n"
98+
"1 0 0\n"
99+
"0 1 0\n"
100+
"0 0 1\n"
101+
"Mg\n"
102+
"1\n"
103+
f"{sel_line}"
104+
f"{style}\n"
105+
f"0.25 0.50 0.75{flags}\n"
106+
)
107+
scaled = self._run_scale(poscar, 2.0)
108+
factor = float(scaled[1])
109+
self.assertGreater(factor, 0.0)
110+
cell = [
111+
[float(x) for x in scaled[ii].split()] for ii in range(2, 5)
112+
]
113+
# Volume must scale from 8 to 8 * 2^3 = 64 in all cases.
114+
vol = (factor**3) * abs(cell[0][0] * cell[1][1] * cell[2][2])
115+
self.assertAlmostEqual(vol, 64.0)
116+
coord_idx = 9 if selective else 8
117+
if selective:
118+
self.assertTrue(scaled[coord_idx].endswith("T F T"))
119+
120+
121+
if __name__ == "__main__":
122+
unittest.main()

0 commit comments

Comments
 (0)