Coverage for ase/spectrum/doscollection.py: 100.00%

178 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import collections 

2from collections.abc import Iterable, Sequence 

3from functools import reduce, singledispatch 

4from typing import ( 

5 Any, 

6 TypeVar, 

7 overload, 

8) 

9 

10import numpy as np 

11from matplotlib.axes import Axes 

12 

13from ase.spectrum.dosdata import DOSData, Floats, GridDOSData, Info, RawDOSData 

14from ase.utils.plotting import SimplePlottingAxes 

15 

16 

17class DOSCollection(collections.abc.Sequence): 

18 """Base class for a collection of DOSData objects""" 

19 

20 def __init__(self, dos_series: Iterable[DOSData]) -> None: 

21 self._data = list(dos_series) 

22 

23 def _sample( 

24 self, energies: Floats, width: float = 0.1, smearing: str = 'Gauss' 

25 ) -> np.ndarray: 

26 """Sample the DOS data at chosen points, with broadening 

27 

28 This samples the underlying DOS data in the same way as the .sample() 

29 method of those DOSData items, returning a 2-D array with columns 

30 corresponding to x and rows corresponding to the collected data series. 

31 

32 Args: 

33 energies: energy values for sampling 

34 width: Width of broadening kernel 

35 smearing: selection of broadening kernel (only "Gauss" is currently 

36 supported) 

37 

38 Returns 

39 ------- 

40 Weights sampled from a broadened DOS at values corresponding to x, 

41 in rows corresponding to DOSData entries contained in this object 

42 """ 

43 

44 if len(self) == 0: 

45 raise IndexError('No data to sample') 

46 

47 return np.asarray( 

48 [ 

49 data._sample(energies, width=width, smearing=smearing) 

50 for data in self 

51 ] 

52 ) 

53 

54 def plot( 

55 self, 

56 npts: int = 1000, 

57 xmin: float | None = None, 

58 xmax: float | None = None, 

59 width: float = 0.1, 

60 smearing: str = 'Gauss', 

61 ax: Axes | None = None, 

62 show: bool = False, 

63 filename: str | None = None, 

64 mplargs: dict | None = None, 

65 ) -> Axes: 

66 """Simple plot of collected DOS data, resampled onto a grid 

67 

68 If the special key 'label' is present in self.info, this will be set 

69 as the label for the plotted line (unless overruled in mplargs). The 

70 label is only seen if a legend is added to the plot (i.e. by calling 

71 `ax.legend()`). 

72 

73 Args: 

74 npts, xmin, xmax: output data range, as passed to self.sample_grid 

75 width: Width of broadening kernel, passed to self.sample_grid() 

76 smearing: selection of broadening kernel for self.sample_grid() 

77 ax: existing Matplotlib axes object. If not provided, a new figure 

78 with one set of axes will be created using Pyplot 

79 show: show the figure on-screen 

80 filename: if a path is given, save the figure to this file 

81 mplargs: additional arguments to pass to matplotlib plot command 

82 (e.g. {'linewidth': 2} for a thicker line). 

83 

84 Returns 

85 ------- 

86 Plotting axes. If "ax" was set, this is the same object. 

87 """ 

88 return self.sample_grid( 

89 npts, xmin=xmin, xmax=xmax, width=width, smearing=smearing 

90 ).plot( 

91 npts=npts, 

92 xmin=xmin, 

93 xmax=xmax, 

94 width=width, 

95 smearing=smearing, 

96 ax=ax, 

97 show=show, 

98 filename=filename, 

99 mplargs=mplargs, 

100 ) 

101 

102 def sample_grid( 

103 self, 

104 npts: int, 

105 xmin: float | None = None, 

106 xmax: float | None = None, 

107 padding: float = 3, 

108 width: float = 0.1, 

109 smearing: str = 'Gauss', 

110 ) -> 'GridDOSCollection': 

111 """Sample the DOS data on an evenly-spaced energy grid 

112 

113 Args: 

114 npts: Number of sampled points 

115 xmin: Minimum sampled energy value; if unspecified, a default is 

116 chosen 

117 xmax: Maximum sampled energy value; if unspecified, a default is 

118 chosen 

119 padding: If xmin/xmax is unspecified, default value will be padded 

120 by padding * width to avoid cutting off peaks. 

121 width: Width of broadening kernel, passed to self.sample_grid() 

122 smearing: selection of broadening kernel, for self.sample_grid() 

123 

124 Returns 

125 ------- 

126 (energy values, sampled DOS) 

127 """ 

128 if len(self) == 0: 

129 raise IndexError('No data to sample') 

130 

131 if xmin is None: 

