Skip to content

Commit

Permalink
Convert kpts in Kpoints to Sequence[tuple] and set it as `prope…
Browse files Browse the repository at this point in the history
…rty` (#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
  • Loading branch information
DanielYang59 authored Apr 28, 2024
1 parent e04444e commit bf2f421
Show file tree
Hide file tree
Showing 16 changed files with 310 additions and 188 deletions.
3 changes: 1 addition & 2 deletions pymatgen/core/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
from numpy.typing import ArrayLike
from typing_extensions import Self

from pymatgen.core.trajectory import Vector3D
from pymatgen.util.typing import CompositionLike
from pymatgen.util.typing import CompositionLike, Vector3D

# This module implements representations of grain boundaries, as well as
# algorithms for generating them.
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@
from numpy.typing import ArrayLike
from typing_extensions import Self

from pymatgen.core.trajectory import Vector3D
from pymatgen.util.typing import PbcLike
from pymatgen.util.typing import PbcLike, Vector3D

__author__ = "Shyue Ping Ong, Michael Kocher"
__copyright__ = "Copyright 2011, The Materials Project"
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/core/trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@

import itertools
import warnings
from collections.abc import Iterator, Sequence
from fnmatch import fnmatch
from pathlib import Path
from typing import TYPE_CHECKING, Any, Union
from typing import TYPE_CHECKING

import numpy as np
from monty.io import zopen
Expand All @@ -20,17 +19,17 @@
from pymatgen.io.vasp.outputs import Vasprun, Xdatcar

if TYPE_CHECKING:
from collections.abc import Iterator

from typing_extensions import Self

from pymatgen.util.typing import Matrix3D, SitePropsType, Vector3D


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

Vector3D = tuple[float, float, float]
Matrix3D = tuple[Vector3D, Vector3D, Vector3D]
SitePropsType = Union[list[dict[Any, Sequence[Any]]], dict[Any, Sequence[Any]]]


class Trajectory(MSONable):
"""Trajectory of a geometry optimization or molecular dynamics simulation.
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/aims/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
from collections.abc import Sequence
from pathlib import Path

from emmet.core.math import Matrix3D, Vector3D
from typing_extensions import Self

from pymatgen.core import Molecule, Structure
from pymatgen.util.typing import Matrix3D, Vector3D

__author__ = "Andrey Sobolev and Thomas A. R. Purcell"
__version__ = "1.0"
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/io/aims/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import gzip
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, cast

import numpy as np

Expand All @@ -16,7 +16,7 @@
from collections.abc import Generator, Sequence
from io import TextIOWrapper

from emmet.core.math import Matrix3D, Vector3D
from pymatgen.util.typing import Matrix3D, Vector3D

__author__ = "Thomas A. R. Purcell and Andrey Sobolev"
__version__ = "1.0"
Expand Down Expand Up @@ -566,9 +566,9 @@ def _parse_lattice_atom_pos(
elif "atom " in line:
line_split = line.split()
species.append(line_split[4])
coords.append([float(inp) for inp in line_split[1:4]])
coords.append(cast(tuple[float, float, float], tuple(float(inp) for inp in line_split[1:4])))
elif "velocity " in line:
velocities.append([float(inp) for inp in line.split()[1:]])
velocities.append(cast(tuple[float, float, float], tuple(float(inp) for inp in line.split()[1:4])))

lattice = Lattice(lattice_vectors) if len(lattice_vectors) == 3 else None
return species, coords, velocities, lattice
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/cif.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
if TYPE_CHECKING:
from typing_extensions import Self

from pymatgen.core.trajectory import Vector3D
from pymatgen.util.typing import Vector3D

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

Expand Down
28 changes: 18 additions & 10 deletions pymatgen/io/cp2k/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@

from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Molecule, Structure
from pymatgen.util.typing import Kpoint

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

if kpoints.style == KpointsSupportedModes.Monkhorst:
k = kpts[0]
x, y, z = (k, k, k) if isinstance(k, (int, float)) else k
kpt: Kpoint = kpts[0] # type: ignore[assignment]
x, y, z = (kpt, kpt, kpt) if isinstance(kpt, (int, float)) else kpt # type: ignore[misc]
scheme = f"MONKHORST-PACK {x} {y} {z}"
units = "B_VECTOR"

elif kpoints.style == KpointsSupportedModes.Reciprocal:
units = "B_VECTOR"
scheme = "GENERAL"

elif kpoints.style == KpointsSupportedModes.Cartesian:
units = "CART_ANGSTROM"
scheme = "GENERAL"

elif kpoints.style == KpointsSupportedModes.Gamma:
if not structure:
raise ValueError(
"No cp2k automatic gamma constructor. A structure is required to construct from spglib"
)

if (isinstance(kpts[0], Iterable) and tuple(kpts[0]) == (1, 1, 1)) or (
isinstance(kpts[0], (float, int)) and int(kpts[0]) == 1
):
scheme = "GAMMA"
units = "B_VECTOR"
elif not structure:
raise ValueError(
"No cp2k automatic gamma constructor. A structure is required to construct from spglib"
)
else:
sga = SpacegroupAnalyzer(structure)
_kpts, weights = zip(*sga.get_ir_reciprocal_mesh(mesh=kpts))
kpts = list(itertools.chain.from_iterable(_kpts))
_kpts, weights = zip(*sga.get_ir_reciprocal_mesh(mesh=kpts)) # type: ignore[assignment]
kpts = tuple(itertools.chain.from_iterable(_kpts))
scheme = "GENERAL"
units = "B_VECTOR"

units = "B_VECTOR"

elif kpoints.style == KpointsSupportedModes.Line_mode:
scheme = "GENERAL"
units = "B_VECTOR"

else:
raise ValueError("Unrecognized k-point style")

return Kpoints(kpts=kpts, weights=weights, scheme=scheme, units=units)


Expand Down
8 changes: 3 additions & 5 deletions pymatgen/io/lobster/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
from pymatgen.util.due import Doi, due

if TYPE_CHECKING:
from collections.abc import Sequence

from typing_extensions import Self

from pymatgen.core.composition import Composition
Expand Down Expand Up @@ -431,7 +429,7 @@ def write_KPOINTS(
reciprocal_density: int = 100,
isym: int = -1,
from_grid: bool = False,
input_grid: Sequence[int] = (5, 5, 5),
input_grid: tuple[int, int, int] = (5, 5, 5),
line_mode: bool = True,
kpoints_line_density: int = 20,
symprec: float = 0.01,
Expand All @@ -446,7 +444,7 @@ def write_KPOINTS(
isym (int): either -1 or 0. Current Lobster versions only allow -1.
from_grid (bool): If True KPOINTS will be generated with the help of a grid given in input_grid.
Otherwise, they will be generated from the reciprocal_density
input_grid (list): grid to generate the KPOINTS file
input_grid (tuple): grid to generate the KPOINTS file
line_mode (bool): If True, band structure will be generated
kpoints_line_density (int): density of the lines in the band structure
symprec (float): precision to determine symmetry
Expand Down Expand Up @@ -543,7 +541,7 @@ def write_KPOINTS(
comment=comment,
style=Kpoints.supported_modes.Reciprocal,
num_kpts=len(kpts),
kpts=kpts,
kpts=tuple(kpts),
kpts_weights=weights,
labels=all_labels,
)
Expand Down
7 changes: 4 additions & 3 deletions pymatgen/io/lobster/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1407,9 +1407,10 @@ def __init__(
self.p_eigenvals = p_eigenvals

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

self.label_dict = label_dict

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/res.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

from typing_extensions import Self

from pymatgen.core.trajectory import Vector3D
from pymatgen.util.typing import Vector3D


@dataclass(frozen=True)
Expand Down
Loading

0 comments on commit bf2f421

Please sign in to comment.