Coverage for ase/io/espresso_namelist/namelist.py: 96.97%
66 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import re
2import warnings
3from collections import UserDict
4from collections.abc import MutableMapping
5from pathlib import Path
7from ase.io.espresso_namelist.keys import ALL_KEYS
10class Namelist(UserDict):
11 """A case-insensitive dictionary for storing Quantum Espresso namelists.
12 This class is a subclass of UserDict, which is a wrapper around a regular
13 dictionary. This allows us to define custom behavior for the dictionary
14 methods, while still having access to the full dictionary API.
16 to_string() have been added to handle the conversion of the dictionary
17 to a string for writing to a file or quick lookup using print().
19 to_nested() have been added to convert the dictionary to a nested
20 dictionary with the correct structure for the specified binary.
21 """
23 def __getitem__(self, key):
24 return super().__getitem__(key.lower())
26 def __setitem__(self, key, value):
27 super().__setitem__(
28 key.lower(),
29 Namelist(value) if isinstance(value, MutableMapping) else value,
30 )
32 def __delitem__(self, key):
33 super().__delitem__(key.lower())
35 def __contains__(self, key):
36 return super().__contains__(key.lower())
38 @staticmethod
39 def search_key(to_find, keys):
40 """Search for a key in the namelist, case-insensitive.
41 Returns the section and key if found, None otherwise.
42 """
43 for section in keys:
44 for key in keys[section]:
45 if re.match(rf'({key})\b(\(+.*\)+)?$', to_find):
46 return section
48 def to_string(self, indent=0, list_form=False):
49 """Format a Namelist object as a string for writing to a file.
50 Assume sections are ordered (taken care of in namelist construction)
51 and that repr converts to a QE readable representation (except bools)
53 Parameters
54 ----------
55 indent : int
56 Number of spaces to indent each line
57 list_form : bool
58 If True, return a list of strings instead of a single string
60 Returns
61 -------
62 pwi : List[str] | str
63 Input line for the namelist
64 """
65 pwi = []
66 for key, value in self.items():
67 if isinstance(value, (Namelist, dict)):
68 pwi.append(f'{" " * indent}&{key.upper()}\n')
69 pwi.extend(Namelist.to_string(value, indent=indent + 3))
70 pwi.append(f'{" " * indent}/\n')
71 else:
72 if value is True:
73 pwi.append(f'{" " * indent}{key:16} = .true.\n')
74 elif value is False:
75 pwi.append(f'{" " * indent}{key:16} = .false.\n')
76 elif isinstance(value, Path):
77 pwi.append(f"{' ' * indent}{key:16} = '{value}'\n")
78 else:
79 pwi.append(f'{" " * indent}{key:16} = {value!r}\n')
80 if list_form:
81 return pwi
82 else:
83 return ''.join(pwi)
85 def to_nested(self, binary='pw', warn=False, **kwargs):
86 keys = ALL_KEYS[binary]
88 constructed_namelist = {
89 section: self.pop(section, {}) for section in keys
90 }
92 constructed_namelist.update(
93 {
94 key: value
95 for key, value in self.items()
96 if isinstance(value, Namelist)
97 }
98 )
100 unused_keys = []
101 for arg_key in list(self):
102 section = Namelist.search_key(arg_key, keys)
103 value = self.pop(arg_key)
104 if section:
105 constructed_namelist[section][arg_key] = value
106 else:
107 unused_keys.append(arg_key)
109 for arg_key in list(kwargs):
110 section = Namelist.search_key(arg_key, keys)
111 value = kwargs.pop(arg_key)
112 if section:
113 warnings.warn(
114 (
115 'Use of kwarg(s) as keyword(s) is deprecated,'
116 'use input_data instead'
117 ),
118 DeprecationWarning,
119 )
120 constructed_namelist[section][arg_key] = value
121 else:
122 unused_keys.append(arg_key)
124 if unused_keys and warn:
125 warnings.warn(
126 f'Unused keys: {", ".join(unused_keys)}',
127 UserWarning,
128 )
130 for section in constructed_namelist:
131 sorted_section = {}
133 def sorting_rule(item):
134 return (
135 keys[section].index(item.split('(')[0])
136 if item.split('(')[0] in keys.get(section, {})
137 else float('inf')
138 )
140 for key in sorted(constructed_namelist[section], key=sorting_rule):
141 sorted_section[key] = constructed_namelist[section][key]
143 constructed_namelist[section] = sorted_section
145 super().update(Namelist(constructed_namelist))