132 xmin = min(min(data.get_energies()) for data in self) - ( 

133 padding * width 

134 ) 

135 if xmax is None: 

136 xmax = max(max(data.get_energies()) for data in self) + ( 

137 padding * width 

138 ) 

139 

140 return GridDOSCollection( 

141 [ 

142 data.sample_grid( 

143 npts, xmin=xmin, xmax=xmax, width=width, smearing=smearing 

144 ) 

145 for data in self 

146 ] 

147 ) 

148 

149 @classmethod 

150 def from_data( 

151 cls, 

152 energies: Floats, 

153 weights: Sequence[Floats], 

154 info: Sequence[Info] | None = None, 

155 ) -> 'DOSCollection': 

156 """Create a DOSCollection from data sharing a common set of energies 

157 

158 This is a convenience method to be used when all the DOS data in the 

159 collection has a common energy axis. There is no performance advantage 

160 in using this method for the generic DOSCollection, but for 

161 GridDOSCollection it is more efficient. 

162 

163 Args: 

164 energy: common set of energy values for input data 

165 weights: array of DOS weights with rows corresponding to different 

166 datasets 

167 info: sequence of info dicts corresponding to weights rows. 

168 

169 Returns 

170 ------- 

171 Collection of DOS data (in RawDOSData format) 

172 """ 

173 

174 info = cls._check_weights_and_info(weights, info) 

175 

176 return cls( 

177 RawDOSData(energies, row_weights, row_info) 

178 for row_weights, row_info in zip(weights, info) 

179 ) 

180 

181 @staticmethod 

182 def _check_weights_and_info( 

183 weights: Sequence[Floats], 

184 info: Sequence[Info] | None, 

185 ) -> Sequence[Info]: 

186 if info is None: 

187 info = [{} for _ in range(len(weights))] 

188 else: 

189 if len(info) != len(weights): 

190 raise ValueError( 

191 'Length of info must match number of rows in weights' 

192 ) 

193 return info 

194 

195 @overload 

196 def __getitem__(self, item: int) -> DOSData: ... 

197 

198 @overload # noqa F811 

199 def __getitem__(self, item: slice) -> 'DOSCollection': # noqa F811 

200 ... 

201 

202 def __getitem__(self, item): # noqa F811 

203 if isinstance(item, int): 

204 return self._data[item] 

205 elif isinstance(item, slice): 

206 return type(self)(self._data[item]) 

207 else: 

208 raise TypeError( 

209 'index in DOSCollection must be an integer or slice' 

210 ) 

211 

212 def __len__(self) -> int: 

213 return len(self._data) 

214 

215 def _almost_equals(self, other: Any) -> bool: 

216 """Compare with another DOSCollection for testing purposes""" 

217 if not isinstance(other, type(self)): 

218 return False 

219 elif len(self) != len(other): 

220 return False 

221 else: 

222 return all(a._almost_equals(b) for a, b in zip(self, other)) 

223 

224 def total(self) -> DOSData: 

225 """Sum all the DOSData in this Collection and label it as 'Total'""" 

226 data = self.sum_all() 

227 data.info.update({'label': 'Total'}) 

228 return data 

229 

230 def sum_all(self) -> DOSData: 

231 """Sum all the DOSData contained in this Collection""" 

232 if len(self) == 0: 

233 raise IndexError('No data to sum') 

234 elif len(self) == 1: 

235 data = self[0].copy() 

236 else: 

237 data = reduce(lambda x, y: x + y, self) 

238 return data 

239 

240 D = TypeVar('D', bound=DOSData) 

241 

242 @staticmethod 

243 def _select_to_list( 

244 dos_collection: Sequence[D], # Bug in flakes 

245 info_selection: dict[str, str], # misses 'D' def 

246 negative: bool = False, 

247 ) -> list[D]: # noqa: F821 

248 query = set(info_selection.items()) 

249 

250 if negative: 

251 return [ 

252 data 

253 for data in dos_collection 

254 if not query.issubset(set(data.info.items())) 

255 ] 

256 else: 

257 return [ 

258 data 

259 for data in dos_collection 

260 if query.issubset(set(data.info.items())) 

261 ] 

262 

263 def select(self, **info_selection: str) -> 'DOSCollection': 

264 """Narrow DOSCollection to items with specified info 

265 

266 For example, if :: 

267 

268 dc = DOSCollection([DOSData(x1, y1, info={'a': '1', 'b': '1'}), 

269 DOSData(x2, y2, info={'a': '2', 'b': '1'})]) 

270 

271 then :: 

272 

273 dc.select(b='1') 

274 

275 will return an identical object to dc, while :: 

276 

277 dc.select(a='1') 

278 

279 will return a DOSCollection with only the first item and :: 

280 

281 dc.select(a='2', b='1') 

282 

283 will return a DOSCollection with only the second item. 

284 

285 """ 

