Coverage for ase/utils/__init__.py: 82.08%
413 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 errno
2import functools
3import io
4import os
5import pickle
6import re
7import string
8import sys
9import time
10import warnings
11from collections.abc import Callable
12from contextlib import ExitStack, contextmanager
13from importlib import import_module
14from math import atan2, cos, degrees, gcd, radians, sin
15from pathlib import Path, PurePath
17import numpy as np
19from ase.formula import formula_hill, formula_metal
21__all__ = [
22 'basestring',
23 'import_module',
24 'seterr',
25 'plural',
26 'devnull',
27 'gcd',
28 'convert_string_to_fd',
29 'Lock',
30 'opencew',
31 'OpenLock',
32 'rotate',
33 'irotate',
34 'pbc2pbc',
35 'givens',
36 'hsv2rgb',
37 'hsv',
38 'pickleload',
39 'reader',
40 'formula_hill',
41 'formula_metal',
42 'PurePath',
43 'xwopen',
44 'tokenize_version',
45 'get_python_package_path_description',
46]
49def tokenize_version(version_string: str):
50 """Parse version string into a tuple for version comparisons.
52 Usage: tokenize_version('3.8') < tokenize_version('3.8.1').
53 """
54 tokens = []
55 for component in version_string.split('.'):
56 match = re.match(r'(\d*)(.*)', component)
57 assert match is not None, f'Cannot parse component {component}'
58 number_str, tail = match.group(1, 2)
59 try:
60 number = int(number_str)
61 except ValueError:
62 number = -1
63 tokens += [number, tail]
64 return tuple(tokens)
67# Python 2+3 compatibility stuff (let's try to remove these things):
68basestring = str
69pickleload = functools.partial(pickle.load, encoding='bytes')
72def deprecate_positionals(maxargs: int):
73 """Decorate a function to warn when too many positional arguments are used.
75 .. versionadded:: 3.30.0
77 Parameters
78 ----------
79 maxargs : int
80 Maximum number of positional arguments allowed without a warning.
82 Returns
83 -------
84 Callable
85 A decorator that emits a FutureWarning when the decorated function
86 is called with more than `maxargs` positional arguments.
87 """
89 def decorator(func):
90 @functools.wraps(func)
91 def wrapper(*args, **kwargs):
92 if len(args) > maxargs:
93 warnings.warn(
94 f'Please do not call {func.__qualname__} with more than '
95 f'{maxargs} positional arguments. Use keywords instead.',
96 FutureWarning,
97 )
98 return func(*args, **kwargs)
100 return wrapper
102 return decorator
105def deprecated(
106 message: str | Warning,
107 category: type[Warning] = FutureWarning,
108 callback: Callable[[list, dict], bool] = lambda args, kwargs: True,
109):
110 """Return a decorator deprecating a function.
112 Parameters
113 ----------
114 message : str or Warning
115 The message to be emitted. If ``message`` is a Warning, then
116 ``category`` is ignored and ``message.__class__`` will be used.
117 category : type[Warning], default=FutureWarning
118 The type of warning to be emitted. If ``message`` is a ``Warning``
119 instance, then ``category`` will be ignored and ``message.__class__``
120 will be used.
121 callback : Callable[[list, dict], bool], default=lambda args, kwargs: True
122 A callable that determines if the warning should be emitted and handles
123 any processing prior to calling the deprecated function. The callable
124 will receive two arguments, a list and a dictionary. The list will
125 contain the positional arguments that the deprecated function was
126 called with at runtime while the dictionary will contain the keyword
127 arguments. The callable *must* return ``True`` if the warning is to be
128 emitted and ``False`` otherwise. The list and dictionary will be
129 unpacked into the positional and keyword arguments, respectively, used
130 to call the deprecated function.
132 Returns
133 -------
134 deprecated_decorator : Callable
135 A decorator for deprecated functions that can be used to conditionally
136 emit deprecation warnings and/or pre-process the arguments of a
137 deprecated function.
139 Example
140 -------
141 >>> # Inspect & replace a keyword parameter passed to a deprecated function
142 >>> from typing import Any, Callable
143 >>> import warnings
144 >>> from ase.utils import deprecated
146 >>> def alias_callback_factory(kwarg: str, alias: str) -> Callable:
147 ... def _replace_arg(_: list, kwargs: dict[str, Any]) -> bool:
148 ... kwargs[kwarg] = kwargs[alias]
149 ... del kwargs[alias]
150 ... return True
151 ... return _replace_arg
153 >>> MESSAGE = ("Calling this function with `atoms` is deprecated. "
154 ... "Use `optimizable` instead.")
155 >>> @deprecated(
156 ... MESSAGE,
157 ... category=DeprecationWarning,
158 ... callback=alias_callback_factory("optimizable", "atoms")
159 ... )
160 ... def function(*, atoms=None, optimizable=None):
161 ... '''
162 ... .. deprecated:: 3.23.0
163 ... Calling this function with ``atoms`` is deprecated.
164 ... Use ``optimizable`` instead.
165 ... '''
166 ... print(f"atoms: {atoms}")
167 ... print(f"optimizable: {optimizable}")
169 >>> with warnings.catch_warnings(record=True) as w:
170 ... warnings.simplefilter("always")
171 ... function(atoms="atoms")
172 atoms: None
173 optimizable: atoms
175 >>> w[-1].category == DeprecationWarning
176 True
177 """
179 def deprecated_decorator(func):
180 @functools.wraps(func)
181 def deprecated_function(*args, **kwargs):
182 _args = list(args)
183 if callback(_args, kwargs):
184 warnings.warn(message, category=category, stacklevel=2)
186 return func(*_args, **kwargs)
188 return deprecated_function
190 return deprecated_decorator
193@contextmanager
194def seterr(**kwargs):
195 """Set how floating-point errors are handled.
197 See np.seterr() for more details.
198 """
199 old = np.seterr(**kwargs)
200 try:
201 yield
202 finally:
203 np.seterr(**old)
206def plural(n, word):
207 """Use plural for n!=1.
209 >>> from ase.utils import plural
211 >>> plural(0, 'egg'), plural(1, 'egg'), plural(2, 'egg')
212 ('0 eggs', '1 egg', '2 eggs')
213 """
214 if n == 1:
215 return '1 ' + word
216 return '%d %ss' % (n, word)
219class DevNull:
220 encoding = 'UTF-8'
221 closed = False
223 _use_os_devnull = deprecated(
224 'use open(os.devnull) instead', DeprecationWarning
225 )
226 # Deprecated for ase-3.21.0. Change to futurewarning later on.
228 @_use_os_devnull
229 def write(self, string):
230 pass
232 @_use_os_devnull
233 def flush(self):
234 pass
236 @_use_os_devnull
237 def seek(self, offset, whence=0):
238 return 0
240 @_use_os_devnull
241 def tell(self):
242 return 0
244 @_use_os_devnull
245 def close(self):
246 pass
248 @_use_os_devnull
249 def isatty(self):
250 return False
252 @_use_os_devnull
253 def read(self, n=-1):
254 return ''
257devnull = DevNull()
260@deprecated(
261 'convert_string_to_fd does not facilitate proper resource '
262 'management. '
263 'Please use e.g. ase.utils.IOContext class instead.'
264)
265def convert_string_to_fd(name, world=None):
266 """Create a file-descriptor for text output.
268 Will open a file for writing with given name. Use None for no output and
269 '-' for sys.stdout.
271 .. deprecated:: 3.22.1
272 Please use e.g. :class:`ase.utils.IOContext` class instead.
273 """
274 if world is None:
275 from ase.parallel import world
276 if name is None or world.rank != 0:
277 return open(os.devnull, 'w')
278 if name == '-':
279 return sys.stdout
280 if isinstance(name, (str, PurePath)):
281 return open(str(name), 'w') # str for py3.5 pathlib
282 return name # we assume name is already a file-descriptor
285# Only Windows has O_BINARY:
286CEW_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, 'O_BINARY', 0)
289@contextmanager
290def xwopen(filename, world=None):
291 """Create and open filename exclusively for writing.
293 If master cpu gets exclusive write access to filename, a file
294 descriptor is returned (a dummy file descriptor is returned on the
295 slaves). If the master cpu does not get write access, None is
296 returned on all processors."""
298 fd = opencew(filename, world)
299 try:
300 yield fd
301 finally:
302 if fd is not None:
303 fd.close()
306# @deprecated('use "with xwopen(...) as fd: ..." to prevent resource leak')
307def opencew(filename, world=None):
308 return _opencew(filename, world)
311def _opencew(filename, world=None):
312 import ase.parallel as parallel
314 if world is None:
315 world = parallel.world
317 closelater = []
319 def opener(file, flags):
320 return os.open(file, flags | CEW_FLAGS)
322 try:
323 error = 0
324 if world.rank == 0:
325 try:
326 fd = open(filename, 'wb', opener=opener)
327 except OSError as ex:
328 error = ex.errno
329 else:
330 closelater.append(fd)
331 else:
332 fd = open(os.devnull, 'wb')
333 closelater.append(fd)
335 # Synchronize:
336 error = world.sum_scalar(error)
337 if error == errno.EEXIST:
338 return None
339 if error:
340 raise OSError(error, 'Error', filename)
342 return fd
343 except BaseException:
344 for fd in closelater:
345 fd.close()
346 raise
349def opencew_text(*args, **kwargs):
350 fd = opencew(*args, **kwargs)
351 if fd is None:
352 return None
353 return io.TextIOWrapper(fd)
356class Lock:
357 def __init__(self, name='lock', world=None, timeout=float('inf')):
358 self.name = str(name)
359 self.timeout = timeout
360 if world is None:
361 from ase.parallel import world
362 self.world = world
364 def acquire(self):
365 dt = 0.2
366 t1 = time.time()
367 while True:
368 fd = opencew(self.name, self.world)
369 if fd is not None:
370 self.fd = fd
371 break
372 time_left = self.timeout - (time.time() - t1)
373 if time_left <= 0:
374 raise TimeoutError
375 time.sleep(min(dt, time_left))
376 dt *= 2
378 def release(self):
379 self.world.barrier()
380 # Important to close fd before deleting file on windows
381 # as a WinError would otherwise be raised.
382 self.fd.close()
383 if self.world.rank == 0:
384 os.remove(self.name)
385 self.world.barrier()
387 def __enter__(self):
388 self.acquire()
390 def __exit__(self, type, value, tb):
391 self.release()
394class OpenLock:
395 def acquire(self):
396 pass
398 def release(self):
399 pass
401 def __enter__(self):
402 pass
404 def __exit__(self, type, value, tb):
405 pass
408def search_current_git_hash(arg, world=None):
409 """Search for .git directory and current git commit hash.
411 Parameters
412 ----------
414 arg: str (directory path) or python module
415 .git directory is searched from the parent directory of
416 the given directory or module.
417 """
418 if world is None:
419 from ase.parallel import world
420 if world.rank != 0:
421 return None
423 # Check argument
424 if isinstance(arg, str):
425 # Directory path
426 dpath = arg
427 else:
428 # Assume arg is module
429 dpath = os.path.dirname(arg.__file__)
430 # dpath = os.path.abspath(dpath)
431 # in case this is just symlinked into $PYTHONPATH
432 dpath = os.path.realpath(dpath)
433 dpath = os.path.dirname(dpath) # Go to the parent directory
434 git_dpath = os.path.join(dpath, '.git')
435 if not os.path.isdir(git_dpath):
436 # Replace this 'if' with a loop if you want to check
437 # further parent directories
438 return None
439 HEAD_file = os.path.join(git_dpath, 'HEAD')
440 if not os.path.isfile(HEAD_file):
441 return None
442 with open(HEAD_file) as fd:
443 line = fd.readline().strip()
444 if line.startswith('ref: '):
445 ref = line[5:]
446 ref_file = os.path.join(git_dpath, ref)
447 else:
448 # Assuming detached HEAD state
449 ref_file = HEAD_file
450 if not os.path.isfile(ref_file):
451 return None
452 with open(ref_file) as fd:
453 line = fd.readline().strip()
454 if all(c in string.hexdigits for c in line):
455 return line
456 return None
459def rotate(rotations, rotation=np.identity(3)):
460 """Convert string of format '50x,-10y,120z' to a rotation matrix.
462 Note that the order of rotation matters, i.e. '50x,40z' is different
463 from '40z,50x'.
464 """
466 if rotations == '':
467 return rotation.copy()
469 for i, a in [
470 ('xyz'.index(s[-1]), radians(float(s[:-1])))
471 for s in rotations.split(',')
472 ]:
473 s = sin(a)
474 c = cos(a)
475 if i == 0:
476 rotation = np.dot(rotation, [(1, 0, 0), (0, c, s), (0, -s, c)])
477 elif i == 1:
478 rotation = np.dot(rotation, [(c, 0, -s), (0, 1, 0), (s, 0, c)])
479 else:
480 rotation = np.dot(rotation, [(c, s, 0), (-s, c, 0), (0, 0, 1)])
481 return rotation
484def givens(a, b):
485 """Solve the equation system::
487 [ c s] [a] [r]
488 [ ] . [ ] = [ ]
489 [-s c] [b] [0]
490 """
491 sgn = np.sign
492 if b == 0:
493 c = sgn(a)
494 s = 0
495 r = abs(a)
496 elif abs(b) >= abs(a):
497 cot = a / b
498 u = sgn(b) * (1 + cot**2) ** 0.5
499 s = 1.0 / u
500 c = s * cot
501 r = b * u
502 else:
503 tan = b / a
504 u = sgn(a) * (1 + tan**2) ** 0.5
505 c = 1.0 / u
506 s = c * tan
507 r = a * u
508 return c, s, r
511def irotate(rotation, initial=np.identity(3)):
512 """Determine x, y, z rotation angles from rotation matrix."""
513 a = np.dot(initial, rotation)
514 cx, sx, rx = givens(a[2, 2], a[1, 2])
515 cy, sy, _ry = givens(rx, a[0, 2])
516 cz, sz, _rz = givens(
517 cx * a[1, 1] - sx * a[2, 1],
518 cy * a[0, 1] - sy * (sx * a[1, 1] + cx * a[2, 1]),
519 )
520 x = degrees(atan2(sx, cx))
521 y = degrees(atan2(-sy, cy))
522 z = degrees(atan2(sz, cz))
523 return x, y, z
526def pbc2pbc(pbc):
527 newpbc = np.empty(3, bool)
528 newpbc[:] = pbc
529 return newpbc
532def string2index(stridx: str) -> int | slice | str:
533 """Convert index string to either int or slice"""
534 if ':' not in stridx:
535 # may contain database accessor
536 try:
537 return int(stridx)
538 except ValueError:
539 return stridx
540 i = [None if s == '' else int(s) for s in stridx.split(':')]
541 return slice(*i)
544def hsv2rgb(h, s, v):
545 """http://en.wikipedia.org/wiki/HSL_and_HSV
547 h (hue) in [0, 360[
548 s (saturation) in [0, 1]
549 v (value) in [0, 1]
551 return rgb in range [0, 1]
552 """
553 if v == 0:
554 return 0, 0, 0
555 if s == 0:
556 return v, v, v
558 i, f = divmod(h / 60.0, 1)
559 p = v * (1 - s)
560 q = v * (1 - s * f)
561 t = v * (1 - s * (1 - f))
563 if i == 0:
564 return v, t, p
565 elif i == 1:
566 return q, v, p
567 elif i == 2:
568 return p, v, t
569 elif i == 3:
570 return p, q, v
571 elif i == 4:
572 return t, p, v
573 elif i == 5:
574 return v, p, q
575 else:
576 raise RuntimeError('h must be in [0, 360]')
579def hsv(array, s=0.9, v=0.9):
580 array = (array + array.min()) * 359.0 / (array.max() - array.min())
581 result = np.empty((len(array.flat), 3))
582 for rgb, h in zip(result, array.flat):
583 rgb[:] = hsv2rgb(h, s, v)
584 return np.reshape(result, array.shape + (3,))
587# This code does the same, but requires pylab
588# def cmap(array, name='hsv'):
589# import pylab
590# a = (array + array.min()) / array.ptp()
591# rgba = getattr(pylab.cm, name)(a)
592# return rgba[:-1] # return rgb only (not alpha)
595def longsum(x):
596 """128-bit floating point sum."""
597 return float(np.asarray(x, dtype=np.longdouble).sum())
600@contextmanager
601def workdir(path, mkdir=False):
602 """Temporarily change, and optionally create, working directory."""
603 path = Path(path)
604 if mkdir:
605 path.mkdir(parents=True, exist_ok=True)
607 olddir = os.getcwd()
608 os.chdir(path)
609 try:
610 yield # Yield the Path or dirname maybe?
611 finally:
612 os.chdir(olddir)
615class iofunction:
616 """Decorate func so it accepts either str or file.
618 (Won't work on functions that return a generator.)"""
620 def __init__(self, mode):
621 self.mode = mode
623 def __call__(self, func):
624 @functools.wraps(func)
625 def iofunc(file, *args, **kwargs):
626 openandclose = isinstance(file, (str, PurePath))
627 fd = None
628 try:
629 if openandclose:
630 fd = open(str(file), self.mode)
631 else:
632 fd = file
633 obj = func(fd, *args, **kwargs)
634 return obj
635 finally:
636 if openandclose and fd is not None:
637 # fd may be None if open() failed
638 fd.close()
640 return iofunc
643def writer(func):
644 return iofunction('w')(func)
647def reader(func):
648 return iofunction('r')(func)
651# The next two functions are for hotplugging into a JSONable class
652# using the jsonable decorator. We are supposed to have this kind of stuff
653# in ase.io.jsonio, but we'd rather import them from a 'basic' module
654# like ase/utils than one which triggers a lot of extra (cyclic) imports.
657def write_json(self, fd):
658 """Write to JSON file."""
659 from ase.io.jsonio import write_json as _write_json
661 _write_json(fd, self)
664@classmethod # type: ignore[misc]
665def read_json(cls, fd):
666 """Read new instance from JSON file."""
667 from ase.io.jsonio import read_json as _read_json
669 obj = _read_json(fd)
670 assert isinstance(obj, cls)
671 return obj
674def jsonable(name):
675 """Decorator for facilitating JSON I/O with a class.
677 Pokes JSON-based read and write functions into the class.
679 In order to write an object to JSON, it needs to be a known simple type
680 (such as ndarray, float, ...) or implement todict(). If the class
681 defines a string called ase_objtype, the decoder will want to convert
682 the object back into its original type when reading."""
684 def jsonableclass(cls):
685 cls.ase_objtype = name
686 if not hasattr(cls, 'todict'):
687 raise TypeError('Class must implement todict()')
689 # We may want the write and read to be optional.
690 # E.g. a calculator might want to be JSONable, but not
691 # that .write() produces a JSON file.
692 #
693 # This is mostly for 'lightweight' object IO.
694 cls.write = write_json
695 cls.read = read_json
696 return cls
698 return jsonableclass
701class ExperimentalFeatureWarning(Warning):
702 pass
705def experimental(func):
706 """Decorator for functions not ready for production use."""
708 @functools.wraps(func)
709 def expfunc(*args, **kwargs):
710 warnings.warn(
711 'This function may change or misbehave: {}()'.format(
712 func.__qualname__
713 ),
714 ExperimentalFeatureWarning,
715 )
716 return func(*args, **kwargs)
718 return expfunc
721@deprecated('use functools.cached_property instead')
722def lazymethod(meth):
723 """Decorator for lazy evaluation and caching of data.
725 Example::
727 class MyClass:
729 @lazymethod
730 def thing(self):
731 return expensive_calculation()
733 The method body is only executed first time thing() is called, and
734 its return value is stored. Subsequent calls return the cached
735 value.
737 .. deprecated:: 3.25.0
738 """
739 name = meth.__name__
741 @functools.wraps(meth)
742 def getter(self):
743 try:
744 cache = self._lazy_cache
745 except AttributeError:
746 cache = self._lazy_cache = {}
748 if name not in cache:
749 cache[name] = meth(self)
750 return cache[name]
752 return getter
755def atoms_to_spglib_cell(atoms):
756 """Convert atoms into data suitable for calling spglib."""
757 return (
758 atoms.get_cell(),
759 atoms.get_scaled_positions(),
760 atoms.get_atomic_numbers(),
761 )
764def warn_legacy(feature_name):
765 warnings.warn(
766 f'The {feature_name} feature is untested and ASE developers do not '
767 'know whether it works or how to use it. Please rehabilitate it '
768 '(by writing unittests) or it may be removed.',
769 FutureWarning,
770 )
773@deprecated('use functools.cached_property instead')
774def lazyproperty(meth):
775 """Decorator like lazymethod, but making item available as a property.
777 .. deprecated:: 3.25.0
778 """
779 return property(lazymethod(meth))
782class _DelExitStack(ExitStack):
783 # We don't want IOContext itself to implement __del__, since IOContext
784 # might be subclassed, and we don't want __del__ on objects that we
785 # don't fully control. Therefore we make a little custom class
786 # that nobody else refers to, and that has the __del__.
787 def __del__(self):
788 self.close()
791class IOContext:
792 @functools.cached_property
793 def _exitstack(self):
794 return _DelExitStack()
796 def __enter__(self):
797 return self
799 def __exit__(self, *args):
800 self.close()
802 def closelater(self, fd):
803 return self._exitstack.enter_context(fd)
805 def close(self):
806 self._exitstack.close()
808 def openfile(self, file, comm, mode='w'):
809 if hasattr(file, 'close'):
810 return file # File already opened, not for us to close.
812 encoding = None if mode.endswith('b') else 'utf-8'
814 if file is None or comm.rank != 0:
815 return self.closelater(
816 open(os.devnull, mode=mode, encoding=encoding)
817 )
819 if file == '-':
820 return sys.stdout
822 return self.closelater(open(file, mode=mode, encoding=encoding))
825def get_python_package_path_description(
826 package, default='module has no path'
827) -> str:
828 """Helper to get path description of a python package/module
830 If path has multiple elements, the first one is returned.
831 If it is empty, the default is returned.
832 Exceptions are returned as strings default+(exception).
833 Always returns a string.
834 """
835 try:
836 p = list(package.__path__)
837 if p:
838 return str(p[0])
839 else:
840 return default
841 except Exception as ex:
842 return f'{default} ({ex})'
845class OldSpglibError(Exception):
846 pass
849def spglib_new_errorhandling(func):
850 def spglib_wrapper(*args, **kwargs):
851 # spglib<2.7.0 returns None when there is an error.
852 # spglib 2.7.0 warns that this will become exceptions in the future.
853 # We hack an environment setting to silence this warning and get the
854 # behaviour we want.
855 key = 'SPGLIB_OLD_ERROR_HANDLING'
856 orig_value = os.environ.get(key)
857 try:
858 os.environ[key] = 'false'
859 value = func(*args, **kwargs)
860 if value is None:
861 raise OldSpglibError()
862 return value
863 finally:
864 if orig_value is not None:
865 os.environ[key] = orig_value
867 return spglib_wrapper