Coverage for ase/io/castep/castep_input_file.py: 78.47%
288 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 difflib
2import re
3import warnings
5import numpy as np
7from ase import Atoms
9# A convenient table to avoid the previously used "eval"
10_tf_table = {
11 '': True, # Just the keyword is equivalent to True
12 'True': True,
13 'False': False,
14}
17def _parse_tss_block(value, scaled=False):
18 # Parse the assigned value for a Transition State Search structure block
19 is_atoms = isinstance(value, Atoms)
20 try:
21 is_strlist = all(map(lambda x: isinstance(x, str), value))
22 except TypeError:
23 is_strlist = False
25 if not is_atoms:
26 if not is_strlist:
27 # Invalid!
28 raise TypeError(
29 'castep.cell.positions_abs/frac_intermediate/'
30 'product expects Atoms object or list of strings'
31 )
33 # First line must be Angstroms, or nothing
34 has_units = len(value[0].strip().split()) == 1
35 if (not scaled) and has_units and value[0].strip() != 'ang':
36 raise RuntimeError(
37 'Only ang units currently supported in castep.'
38 'cell.positions_abs_intermediate/product'
39 )
40 return '\n'.join(map(str.strip, value))
41 else:
42 text_block = '' if scaled else 'ang\n'
43 positions = (
44 value.get_scaled_positions() if scaled else value.get_positions()
45 )
46 symbols = value.get_chemical_symbols()
47 for s, p in zip(symbols, positions):
48 text_block += ' {} {:.3f} {:.3f} {:.3f}\n'.format(s, *p)
50 return text_block
53class CastepOption:
54 """CASTEP option.
56 Handles basic conversions from string to its value type."""
58 default_convert_types = {
59 'boolean (logical)': 'bool',
60 'defined': 'bool',
61 'string': 'str',
62 'integer': 'int',
63 'real': 'float',
64 'integer vector': 'int_vector',
65 'real vector': 'float_vector',
66 'physical': 'float_physical',
67 'block': 'block',
68 }
70 def __init__(
71 self,
72 keyword,
73 level,
74 option_type,
75 value=None,
76 docstring='No information available',
77 ):
78 self.keyword = keyword
79 self.level = level
80 self.type = option_type
81 self._value = value
82 self.__doc__ = docstring
84 @property
85 def value(self):
87 if self._value is not None:
88 if self.type.lower() in (
89 'integer vector',
90 'real vector',
91 'physical',
92 ):
93 return ' '.join(map(str, self._value))
94 elif self.type.lower() in ('boolean (logical)', 'defined'):
95 return str(self._value).upper()
96 else:
97 return str(self._value)
99 @property
100 def raw_value(self):
101 # The value, not converted to a string
102 return self._value
104 @value.setter # type: ignore[attr-defined, no-redef]
105 def value(self, val):
107 if val is None:
108 self.clear()
109 return
111 ctype = self.default_convert_types.get(self.type.lower(), 'str')
112 typeparse = f'_parse_{ctype}'
113 try:
114 self._value = getattr(self, typeparse)(val)
115 except ValueError:
116 raise ConversionError(ctype, self.keyword, val)
118 def clear(self):
119 """Reset the value of the option to None again"""
120 self._value = None
122 @staticmethod
123 def _parse_bool(value):
124 try:
125 value = _tf_table[str(value).strip().title()]
126 except (KeyError, ValueError):
127 raise ValueError()
128 return value
130 @staticmethod
131 def _parse_str(value):
132 value = str(value)
133 return value
135 @staticmethod
136 def _parse_int(value):
137 value = int(value)
138 return value
140 @staticmethod
141 def _parse_float(value):
142 value = float(value)
143 return value
145 @staticmethod
146 def _parse_int_vector(value):
147 # Accepts either a string or an actual list/numpy array of ints
148 if isinstance(value, str):
149 if ',' in value:
150 value = value.replace(',', ' ')
151 value = list(map(int, value.split()))
153 value = np.array(value)
155 if value.shape != (3,) or value.dtype != int:
156 raise ValueError()
158 return list(value)
160 @staticmethod
161 def _parse_float_vector(value):
162 # Accepts either a string or an actual list/numpy array of floats
163 if isinstance(value, str):
164 if ',' in value:
165 value = value.replace(',', ' ')
166 value = list(map(float, value.split()))
168 value = np.array(value) * 1.0
170 if value.shape != (3,) or value.dtype != float:
171 raise ValueError()
173 return list(value)
175 @staticmethod
176 def _parse_float_physical(value):
177 # If this is a string containing units, saves them
178 if isinstance(value, str):
179 value = value.split()
181 try:
182 l = len(value)
183 except TypeError:
184 l = 1
185 value = [value]
187 if l == 1:
188 try:
189 value = (float(value[0]), '')
190 except (TypeError, ValueError):
191 raise ValueError()
192 elif l == 2:
193 try:
194 value = (float(value[0]), value[1])
195 except (TypeError, ValueError, IndexError):
196 raise ValueError()
197 else:
198 raise ValueError()
200 return value
202 @staticmethod
203 def _parse_block(value):
205 if isinstance(value, str):
206 return value
207 elif hasattr(value, '__getitem__'):
208 return '\n'.join(value) # Arrays of lines
209 else:
210 raise ValueError()
212 def __repr__(self):
213 if self._value:
214 expr = ('Option: {keyword}({type}, {level}):\n{_value}\n').format(
215 **self.__dict__
216 )
217 else:
218 expr = ('Option: {keyword}[unset]({type}, {level})').format(
219 **self.__dict__
220 )
221 return expr
223 def __eq__(self, other):
224 if not isinstance(other, CastepOption):
225 return False
226 else:
227 return self.__dict__ == other.__dict__
230class CastepOptionDict:
231 """A dictionary-like object to hold a set of options for .cell or .param
232 files loaded from a dictionary, for the sake of validation.
234 Replaces the old CastepCellDict and CastepParamDict that were defined in
235 the castep_keywords.py file.
236 """
238 def __init__(self, options=None):
239 object.__init__(self)
240 self._options = {} # ComparableDict is not needed any more as
241 # CastepOptions can be compared directly now
242 for kw in options:
243 opt = CastepOption(**options[kw])
244 self._options[opt.keyword] = opt
245 self.__dict__[opt.keyword] = opt
248class CastepInputFile:
249 """Master class for CastepParam and CastepCell to inherit from"""
251 _keyword_conflicts: list[set[str]] = []
253 def __init__(self, options_dict=None, keyword_tolerance=1):
254 object.__init__(self)
256 if options_dict is None:
257 options_dict = CastepOptionDict({})
259 self._options = options_dict._options
260 self.__dict__.update(self._options)
261 # keyword_tolerance means how strict the checks on new attributes are
262 # 0 = no new attributes allowed
263 # 1 = new attributes allowed, warning given
264 # 2 = new attributes allowed, silent
265 self._perm = np.clip(keyword_tolerance, 0, 2)
267 # Compile a dictionary for quick check of conflict sets
268 self._conflict_dict = {
269 kw: set(cset).difference({kw})
270 for cset in self._keyword_conflicts
271 for kw in cset
272 }
274 def __repr__(self):
275 expr = ''
276 is_default = True
277 for key, option in sorted(self._options.items()):
278 if option.value is not None:
279 is_default = False
280 expr += '%20s : %s\n' % (key, option.value)
281 if is_default:
282 expr = 'Default\n'
284 expr += f'Keyword tolerance: {self._perm}'
285 return expr
287 def __setattr__(self, attr, value):
289 # Hidden attributes are treated normally
290 if attr.startswith('_'):
291 self.__dict__[attr] = value
292 return
294 if attr not in self._options.keys():
295 if self._perm > 0:
296 # Do we consider it a string or a block?
297 is_str = isinstance(value, str)
298 is_block = False
299 if (hasattr(value, '__getitem__') and not is_str) or (
300 is_str and len(value.split('\n')) > 1
301 ):
302 is_block = True
304 if self._perm == 0:
305 similars = difflib.get_close_matches(attr, self._options.keys())
306 if similars:
307 raise RuntimeError(
308 f'Option "{attr}" not known! You mean "{similars[0]}"?'
309 )
310 else:
311 raise RuntimeError(f'Option "{attr}" is not known!')
312 elif self._perm == 1:
313 warnings.warn(
314 ('Option "%s" is not known and will be added as a %s')
315 % (attr, ('block' if is_block else 'string'))
316 )
317 attr = attr.lower()
318 opt = CastepOption(
319 keyword=attr,
320 level='Unknown',
321 option_type='block' if is_block else 'string',
322 )
323 self._options[attr] = opt
324 self.__dict__[attr] = opt
325 else:
326 attr = attr.lower()
327 opt = self._options[attr]
329 if not opt.type.lower() == 'block' and isinstance(value, str):
330 value = value.replace(':', ' ')
332 # If it is, use the appropriate parser, unless a custom one is defined
333 attrparse = f'_parse_{attr.lower()}'
335 # Check for any conflicts if the value is not None
336 if value is not None:
337 cset = self._conflict_dict.get(attr.lower(), {})
338 for c in cset:
339 if c in self._options and self._options[c].value:
340 warnings.warn(
341 'option "{attr}" conflicts with "{conflict}" in '
342 'calculator. Setting "{conflict}" to '
343 'None.'.format(attr=attr, conflict=c)
344 )
345 self._options[c].value = None
347 if hasattr(self, attrparse):
348 self._options[attr].value = self.__getattribute__(attrparse)(value)
349 else:
350 self._options[attr].value = value
352 def __getattr__(self, name):
353 if name[0] == '_' or self._perm == 0:
354 raise AttributeError()
356 if self._perm == 1:
357 warnings.warn(f'Option {(name)} is not known, returning None')
359 return CastepOption(
360 keyword='none', level='Unknown', option_type='string', value=None
361 )
363 def get_attr_dict(self, raw=False, types=False):
364 """Settings that go into .param file in a traditional dict"""
366 attrdict = {
367 k: o.raw_value if raw else o.value
368 for k, o in self._options.items()
369 if o.value is not None
370 }
372 if types:
373 for key, val in attrdict.items():
374 attrdict[key] = (val, self._options[key].type)
376 return attrdict
379class CastepParam(CastepInputFile):
380 """CastepParam abstracts the settings that go into the .param file"""
382 _keyword_conflicts = [
383 {'cut_off_energy', 'basis_precision'},
384 ]
386 def __init__(self, castep_keywords, keyword_tolerance=1):
387 self._castep_version = castep_keywords.castep_version
388 CastepInputFile.__init__(
389 self, castep_keywords.CastepParamDict(), keyword_tolerance
390 )
392 @property
393 def castep_version(self):
394 return self._castep_version
396 # .param specific parsers
397 def _parse_reuse(self, value):
398 if value is None:
399 return None # Reset the value
400 try:
401 if self._options['continuation'].value:
402 warnings.warn(
403 'Cannot set reuse if continuation is set, and '
404 'vice versa. Set the other to None, if you want '
405 'this setting.'
406 )
407 return None
408 except KeyError:
409 pass
410 return 'default' if (value is True) else str(value)
412 def _parse_continuation(self, value):
413 if value is None:
414 return None # Reset the value
415 try:
416 if self._options['reuse'].value:
417 warnings.warn(
418 'Cannot set reuse if continuation is set, and '
419 'vice versa. Set the other to None, if you want '
420 'this setting.'
421 )
422 return None
423 except KeyError:
424 pass
425 return 'default' if (value is True) else str(value)
428class CastepCell(CastepInputFile):
429 """CastepCell abstracts all setting that go into the .cell file"""
431 _keyword_conflicts = [
432 {
433 'kpoint_mp_grid',
434 'kpoint_mp_spacing',
435 'kpoint_list',
436 'kpoints_mp_grid',
437 'kpoints_mp_spacing',
438 'kpoints_list',
439 },
440 {
441 'bs_kpoint_mp_grid',
442 'bs_kpoint_mp_spacing',
443 'bs_kpoint_list',
444 'bs_kpoint_path',
445 'bs_kpoints_mp_grid',
446 'bs_kpoints_mp_spacing',
447 'bs_kpoints_list',
448 'bs_kpoints_path',
449 },
450 {
451 'spectral_kpoint_mp_grid',
452 'spectral_kpoint_mp_spacing',
453 'spectral_kpoint_list',
454 'spectral_kpoint_path',
455 'spectral_kpoints_mp_grid',
456 'spectral_kpoints_mp_spacing',
457 'spectral_kpoints_list',
458 'spectral_kpoints_path',
459 },
460 {
461 'phonon_kpoint_mp_grid',
462 'phonon_kpoint_mp_spacing',
463 'phonon_kpoint_list',
464 'phonon_kpoint_path',
465 'phonon_kpoints_mp_grid',
466 'phonon_kpoints_mp_spacing',
467 'phonon_kpoints_list',
468 'phonon_kpoints_path',
469 },
470 {
471 'fine_phonon_kpoint_mp_grid',
472 'fine_phonon_kpoint_mp_spacing',
473 'fine_phonon_kpoint_list',
474 'fine_phonon_kpoint_path',
475 },
476 {
477 'magres_kpoint_mp_grid',
478 'magres_kpoint_mp_spacing',
479 'magres_kpoint_list',
480 'magres_kpoint_path',
481 },
482 {
483 'elnes_kpoint_mp_grid',
484 'elnes_kpoint_mp_spacing',
485 'elnes_kpoint_list',
486 'elnes_kpoint_path',
487 },
488 {
489 'optics_kpoint_mp_grid',
490 'optics_kpoint_mp_spacing',
491 'optics_kpoint_list',
492 'optics_kpoint_path',
493 },
494 {
495 'supercell_kpoint_mp_grid',
496 'supercell_kpoint_mp_spacing',
497 'supercell_kpoint_list',
498 'supercell_kpoint_path',
499 },
500 ]
502 def __init__(self, castep_keywords, keyword_tolerance=1):
503 self._castep_version = castep_keywords.castep_version
504 CastepInputFile.__init__(
505 self, castep_keywords.CastepCellDict(), keyword_tolerance
506 )
508 @property
509 def castep_version(self):
510 return self._castep_version
512 # .cell specific parsers
513 def _parse_species_pot(self, value):
515 # Single tuple
516 if isinstance(value, tuple) and len(value) == 2:
517 value = [value]
518 # List of tuples
519 if hasattr(value, '__getitem__'):
520 pspots = [tuple(map(str.strip, x)) for x in value]
521 if not all(map(lambda x: len(x) == 2, value)):
522 warnings.warn(
523 'Please specify pseudopotentials in python as '
524 'a tuple or a list of tuples formatted like: '
525 '(species, file), e.g. ("O", "path-to/O_OTFG.usp") '
526 'Anything else will be ignored'
527 )
528 return None
530 text_block = self._options['species_pot'].value
532 text_block = text_block if text_block else ''
533 # Remove any duplicates
534 for pp in pspots:
535 text_block = re.sub(rf'\n?\s*{pp[0]}\s+.*', '', text_block)
536 if pp[1]:
537 text_block += '\n%s %s' % pp
539 return text_block
541 def _parse_symmetry_ops(self, value):
542 if (
543 not isinstance(value, tuple)
544 or not len(value) == 2
545 or not value[0].shape[1:] == (3, 3)
546 or not value[1].shape[1:] == (3,)
547 or not value[0].shape[0] == value[1].shape[0]
548 ):
549 warnings.warn('Invalid symmetry_ops block, skipping')
550 return
551 # Now on to print...
552 text_block = ''
553 for op_i, (op_rot, op_tranls) in enumerate(zip(*value)):
554 text_block += '\n'.join(
555 [' '.join([str(x) for x in row]) for row in op_rot]
556 )
557 text_block += '\n'
558 text_block += ' '.join([str(x) for x in op_tranls])
559 text_block += '\n\n'
561 return text_block
563 def _parse_positions_abs_intermediate(self, value):
564 return _parse_tss_block(value)
566 def _parse_positions_abs_product(self, value):
567 return _parse_tss_block(value)
569 def _parse_positions_frac_intermediate(self, value):
570 return _parse_tss_block(value, True)
572 def _parse_positions_frac_product(self, value):
573 return _parse_tss_block(value, True)
576class ConversionError(Exception):
577 """Print customized error for options that are not converted correctly
578 and point out that they are maybe not implemented, yet"""
580 def __init__(self, key_type, attr, value):
581 Exception.__init__(self)
582 self.key_type = key_type
583 self.value = value
584 self.attr = attr
586 def __str__(self):
587 contact_email = 'simon.rittmeyer@tum.de'
588 return (
589 f'Could not convert {self.attr} = {self.value} '
590 + 'to {self.key_type}\n'
591 + 'This means you either tried to set a value of the wrong\n'
592 + 'type or this keyword needs some special care. Please feel\n'
593 + 'to add it to the corresponding __setattr__ method and send\n'
594 + f'the patch to {(contact_email)}, so we can all benefit.'
595 )