286 

287 matches = self._select_to_list(self, info_selection) 

288 return type(self)(matches) 

289 

290 def select_not(self, **info_selection: str) -> 'DOSCollection': 

291 """Narrow DOSCollection to items without specified info 

292 

293 For example, if :: 

294 

295 dc = DOSCollection([DOSData(x1, y1, info={'a': '1', 'b': '1'}), 

296 DOSData(x2, y2, info={'a': '2', 'b': '1'})]) 

297 

298 then :: 

299 

300 dc.select_not(b='2') 

301 

302 will return an identical object to dc, while :: 

303 

304 dc.select_not(a='2') 

305 

306 will return a DOSCollection with only the first item and :: 

307 

308 dc.select_not(a='1', b='1') 

309 

310 will return a DOSCollection with only the second item. 

311 

312 """ 

313 matches = self._select_to_list(self, info_selection, negative=True) 

314 return type(self)(matches) 

315 

316 # Use typehint *info_keys: str from python3.11+ 

317 def sum_by(self, *info_keys) -> 'DOSCollection': 

318 """Return a DOSCollection with some data summed by common attributes 

319 

320 For example, if :: 

321 

322 dc = DOSCollection([DOSData(x1, y1, info={'a': '1', 'b': '1'}), 

323 DOSData(x2, y2, info={'a': '2', 'b': '1'}), 

324 DOSData(x3, y3, info={'a': '2', 'b': '2'})]) 

325 

326 then :: 

327 

328 dc.sum_by('b') 

329 

330 will return a collection equivalent to :: 

331 

332 DOSCollection([DOSData(x1, y1, info={'a': '1', 'b': '1'}) 

333 + DOSData(x2, y2, info={'a': '2', 'b': '1'}), 

334 DOSData(x3, y3, info={'a': '2', 'b': '2'})]) 

335 

336 where the resulting contained DOSData have info attributes of 

337 {'b': '1'} and {'b': '2'} respectively. 

338 

339 dc.sum_by('a', 'b') on the other hand would return the full three-entry 

340 collection, as none of the entries have common 'a' *and* 'b' info. 

341 

342 """ 

343 

344 def _matching_info_tuples(data: DOSData): 

345 """Get relevent dict entries in tuple form 

346 

347 e.g. if data.info = {'a': 1, 'b': 2, 'c': 3} 

348 and info_keys = ('a', 'c') 

349 

350 then return (('a', 1), ('c': 3)) 

351 """ 

352 matched_keys = set(info_keys) & set(data.info) 

353 return tuple( 

354 sorted([(key, data.info[key]) for key in matched_keys]) 

355 ) 

356 

357 # Sorting inside info matching helps set() to remove redundant matches; 

358 # combos are then sorted() to ensure consistent output across sessions. 

359 all_combos = map(_matching_info_tuples, self) 

360 unique_combos = sorted(set(all_combos)) 

361 

362 # For each key/value combination, perform a select() to obtain all 

363 # the matching entries and sum them together. 

364 collection_data = [ 

365 self.select(**dict(combo)).sum_all() for combo in unique_combos 

366 ] 

367 return type(self)(collection_data) 

368 

369 def __add__(self, other: 'DOSCollection | DOSData') -> 'DOSCollection': 

370 """Join entries between two DOSCollection objects of the same type 

371 

372 It is also possible to add a single DOSData object without wrapping it 

373 in a new collection: i.e. :: 

374 

375 DOSCollection([dosdata1]) + DOSCollection([dosdata2]) 

376 

377 or :: 

378 

379 DOSCollection([dosdata1]) + dosdata2 

380 

381 will return :: 

382 

383 DOSCollection([dosdata1, dosdata2]) 

384 

385 """ 

386 return _add_to_collection(other, self) 

387 

388 

389@singledispatch 

390def _add_to_collection( 

391 other: DOSData | DOSCollection, collection: DOSCollection 

392) -> DOSCollection: 

393 if isinstance(other, type(collection)): 

394 return type(collection)(list(collection) + list(other)) 

395 elif isinstance(other, DOSCollection): 

396 raise TypeError( 

397 'Only DOSCollection objects of the same type may ' 

398 "be joined with '+'." 

399 ) 

400 else: 

401 raise TypeError( 

402 'DOSCollection may only be joined to DOSData or ' 

403 "DOSCollection objects with '+'." 

404 ) 

405 

406 

407@_add_to_collection.register(DOSData) 

