Skip to content

Commit

Permalink
issue warning for duplicate keys
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielYang59 committed Oct 19, 2024
1 parent 51f5922 commit d43bb1a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/pymatgen/io/vasp/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import re
import subprocess
import warnings
from collections import UserDict
from collections import Counter, UserDict
from enum import Enum, unique
from glob import glob
from hashlib import sha256
Expand Down Expand Up @@ -720,14 +720,21 @@ class Incar(UserDict, MSONable):

def __init__(self, params: dict[str, Any] | None = None) -> None:
"""
Create an Incar object.
Clean up params and create an Incar object.
Args:
params (dict): Input parameters as a dictionary.
Warnings:
BadIncarWarning: If there are duplicate in keys (case insensitive).
"""
super().__init__()
params = params if params is not None else {}
# TODO: Check for duplicate in params
params = params or {}

# Check for case-insensitive duplicate keys
key_counter = Counter(key.strip().upper() for key in params)
duplicates = [key for key, count in key_counter.items() if count > 1]
if duplicates:
warnings.warn(f"Duplicate keys found (case-insensitive): {duplicates}", BadIncarWarning, stacklevel=2)

# If INCAR contains vector-like MAGMOMS given as a list
# of floats, convert to a list of lists
Expand All @@ -739,7 +746,7 @@ def __init__(self, params: dict[str, Any] | None = None) -> None:
val.append(params["MAGMOM"][idx * 3 : (idx + 1) * 3])
params["MAGMOM"] = val

self.update(params)
super().__init__(params)

def __setitem__(self, key: str, val: Any) -> None:
"""
Expand Down
8 changes: 8 additions & 0 deletions tests/io/vasp/test_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,14 @@ def test_init(self):
assert float(incar["EDIFF"]) == 1e-4, "Wrong EDIFF"
assert isinstance(incar["LORBIT"], int)

def test_check_for_duplicate(self):
incar_str: str = """encut = 400
ENCUT = 500
"""

with pytest.warns(UserWarning, match="Duplicate keys found"):
Incar.from_str(incar_str)

def test_key_case_insensitive(self):
"""Verify that keys are case-insensitive by internally converting
all keys to upper case. This includes operations such as:
Expand Down

0 comments on commit d43bb1a

Please sign in to comment.