Coverage for ase/spectrum/dosdata.py: 100.00%
153 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
1# Refactor of DOS-like data objects
2# towards replacing ase.dft.dos and ase.dft.pdos
3import warnings
4from abc import ABCMeta, abstractmethod
5from collections.abc import Sequence
6from typing import Any, TypeVar
8import numpy as np
9from matplotlib.axes import Axes
11from ase.utils.plotting import SimplePlottingAxes
13# For now we will be strict about Info and say it has to be str->str. Perhaps
14# later we will allow other types that have reliable comparison operations.
15Info = dict[str, str]
17# Still no good solution to type checking with arrays.
18Floats = Sequence[float] | np.ndarray
21class DOSData(metaclass=ABCMeta):
22 """Abstract base class for a single series of DOS-like data
24 Only the 'info' is a mutable attribute; DOS data is set at init"""
26 def __init__(self, info: Info | None = None) -> None:
27 if info is None:
28 self.info = {}
29 elif isinstance(info, dict):
30 self.info = info
31 else:
32 raise TypeError('Info must be a dict or None')
34 @abstractmethod
35 def get_energies(self) -> Floats:
36 """Get energy data stored in this object"""
38 @abstractmethod
39 def get_weights(self) -> Floats:
40 """Get DOS weights stored in this object"""
42 @abstractmethod
43 def copy(self) -> 'DOSData':
44 """Returns a copy in which info dict can be safely mutated"""
46 def _sample(
47 self, energies: Floats, width: float = 0.1, smearing: str = 'Gauss'
48 ) -> np.ndarray:
49 """Sample the DOS data at chosen points, with broadening
51 Note that no correction is made here for the sampling bin width; total
52 intensity will vary with sampling density.
54 Args:
55 energies: energy values for sampling
56 width: Width of broadening kernel
57 smearing: selection of broadening kernel (only "Gauss" is currently
58 supported)
60 Returns
61 -------
62 Weights sampled from a broadened DOS at values corresponding to x
63 """
65 self._check_positive_width(width)
66 weights_grid = np.zeros(len(energies), float)
67 weights = self.get_weights()
68 energies = np.asarray(energies, float)
70 for i, raw_energy in enumerate(self.get_energies()):
71 delta = self._delta(energies, raw_energy, width, smearing=smearing)
72 weights_grid += weights[i] * delta
73 return weights_grid
75 def _almost_equals(self, other: Any) -> bool:
76 """Compare with another DOSData for testing purposes"""
77 if not isinstance(other, type(self)):
78 return False
79 if self.info != other.info:
80 return False
81 if not np.allclose(self.get_weights(), other.get_weights()):
82 return False
83 return np.allclose(self.get_energies(), other.get_energies())
85 @staticmethod
86 def _delta(
87 x: np.ndarray, x0: float, width: float, smearing: str = 'Gauss'
88 ) -> np.ndarray:
89 """Return a delta-function centered at 'x0'.
91 This function is used with numpy broadcasting; if x is a row and x0 is
92 a column vector, the returned data will be a 2D array with each row
93 corresponding to a different delta center.
94 """
95 if smearing.lower() == 'gauss':
96 x1 = -0.5 * ((x - x0) / width) ** 2
97 return np.exp(x1) / (np.sqrt(2 * np.pi) * width)
98 else:
99 msg = 'Requested smearing type not recognized. Got {}'.format(
100 smearing
101 )
102 raise ValueError(msg)
104 @staticmethod
105 def _check_positive_width(width):
106 if width <= 0.0:
107 msg = 'Cannot add 0 or negative width smearing'
108 raise ValueError(msg)
110 def sample_grid(
111 self,
112 npts: int,
113 xmin: float | None = None,
114 xmax: float | None = None,
115 padding: float = 3,
116 width: float = 0.1,
117 smearing: str = 'Gauss',
118 ) -> 'GridDOSData':
119 """Sample the DOS data on an evenly-spaced energy grid
121 Args:
122 npts: Number of sampled points
123 xmin: Minimum sampled x value; if unspecified, a default is chosen
124 xmax: Maximum sampled x value; if unspecified, a default is chosen
125 padding: If xmin/xmax is unspecified, default value will be padded
126 by padding * width to avoid cutting off peaks.
127 width: Width of broadening kernel
128 smearing: selection of broadening kernel (only 'Gauss' is
129 implemented)
131 Returns
132 -------
133 (energy values, sampled DOS)
134 """
136 if xmin is None:
137 xmin = min(self.get_energies()) - (padding * width)
138 if xmax is None:
139 xmax = max(self.get_energies()) + (padding * width)
140 energies_grid = np.linspace(xmin, xmax, npts)
141 weights_grid = self._sample(
142 energies_grid, width=width, smearing=smearing
143 )
145 return GridDOSData(energies_grid, weights_grid, info=self.info.copy())
147 def plot(
148 self,
149 npts: int = 1000,
150 xmin: float | None = None,
151 xmax: float | None = None,
152 width: float = 0.1,
153 smearing: str = 'Gauss',
154 ax: Axes | None = None,
155 show: bool = False,
156 filename: str | None = None,
157 mplargs: dict | None = None,
158 ) -> Axes:
159 """Simple 1-D plot of DOS data, resampled onto a grid
161 If the special key 'label' is present in self.info, this will be set
162 as the label for the plotted line (unless overruled in mplargs). The
163 label is only seen if a legend is added to the plot (i.e. by calling
164 ``ax.legend()``).
166 Args:
167 npts, xmin, xmax: output data range, as passed to self.sample_grid
168 width: Width of broadening kernel for self.sample_grid()
169 smearing: selection of broadening kernel for self.sample_grid()
170 ax: existing Matplotlib axes object. If not provided, a new figure
171 with one set of axes will be created using Pyplot
172 show: show the figure on-screen
173 filename: if a path is given, save the figure to this file
174 mplargs: additional arguments to pass to matplotlib plot command
175 (e.g. {'linewidth': 2} for a thicker line).
178 Returns
179 -------
180 Plotting axes. If "ax" was set, this is the same object.
181 """
183 if mplargs is None:
184 mplargs = {}
185 if 'label' not in mplargs:
186 mplargs.update({'label': self.label_from_info(self.info)})
188 return self.sample_grid(
189 npts, xmin=xmin, xmax=xmax, width=width, smearing=smearing
190 ).plot(
191 ax=ax,
192 xmin=xmin,
193 xmax=xmax,
194 show=show,
195 filename=filename,
196 mplargs=mplargs,
197 )
199 @staticmethod
200 def label_from_info(info: dict[str, str]):
201 """Generate an automatic legend label from info dict"""
202 if 'label' in info:
203 return info['label']
204 else:
205 return '; '.join(map(lambda x: f'{x[0]}: {x[1]}', info.items()))
208class GeneralDOSData(DOSData):
209 """Base class for a single series of DOS-like data
211 Only the 'info' is a mutable attribute; DOS data is set at init
213 This is the base class for DOSData objects that accept/set seperate
214 "energies" and "weights" sequences of equal length at init.
216 """
218 def __init__(
219 self, energies: Floats, weights: Floats, info: Info | None = None
220 ) -> None:
221 super().__init__(info=info)
223 n_entries = len(energies)
224 if len(weights) != n_entries:
225 raise ValueError('Energies and weights must be the same length')
227 # Internally store the data as a np array with two rows; energy, weight
228 self._data = np.empty((2, n_entries), dtype=float, order='C')
229 self._data[0, :] = energies
230 self._data[1, :] = weights
232 def get_energies(self) -> np.ndarray:
233 return self._data[0, :].copy()
235 def get_weights(self) -> np.ndarray:
236 return self._data[1, :].copy()
238 D = TypeVar('D', bound='GeneralDOSData')
240 def copy(self: D) -> D: # noqa F821
241 return type(self)(
242 self.get_energies(), self.get_weights(), info=self.info.copy()
243 )
246class RawDOSData(GeneralDOSData):
247 """A collection of weighted delta functions which sum to form a DOS
249 This is an appropriate data container for density-of-states (DOS) or
250 spectral data where the energy data values not form a known regular
251 grid. The data may be plotted or resampled for further analysis using the
252 sample_grid() and plot() methods. Multiple weights at the same
253 energy value will *only* be combined in output data, and data stored in
254 RawDOSData is never resampled. A plot_deltas() function is also provided
255 which plots the raw data.
257 Metadata may be stored in the info dict, in which keys and values must be
258 strings. This data is used for selecting and combining multiple DOSData
259 objects in a DOSCollection object.
261 When RawDOSData objects are combined with the addition operator::
263 big_dos = raw_dos_1 + raw_dos_2
265 the energy and weights data is *concatenated* (i.e. combined without
266 sorting or replacement) and the new info dictionary consists of the
267 *intersection* of the inputs: only key-value pairs that were common to both
268 of the input objects will be retained in the new combined object. For
269 example::
271 (RawDOSData([x1], [y1], info={'symbol': 'O', 'index': '1'})
272 + RawDOSData([x2], [y2], info={'symbol': 'O', 'index': '2'}))
274 will yield the equivalent of::
276 RawDOSData([x1, x2], [y1, y2], info={'symbol': 'O'})
278 """
280 def __add__(self, other: 'RawDOSData') -> 'RawDOSData':
281 if not isinstance(other, RawDOSData):
282 raise TypeError(
283 'RawDOSData can only be combined with other RawDOSData objects'
284 )
286 # Take intersection of metadata (i.e. only common entries are retained)
287 new_info = dict(set(self.info.items()) & set(other.info.items()))
289 # Concatenate the energy/weight data
290 new_data = np.concatenate((self._data, other._data), axis=1)
292 new_object = RawDOSData([], [], info=new_info)
293 new_object._data = new_data
295 return new_object
297 def plot_deltas(
298 self,
299 ax: Axes | None = None,
300 show: bool = False,
301 filename: str | None = None,
302 mplargs: dict | None = None,
303 ) -> Axes:
304 """Simple plot of sparse DOS data as a set of delta functions
306 Items at the same x-value can overlap and will not be summed together
308 Args:
309 ax: existing Matplotlib axes object. If not provided, a new figure
310 with one set of axes will be created using Pyplot
311 show: show the figure on-screen
312 filename: if a path is given, save the figure to this file
313 mplargs: additional arguments to pass to matplotlib Axes.vlines
314 command (e.g. {'linewidth': 2} for a thicker line).
316 Returns
317 -------
318 Plotting axes. If "ax" was set, this is the same object.
319 """
321 if mplargs is None:
322 mplargs = {}
324 with SimplePlottingAxes(ax=ax, show=show, filename=filename) as ax:
325 ax.vlines(self.get_energies(), 0, self.get_weights(), **mplargs)
327 return ax
330class GridDOSData(GeneralDOSData):
331 """A collection of regularly-sampled data which represents a DOS
333 This is an appropriate data container for density-of-states (DOS) or
334 spectral data where the intensity values form a regular grid. This
335 is generally the result of sampling or integrating into discrete
336 bins, rather than a collection of unique states. The data may be
337 plotted or resampled for further analysis using the sample_grid()
338 and plot() methods.
340 Metadata may be stored in the info dict, in which keys and values must be
341 strings. This data is used for selecting and combining multiple DOSData
342 objects in a DOSCollection object.
344 When RawDOSData objects are combined with the addition operator::
346 big_dos = raw_dos_1 + raw_dos_2
348 the weights data is *summed* (requiring a consistent energy grid) and the
349 new info dictionary consists of the *intersection* of the inputs: only
350 key-value pairs that were common to both of the input objects will be
351 retained in the new combined object. For example::
353 (GridDOSData([0.1, 0.2, 0.3], [y1, y2, y3],
354 info={'symbol': 'O', 'index': '1'})
355 + GridDOSData([0.1, 0.2, 0.3], [y4, y5, y6],
356 info={'symbol': 'O', 'index': '2'}))
358 will yield the equivalent of::
360 GridDOSData([0.1, 0.2, 0.3], [y1+y4, y2+y5, y3+y6], info={'symbol': 'O'})
362 """
364 def __init__(
365 self, energies: Floats, weights: Floats, info: Info | None = None
366 ) -> None:
367 n_entries = len(energies)
368 if not np.allclose(
369 energies, np.linspace(energies[0], energies[-1], n_entries)
370 ):
371 raise ValueError('Energies must be an evenly-spaced 1-D grid')
373 if len(weights) != n_entries:
374 raise ValueError('Energies and weights must be the same length')
376 super().__init__(energies, weights, info=info)
377 self.sigma_cutoff = 3
379 def _check_spacing(self, width) -> float:
380 current_spacing = self._data[0, 1] - self._data[0, 0]
381 if width < (2 * current_spacing):
382 warnings.warn(
383 'The broadening width is small compared to the original '
384 'sampling density. The results are unlikely to be smooth.'
385 )
386 return current_spacing
388 def _sample(
389 self, energies: Floats, width: float = 0.1, smearing: str = 'Gauss'
390 ) -> np.ndarray:
391 current_spacing = self._check_spacing(width)
392 return (
393 super()._sample(energies=energies, width=width, smearing=smearing)
394 * current_spacing
395 )
397 def __add__(self, other: 'GridDOSData') -> 'GridDOSData':
398 # This method uses direct access to the mutable energy and weights data
399 # (self._data) to avoid redundant copying operations. The __init__
400 # method of GridDOSData will write this to a new array, so on this
401 # occasion it is safe to pass references to the mutable data.
403 if not isinstance(other, GridDOSData):
404 raise TypeError(
405 'GridDOSData can only be combined with other '
406 'GridDOSData objects'
407 )
408 if len(self._data[0, :]) != len(other.get_energies()):
409 raise ValueError(
410 'Cannot add GridDOSData objects with different-'
411 'length energy grids.'
412 )
414 if not np.allclose(self._data[0, :], other.get_energies()):
415 raise ValueError(
416 'Cannot add GridDOSData objects with different energy grids.'
417 )
419 # Take intersection of metadata (i.e. only common entries are retained)
420 new_info = dict(set(self.info.items()) & set(other.info.items()))
422 # Sum the energy/weight data
423 new_weights = self._data[1, :] + other.get_weights()
425 new_object = GridDOSData(self._data[0, :], new_weights, info=new_info)
426 return new_object
428 @staticmethod
429 def _interpret_smearing_args(
430 npts: int,
431 width: float | None = None,
432 default_npts: int = 1000,
433 default_width: float = 0.1,
434 ) -> tuple[int, float | None]:
435 """Figure out what the user intended: resample if width provided"""
436 if width is not None:
437 if npts:
438 return (npts, float(width))
439 else:
440 return (default_npts, float(width))
441 else:
442 if npts:
443 return (npts, default_width)
444 else:
445 return (0, None)
447 def plot(
448 self,
449 npts: int = 0,
450 xmin: float | None = None,
451 xmax: float | None = None,
452 width: float | None = None,
453 smearing: str = 'Gauss',
454 ax: Axes | None = None,
455 show: bool = False,
456 filename: str | None = None,
457 mplargs: dict | None = None,
458 ) -> Axes:
459 """Simple 1-D plot of DOS data
461 Data will be resampled onto a grid with `npts` points unless `npts` is
462 set to zero, in which case:
464 - no resampling takes place
465 - `width` and `smearing` are ignored
466 - `xmin` and `xmax` affect the axis limits of the plot, not the
467 underlying data.
469 If the special key 'label' is present in self.info, this will be set
470 as the label for the plotted line (unless overruled in mplargs). The
471 label is only seen if a legend is added to the plot (i.e. by calling
472 ``ax.legend()``).
474 Args:
475 npts, xmin, xmax: output data range, as passed to self.sample_grid
476 width: Width of broadening kernel, passed to self.sample_grid().
477 If no npts was set but width is set, npts will be set to 1000.
478 smearing: selection of broadening kernel for self.sample_grid()
479 ax: existing Matplotlib axes object. If not provided, a new figure
480 with one set of axes will be created using Pyplot
481 show: show the figure on-screen
482 filename: if a path is given, save the figure to this file
483 mplargs: additional arguments to pass to matplotlib plot command
484 (e.g. {'linewidth': 2} for a thicker line).
486 Returns
487 -------
488 Plotting axes. If "ax" was set, this is the same object.
489 """
491 npts, width = self._interpret_smearing_args(npts, width)
493 if mplargs is None:
494 mplargs = {}
495 if 'label' not in mplargs:
496 mplargs.update({'label': self.label_from_info(self.info)})
498 if npts:
499 assert isinstance(width, float)
500 dos = self.sample_grid(
501 npts, xmin=xmin, xmax=xmax, width=width, smearing=smearing
502 )
503 else:
504 dos = self
506 energies, intensity = dos.get_energies(), dos.get_weights()
508 with SimplePlottingAxes(ax=ax, show=show, filename=filename) as ax:
509 ax.plot(energies, intensity, **mplargs)
510 ax.set_xlim(left=xmin, right=xmax)
512 return ax