408def _add_data(other: DOSData, collection: DOSCollection) -> DOSCollection: 

409 """Return a new DOSCollection with an additional DOSData item""" 

410 return type(collection)(list(collection) + [other]) 

411 

412 

413class RawDOSCollection(DOSCollection): 

414 def __init__(self, dos_series: Iterable[RawDOSData]) -> None: 

415 super().__init__(dos_series) 

416 for dos_data in self: 

417 if not isinstance(dos_data, RawDOSData): 

418 raise TypeError( 

419 'RawDOSCollection can only store RawDOSData objects.' 

420 ) 

421 

422 

423class GridDOSCollection(DOSCollection): 

424 def __init__( 

425 self, dos_series: Iterable[GridDOSData], energies: Floats | None = None 

426 ) -> None: 

427 dos_list = list(dos_series) 

428 if energies is None: 

429 if len(dos_list) == 0: 

430 raise ValueError( 

431 'Must provide energies to create a ' 

432 'GridDOSCollection without any DOS data.' 

433 ) 

434 self._energies = dos_list[0].get_energies() 

435 else: 

436 self._energies = np.asarray(energies) 

437 

438 self._weights: np.ndarray = np.empty( 

439 (len(dos_list), len(self._energies)), 

440 float, 

441 ) 

442 self._info = [] 

443 

444 for i, dos_data in enumerate(dos_list): 

445 if not isinstance(dos_data, GridDOSData): 

446 raise TypeError( 

447 'GridDOSCollection can only store GridDOSData objects.' 

448 ) 

449 if ( 

450 dos_data.get_energies().shape != self._energies.shape 

451 or not np.allclose(dos_data.get_energies(), self._energies) 

452 ): 

453 raise ValueError( 

454 'All GridDOSData objects in GridDOSCollection' 

455 ' must have the same energy axis.' 

456 ) 

457 self._weights[i, :] = dos_data.get_weights() 

458 self._info.append(dos_data.info) 

459 

460 def get_energies(self) -> Floats: 

461 return self._energies.copy() 

462 

463 def get_all_weights(self) -> Sequence[Floats] | np.ndarray: 

464 return self._weights.copy() 

465 

466 def __len__(self) -> int: 

467 return self._weights.shape[0] 

468 

469 @overload # noqa F811 

470 def __getitem__(self, item: int) -> DOSData: ... 

471 

472 @overload # noqa F811 

473 def __getitem__(self, item: slice) -> 'GridDOSCollection': # noqa F811 

474 ... 

475 

476 def __getitem__(self, item): # noqa F811 

477 if isinstance(item, int): 

478 return GridDOSData( 

479 self._energies, self._weights[item, :], info=self._info[item] 

480 ) 

481 elif isinstance(item, slice): 

482 return type(self)([self[i] for i in range(len(self))[item]]) 

483 else: 

484 raise TypeError( 

485 'index in DOSCollection must be an integer or slice' 

486 ) 

487 

488 @classmethod 

489 def from_data( 

490 cls, 

491 energies: Floats, 

492 weights: Sequence[Floats], 

493 info: Sequence[Info] | None = None, 

494 ) -> 'GridDOSCollection': 

495 """Create a GridDOSCollection from data with a common set of energies 

496 

497 This convenience method may also be more efficient as it limits 

498 redundant copying/checking of the data. 

499 

500 Args: 

501 energies: common set of energy values for input data 

502 weights: array of DOS weights with rows corresponding to different 

503 datasets 

504 info: sequence of info dicts corresponding to weights rows. 

505 

506 Returns 

507 ------- 

508 Collection of DOS data (in RawDOSData format) 

509 """ 

510 

511 weights_array = np.asarray(weights, dtype=float) 

512 if len(weights_array.shape) != 2: 

513 raise IndexError('Weights must be a 2-D array or nested sequence') 

514 if weights_array.shape[0] < 1: 

515 raise IndexError('Weights cannot be empty') 

516 if weights_array.shape[1] != len(energies): 

517 raise IndexError('Length of weights rows must equal size of x') 

518 

519 info = cls._check_weights_and_info(weights, info) 

520 

521 dos_collection = cls([GridDOSData(energies, weights_array[0])]) 

522 dos_collection._weights = weights_array 

523 dos_collection._info = list(info) 

524 

525 return dos_collection 

526 

527 def select(self, **info_selection: str) -> 'DOSCollection': 

