Skip to content

Commit bf2f421

Browse files
authored
Convert kpts in Kpoints to Sequence[tuple] and set it as property (#3758)
* convert some types * make real tuple * remove unnecessary `int` before `math.floor/ceil` * Revert remove unnecessary int to avoid diff pollute This reverts commit f8f43a2. * fix some tests * fix more tests * relocate type Vector3D Matrix3D SitePropsType * fix some Kpoint types * fix some type * relocate dunder methods to the head * fix some type errors * revert unneeded cast to tuple * pre-commit auto-fixes * revert unneeded cast to tuple * revert unneeded cast to tuple * pre-commit auto-fixes * use Union over | * remove unnecessary wrapping * fix some types * fix direct float str to int conversion * use float for Kpoint * fix type * increase msg verbosity * fix types * remove debug print * add missing types * handle nparray * fix/suppress mypy error * change kpt weight to float in doc * add type for typealias * fix typealias import * remove type annotation for types * add unit test for property kpts
1 parent e04444e commit bf2f421

File tree

16 files changed

+310
-188
lines changed

16 files changed

+310
-188
lines changed

pymatgen/core/interface.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
from numpy.typing import ArrayLike
3030
from typing_extensions import Self
3131

32-
from pymatgen.core.trajectory import Vector3D
33-
from pymatgen.util.typing import CompositionLike
32+
from pymatgen.util.typing import CompositionLike, Vector3D
3433

3534
# This module implements representations of grain boundaries, as well as
3635
# algorithms for generating them.

pymatgen/core/lattice.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@
2525
from numpy.typing import ArrayLike
2626
from typing_extensions import Self
2727

28-
from pymatgen.core.trajectory import Vector3D
29-
from pymatgen.util.typing import PbcLike
28+
from pymatgen.util.typing import PbcLike, Vector3D
3029

3130
__author__ = "Shyue Ping Ong, Michael Kocher"
3231
__copyright__ = "Copyright 2011, The Materials Project"

pymatgen/core/trajectory.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,9 @@
66

77
import itertools
88
import warnings
9-
from collections.abc import Iterator, Sequence
109
from fnmatch import fnmatch
1110
from pathlib import Path
12-
from typing import TYPE_CHECKING, Any, Union
11+
from typing import TYPE_CHECKING
1312

1413
import numpy as np
1514
from monty.io import zopen
@@ -20,17 +19,17 @@
2019
from pymatgen.io.vasp.outputs import Vasprun, Xdatcar
2120

2221
if TYPE_CHECKING:
22+
from collections.abc import Iterator
23+
2324
from typing_extensions import Self
2425

26+
from pymatgen.util.typing import Matrix3D, SitePropsType, Vector3D
27+
2528

2629
__author__ = "Eric Sivonxay, Shyam Dwaraknath, Mingjian Wen, Evan Spotte-Smith"
2730
__version__ = "0.1"
2831
__date__ = "Jun 29, 2022"
2932

30-
Vector3D = tuple[float, float, float]
31-
Matrix3D = tuple[Vector3D, Vector3D, Vector3D]
32-
SitePropsType = Union[list[dict[Any, Sequence[Any]]], dict[Any, Sequence[Any]]]
33-
3433

3534
class Trajectory(MSONable):
3635
"""Trajectory of a geometry optimization or molecular dynamics simulation.

pymatgen/io/aims/outputs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
from collections.abc import Sequence
1919
from pathlib import Path
2020

21-
from emmet.core.math import Matrix3D, Vector3D
2221
from typing_extensions import Self
2322

2423
from pymatgen.core import Molecule, Structure
24+
from pymatgen.util.typing import Matrix3D, Vector3D
2525

2626
__author__ = "Andrey Sobolev and Thomas A. R. Purcell"
2727
__version__ = "1.0"

pymatgen/io/aims/parsers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import gzip
66
from dataclasses import dataclass, field
77
from pathlib import Path
8-
from typing import TYPE_CHECKING, Any
8+
from typing import TYPE_CHECKING, Any, cast
99

1010
import numpy as np
1111

@@ -16,7 +16,7 @@
1616
from collections.abc import Generator, Sequence
1717
from io import TextIOWrapper
1818

19-
from emmet.core.math import Matrix3D, Vector3D
19+
from pymatgen.util.typing import Matrix3D, Vector3D
2020

2121
__author__ = "Thomas A. R. Purcell and Andrey Sobolev"
2222
__version__ = "1.0"
@@ -566,9 +566,9 @@ def _parse_lattice_atom_pos(
566566
elif "atom " in line:
567567
line_split = line.split()
568568
species.append(line_split[4])
569-
coords.append([float(inp) for inp in line_split[1:4]])
569+
coords.append(cast(tuple[float, float, float], tuple(float(inp) for inp in line_split[1:4])))
570570
elif "velocity " in line:
571-
velocities.append([float(inp) for inp in line.split()[1:]])
571+
velocities.append(cast(tuple[float, float, float], tuple(float(inp) for inp in line.split()[1:4])))
572572

573573
lattice = Lattice(lattice_vectors) if len(lattice_vectors) == 3 else None
574574
return species, coords, velocities, lattice

pymatgen/io/cif.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
if TYPE_CHECKING:
3333
from typing_extensions import Self
3434

35-
from pymatgen.core.trajectory import Vector3D
35+
from pymatgen.util.typing import Vector3D
3636

3737
__author__ = "Shyue Ping Ong, Will Richards, Matthew Horton"
3838

pymatgen/io/cp2k/inputs.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050

5151
from pymatgen.core.lattice import Lattice
5252
from pymatgen.core.structure import Molecule, Structure
53+
from pymatgen.util.typing import Kpoint
5354

5455
__author__ = "Nicholas Winner"
5556
__version__ = "2.0"
@@ -2031,37 +2032,44 @@ def from_kpoints(cls, kpoints: VaspKpoints, structure=None) -> Self:
20312032
weights = kpoints.kpts_weights
20322033

20332034
if kpoints.style == KpointsSupportedModes.Monkhorst:
2034-
k = kpts[0]
2035-
x, y, z = (k, k, k) if isinstance(k, (int, float)) else k
2035+
kpt: Kpoint = kpts[0] # type: ignore[assignment]
2036+
x, y, z = (kpt, kpt, kpt) if isinstance(kpt, (int, float)) else kpt # type: ignore[misc]
20362037
scheme = f"MONKHORST-PACK {x} {y} {z}"
20372038
units = "B_VECTOR"
2039+
20382040
elif kpoints.style == KpointsSupportedModes.Reciprocal:
20392041
units = "B_VECTOR"
20402042
scheme = "GENERAL"
2043+
20412044
elif kpoints.style == KpointsSupportedModes.Cartesian:
20422045
units = "CART_ANGSTROM"
20432046
scheme = "GENERAL"
2047+
20442048
elif kpoints.style == KpointsSupportedModes.Gamma:
2049+
if not structure:
2050+
raise ValueError(
2051+
"No cp2k automatic gamma constructor. A structure is required to construct from spglib"
2052+
)
2053+
20452054
if (isinstance(kpts[0], Iterable) and tuple(kpts[0]) == (1, 1, 1)) or (
20462055
isinstance(kpts[0], (float, int)) and int(kpts[0]) == 1
20472056
):
20482057
scheme = "GAMMA"
2049-
units = "B_VECTOR"
2050-
elif not structure:
2051-
raise ValueError(
2052-
"No cp2k automatic gamma constructor. A structure is required to construct from spglib"
2053-
)
20542058
else:
20552059
sga = SpacegroupAnalyzer(structure)
2056-
_kpts, weights = zip(*sga.get_ir_reciprocal_mesh(mesh=kpts))
2057-
kpts = list(itertools.chain.from_iterable(_kpts))
2060+
_kpts, weights = zip(*sga.get_ir_reciprocal_mesh(mesh=kpts)) # type: ignore[assignment]
2061+
kpts = tuple(itertools.chain.from_iterable(_kpts))
20582062
scheme = "GENERAL"
2059-
units = "B_VECTOR"
2063+
2064+
units = "B_VECTOR"
2065+
20602066
elif kpoints.style == KpointsSupportedModes.Line_mode:
20612067
scheme = "GENERAL"
20622068
units = "B_VECTOR"
2069+
20632070
else:
20642071
raise ValueError("Unrecognized k-point style")
2072+
20652073
return Kpoints(kpts=kpts, weights=weights, scheme=scheme, units=units)
20662074

20672075

pymatgen/io/lobster/inputs.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@
3030
from pymatgen.util.due import Doi, due
3131

3232
if TYPE_CHECKING:
33-
from collections.abc import Sequence
34-
3533
from typing_extensions import Self
3634

3735
from pymatgen.core.composition import Composition
@@ -431,7 +429,7 @@ def write_KPOINTS(
431429
reciprocal_density: int = 100,
432430
isym: int = -1,
433431
from_grid: bool = False,
434-
input_grid: Sequence[int] = (5, 5, 5),
432+
input_grid: tuple[int, int, int] = (5, 5, 5),
435433
line_mode: bool = True,
436434
kpoints_line_density: int = 20,
437435
symprec: float = 0.01,
@@ -446,7 +444,7 @@ def write_KPOINTS(
446444
isym (int): either -1 or 0. Current Lobster versions only allow -1.
447445
from_grid (bool): If True KPOINTS will be generated with the help of a grid given in input_grid.
448446
Otherwise, they will be generated from the reciprocal_density
449-
input_grid (list): grid to generate the KPOINTS file
447+
input_grid (tuple): grid to generate the KPOINTS file
450448
line_mode (bool): If True, band structure will be generated
451449
kpoints_line_density (int): density of the lines in the band structure
452450
symprec (float): precision to determine symmetry
@@ -543,7 +541,7 @@ def write_KPOINTS(
543541
comment=comment,
544542
style=Kpoints.supported_modes.Reciprocal,
545543
num_kpts=len(kpts),
546-
kpts=kpts,
544+
kpts=tuple(kpts),
547545
kpts_weights=weights,
548546
labels=all_labels,
549547
)

pymatgen/io/lobster/outputs.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1407,9 +1407,10 @@ def __init__(
14071407
self.p_eigenvals = p_eigenvals
14081408

14091409
label_dict = {}
1410-
for idx, label in enumerate(kpoints_object.labels[-self.number_kpts :], start=0):
1411-
if label is not None:
1412-
label_dict[label] = kpoints_array[idx]
1410+
if kpoints_object.labels is not None:
1411+
for idx, label in enumerate(kpoints_object.labels[-self.number_kpts :], start=0):
1412+
if label is not None:
1413+
label_dict[label] = kpoints_array[idx]
14131414

14141415
self.label_dict = label_dict
14151416

pymatgen/io/res.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
from typing_extensions import Self
3131

32-
from pymatgen.core.trajectory import Vector3D
32+
from pymatgen.util.typing import Vector3D
3333

3434

3535
@dataclass(frozen=True)

0 commit comments

Comments
 (0)