528 """Narrow GridDOSCollection to items with specified info 

529 

530 For example, if :: 

531 

532 dc = GridDOSCollection([GridDOSData(x, y1, 

533 info={'a': '1', 'b': '1'}), 

534 GridDOSData(x, y2, 

535 info={'a': '2', 'b': '1'})]) 

536 

537 then :: 

538 

539 dc.select(b='1') 

540 

541 will return an identical object to dc, while :: 

542 

543 dc.select(a='1') 

544 

545 will return a DOSCollection with only the first item and :: 

546 

547 dc.select(a='2', b='1') 

548 

549 will return a DOSCollection with only the second item. 

550 

551 """ 

552 

553 matches = self._select_to_list(self, info_selection) 

554 if len(matches) == 0: 

555 return type(self)([], energies=self._energies) 

556 else: 

557 return type(self)(matches) 

558 

559 def select_not(self, **info_selection: str) -> 'DOSCollection': 

560 """Narrow GridDOSCollection to items without specified info 

561 

562 For example, if :: 

563 

564 dc = GridDOSCollection([GridDOSData(x, y1, 

565 info={'a': '1', 'b': '1'}), 

566 GridDOSData(x, y2, 

567 info={'a': '2', 'b': '1'})]) 

568 

569 then :: 

570 

571 dc.select_not(b='2') 

572 

573 will return an identical object to dc, while :: 

574 

575 dc.select_not(a='2') 

576 

577 will return a DOSCollection with only the first item and :: 

578 

579 dc.select_not(a='1', b='1') 

580 

581 will return a DOSCollection with only the second item. 

582 

583 """ 

584 matches = self._select_to_list(self, info_selection, negative=True) 

585 if len(matches) == 0: 

586 return type(self)([], energies=self._energies) 

587 else: 

588 return type(self)(matches) 

589 

590 def plot( 

591 self, 

592 npts: int = 0, 

593 xmin: float | None = None, 

594 xmax: float | None = None, 

595 width: float | None = None, 

596 smearing: str = 'Gauss', 

597 ax: Axes | None = None, 

598 show: bool = False, 

599 filename: str | None = None, 

600 mplargs: dict | None = None, 

601 ) -> Axes: 

602 """Simple plot of collected DOS data, resampled onto a grid 

603 

604 If the special key 'label' is present in self.info, this will be set 

605 as the label for the plotted line (unless overruled in mplargs). The 

606 label is only seen if a legend is added to the plot (i.e. by calling 

607 `ax.legend()`). 

608 

609 Args: 

610 npts: 

611 Number of points in resampled x-axis. If set to zero (default), 

612 no resampling is performed and the stored data is plotted 

613 directly. 

614 xmin, xmax: 

615 output data range; this limits the resampling range as well as 

616 the plotting output 

617 width: Width of broadening kernel, passed to self.sample() 

618 smearing: selection of broadening kernel, passed to self.sample() 

619 ax: existing Matplotlib axes object. If not provided, a new figure 

620 with one set of axes will be created using Pyplot 

621 show: show the figure on-screen 

622 filename: if a path is given, save the figure to this file 

623 mplargs: additional arguments to pass to matplotlib plot command 

624 (e.g. {'linewidth': 2} for a thicker line). 

625 

626 Returns 

627 ------- 

628 Plotting axes. If "ax" was set, this is the same object. 

629 """ 

630 

631 # Apply defaults if necessary 

632 npts, width = GridDOSData._interpret_smearing_args(npts, width) 

633 

634 if npts: 

635 assert isinstance(width, float) 

636 dos = self.sample_grid( 

637 npts, xmin=xmin, xmax=xmax, width=width, smearing=smearing 

638 ) 

639 else: 

640 dos = self 

641 

642 energies, all_y = dos._energies, dos._weights 

643 

644 all_labels = [DOSData.label_from_info(data.info) for data in self] 

645 

646 with SimplePlottingAxes(ax=ax, show=show, filename=filename) as ax: 

647 self._plot_broadened(ax, energies, all_y, all_labels, mplargs) 

648 

649 return ax 

650 

651 @staticmethod 

652 def _plot_broadened( 

653 ax: Axes, 

654 energies: Floats, 

655 all_y: np.ndarray, 

656 all_labels: Sequence[str], 

657 mplargs: dict | None, 

658 ): 

659 """Plot DOS data with labels to axes 

660 

661 This is separated into another function so that subclasses can 

662 manipulate broadening, labels etc in their plot() method.""" 

663 if mplargs is None: 

664 mplargs = {} 

665 

666 all_lines = ax.plot(energies, all_y.T, **mplargs) 

667 for line, label in zip(all_lines, all_labels): 

668 line.set_label(label) 

669 ax.legend() 

670 

671 ax.set_xlim(left=min(energies), right=max(energies)) 

672 ax.set_ylim(bottom=0)