Coverage for dynasor/correlation_functions.py: 98%

303 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-09 14:30 +0000

1from itertools import combinations_with_replacement 

2from typing import Optional 

3 

4import numba 

5import numpy as np 

6from ase import Atoms 

7from numpy.typing import NDArray 

8 

9from dynasor.compute_config import get_compute_config 

10from dynasor.logging_tools import logger, warn_if_numba_threading_layer_is_slow 

11from dynasor.trajectory import Trajectory, WindowIterator 

12from dynasor.trajectory.prefetch import (_drop_frames_outside_windows, 

13 _prefetch_batched_iter) 

14from dynasor.sample import DynamicSample, StaticSample 

15 

16from dynasor.tools.acfs import psd_from_acf_2d 

17from dynasor.core.time_averager import TimeAverager, truncate_nans 

18from dynasor.core.reciprocal import _calc_rho_q_incoherent 

19from dynasor.core.frame_processors import get_frame_processor 

20from dynasor.qpoints.lattice import is_qpoint_commensurate 

21from dynasor.tools.structures import get_offset_index 

22from dynasor.units import Dalton_to_dmu, radians_per_fs_to_meV 

23 

24 

25def _validate_qpoints_commensurate(q_points: NDArray[float], cell: NDArray[float]) -> None: 

26 """Raise if any q-point is not commensurate with the simulation cell.""" 

27 n_bad = sum(not is_qpoint_commensurate(q, cell) for q in q_points) 

28 if n_bad > 0: 

29 raise ValueError( 

30 f'{n_bad} of {len(q_points)} q-points are not commensurate with the cell; use ' 

31 'get_spherical_qpoints or get_supercell_qpoints_along_path to generate ' 

32 'commensurate q-points.') 

33 

34 

35def compute_dynamic_structure_factors( 

36 traj: Trajectory, 

37 q_points: NDArray[float], 

38 dt: float, 

39 window_size: int, 

40 window_step: Optional[int] = 1, 

41 calculate_currents: Optional[bool] = False, 

42 calculate_incoherent: Optional[bool] = False, 

43 logging_interval: Optional[int] = 1000, 

44) -> DynamicSample: 

45 r"""Compute the dynamic structure factors. The results are returned in the 

46 form of a :class:`DynamicSample <dynasor.sample.DynamicSample>` 

47 object. 

48 

49 The computational backend and precision are set globally via 

50 :func:`set_compute_config <dynasor.set_compute_config>`, not as parameters of this 

51 function; see :ref:`the backends reference page <backends>` for details, including 

52 which parts of this calculation the GPU backends do (and do not) accelerate. 

53 

54 Parameters 

55 ---------- 

56 traj 

57 Input trajectory. 

58 q_points 

59 Array of q-points in units of rad/Å with shape ``(N_qpoints, 3)`` in Cartesian coordinates. 

60 dt 

61 Time difference in femtoseconds between two consecutive snapshots 

62 in the trajectory. Note that you should *not* change :attr:`dt` if you change 

63 :attr:`frame_step <dynasor.Trajectory.frame_step>` in :attr:`traj`. 

64 window_size 

65 Maximum time lag, expressed as a number of frame intervals, for which to calculate 

66 correlations. Each calculation window therefore contains ``window_size + 1`` frames, 

67 including the frame at time lag zero. This parameter determines the smallest frequency 

68 resolved. 

69 window_step 

70 Window step (or stride) given as the number of frames between consecutive trajectory 

71 windows. This parameter does *not* affect the time between consecutive frames in the 

72 calculation. If :attr:`window_step` > :attr:`window_size` + 1, some frames will not be 

73 used. 

74 calculate_currents 

75 Calculate the current correlations. Requires velocities to be available in :attr:`traj`. 

76 calculate_incoherent 

77 Calculate the incoherent part (self-part) of :math:`F_\text{incoh}`. Always evaluated on 

78 CPU via the Numba kernel, regardless of the configured backend (see 

79 :func:`set_compute_config <dynasor.set_compute_config>`). 

80 logging_interval 

81 Log progress at ``INFO`` level every this many windows. Set to ``0`` to disable 

82 progress logging. 

83 """ 

84 # sanity check input args 

85 if q_points.ndim != 2 or q_points.shape[1] != 3: 

86 raise ValueError('q-points array has the wrong shape.') 

87 if dt <= 0: 

88 raise ValueError(f'dt must be positive: dt= {dt}') 

89 if window_size <= 2: 

90 raise ValueError(f'window_size must be larger than 2: window_size= {window_size}') 

91 if window_step <= 0: 

92 raise ValueError(f'window_step must be positive: window_step= {window_step}') 

93 if not traj.has_positions: 

94 raise ValueError('compute_dynamic_structure_factors requires positions to be available ' 

95 'in the trajectory, but traj does not provide positions.') 

96 if calculate_currents and not traj.has_velocities: 

97 raise ValueError('calculate_currents=True requires velocities to be available in the ' 

98 'trajectory, but traj does not provide velocities.') 

99 _validate_qpoints_commensurate(q_points, traj.cell) 

100 

101 # define internal parameters 

102 n_qpoints = q_points.shape[0] 

103 delta_t = traj.frame_step * dt 

104 N_tc = window_size + 1 

105 

106 # log all setup information 

107 n_fft = 2 * window_size + 1 

108 dw = 2 * np.pi / (n_fft * delta_t) 

109 w_max = window_size * dw 

110 w_N = np.pi / delta_t 

111 dw_mev = dw * radians_per_fs_to_meV 

112 w_max_mev = w_max * radians_per_fs_to_meV 

113 w_N_mev = w_N * radians_per_fs_to_meV 

114 logger.info(f'Spacing between samples (frame_step): {traj.frame_step}') 

115 logger.info(f'Time between consecutive frames in input trajectory (dt): {dt} fs') 

116 logger.info(f'Time between consecutive frames used (dt * frame_step): {delta_t} fs') 

117 logger.info(f'Time window size (dt * frame_step * window_size): {delta_t * window_size:.1f} fs') 

118 logger.info(f'Angular frequency resolution: dw = {dw:.6f} rad/fs = {dw_mev:.3f} meV') 

119 logger.info(f'Maximum angular frequency: {w_max:.6f} rad/fs = {w_max_mev:.3f} meV ' 

120 f'(Nyquist limit: {w_N:.6f} rad/fs = {w_N_mev:.3f} meV)') 

121 

122 if calculate_currents: 

123 logger.info('Calculating current (velocity) correlations') 

124 if calculate_incoherent: 

125 logger.info('Calculating incoherent part (self-part) of correlations') 

126 

127 # log some info regarding q-points 

128 logger.info(f'Number of q-points: {n_qpoints}') 

129 

130 q_directions = q_points.astype(float, copy=True) 

131 q_distances = np.linalg.norm(q_points, axis=1) 

132 nonzero = q_distances > 0 

133 q_directions[nonzero] /= q_distances[nonzero].reshape(-1, 1) 

134 

135 # setup functions to process frames 

136 compute_config = get_compute_config() 

137 backend = compute_config.backend 

138 precision = compute_config.precision 

139 gpu_batch_size = compute_config.batch_size 

140 

141 is_batched, processor = get_frame_processor( 

142 q_points, backend, precision, gpu_batch_size, 

143 calculate_currents=calculate_currents, q_directions=q_directions) 

144 

145 # Build the frame source and window iterator. 

146 # GPU: batching + background prefetch thread (processor reads B frames, 

147 # GPU-processes them, and queues results while the main thread runs 

148 # calc_corr on the previous window). 

149 # Numba: standard per-frame element_processor inside WindowIterator. 

150 if is_batched: 150 ↛ 155line 150 didn't jump to line 155 because the condition on line 150 was never true

151 # The batched processor runs ahead of the window iterator, so frames 

152 # that fall between two windows have to be dropped here; skipping them 

153 # in the window iterator would leave them already transformed. What 

154 # remains is one group of N_tc frames per window, hence the step. 

155 if window_step >= N_tc: 

156 raw_frames = _drop_frames_outside_windows(traj, N_tc, window_step) 

157 iterator_step = N_tc 

158 else: 

159 raw_frames = traj 

160 iterator_step = window_step 

161 _frame_source = _prefetch_batched_iter(raw_frames, processor, batch_size=gpu_batch_size) 

162 window_iterator = WindowIterator(_frame_source, width=N_tc, window_step=iterator_step) 

163 else: 

164 window_iterator = WindowIterator(traj, width=N_tc, window_step=window_step, 

165 element_processor=processor) 

166 

167 # define all atom types and pairs 

168 atom_types = traj.atom_types 

169 pairs = list(combinations_with_replacement(atom_types, r=2)) 

170 particle_counts = {key: len(val) for key, val in traj.atomic_indices.items()} 

171 logger.debug('Considering pairs:') 

172 for pair in pairs: 

173 logger.debug(f' {pair}') 

174 

175 # set up all time averager instances 

176 F_q_t_averager = dict() 

177 for pair in pairs: 

178 F_q_t_averager[pair] = TimeAverager(N_tc, n_qpoints) 

179 if calculate_currents: 

180 Cl_q_t_averager = dict() 

181 Ct_q_t_averager = dict() 

182 for pair in pairs: 

183 Cl_q_t_averager[pair] = TimeAverager(N_tc, n_qpoints) 

184 Ct_q_t_averager[pair] = TimeAverager(N_tc, n_qpoints) 

185 if calculate_incoherent: 

186 F_s_q_t_averager = dict() 

187 for pair in atom_types: 

188 F_s_q_t_averager[pair] = TimeAverager(N_tc, n_qpoints) 

189 incoherent_displacements = dict() 

190 incoherent_rho = dict() 

191 

192 # define correlation function 

193 def calc_corr(window, time_i): 

194 # Calculate correlations between two frames in the window without normalization 1/N 

195 f0 = window[0] 

196 fi = window[time_i] 

197 for s1, s2 in pairs: 

198 Fqt = np.real(f0.rho_qs_dict[s1] * fi.rho_qs_dict[s2].conjugate()) 

199 if s1 != s2: 

200 Fqt += np.real(f0.rho_qs_dict[s2] * fi.rho_qs_dict[s1].conjugate()) 

201 F_q_t_averager[(s1, s2)].add_sample(time_i, Fqt) 

202 

203 if calculate_currents: 

204 for s1, s2 in pairs: 

205 Clqt = np.real(f0.jz_qs_dict[s1] * fi.jz_qs_dict[s2].conjugate()) 

206 Ctqt = 0.5 * np.real(np.sum(f0.jper_qs_dict[s1] * 

207 fi.jper_qs_dict[s2].conjugate(), axis=1)) 

208 if s1 != s2: 

209 Clqt += np.real(f0.jz_qs_dict[s2] * fi.jz_qs_dict[s1].conjugate()) 

210 Ctqt += 0.5 * np.real(np.sum(f0.jper_qs_dict[s2] * 

211 fi.jper_qs_dict[s1].conjugate(), axis=1)) 

212 

213 Cl_q_t_averager[(s1, s2)].add_sample(time_i, Clqt) 

214 Ct_q_t_averager[(s1, s2)].add_sample(time_i, Ctqt) 

215 

216 def calc_incoherent(window): 

217 # Calculate the incoherent (self) part for all lags in the window at once. 

218 n_window = len(window) 

219 f0 = window[0] 

220 for atom_type in atom_types: 

221 x0 = f0.positions_by_type[atom_type] 

222 if atom_type not in incoherent_displacements: 

223 incoherent_displacements[atom_type] = np.empty( 

224 (n_window, 3, x0.shape[0]), dtype=x0.dtype) 

225 incoherent_rho[atom_type] = np.empty( 

226 (n_window, n_qpoints), dtype=np.float64) 

227 

228 displacements = incoherent_displacements[atom_type][:n_window] 

229 for time_i, frame in enumerate(window): 

230 np.subtract(frame.positions_by_type[atom_type].T, x0.T, 

231 out=displacements[time_i]) 

232 

233 rho = incoherent_rho[atom_type][:n_window] 

234 _calc_rho_q_incoherent(displacements, q_points, out=rho) 

235 for time_i, sample in enumerate(rho): 

236 F_s_q_t_averager[atom_type].add_sample(time_i, sample) 

237 

238 # run calculation 

239 # This is the "main loop" over the trajectory 

240 for window in window_iterator: 

241 if logging_interval and window[0].frame_index % logging_interval == 0: 

242 traj._log_progress(window[-1].frame_index, window_start=window[0].frame_index) 

243 

244 for time_i in range(len(window)): 

245 calc_corr(window, time_i) 

246 

247 if calculate_incoherent: 

248 calc_incoherent(window) 

249 

250 # collect results into dict with numpy arrays (n_qpoints, N_tc) 

251 data_dict_corr = dict() 

252 data_dict_corr['q_points'] = q_points 

253 

254 time = None 

255 for pair in pairs: 

256 key = '_'.join(pair) 

257 F_q_t = 1 / traj.n_atoms * truncate_nans(F_q_t_averager[pair].get_average_all()) 

258 w, S_q_w = psd_from_acf_2d(F_q_t, delta_t) 

259 S_q_w = np.array(S_q_w) 

260 

261 if time is None: 

262 # Determine the actual length of time signal after truncation (if needed) 

263 time = delta_t * np.arange(F_q_t.shape[1], dtype=float) 

264 N_tc_actual = len(time) 

265 F_q_t_tot = np.zeros((n_qpoints, N_tc_actual)) 

266 S_q_w_tot = np.zeros((n_qpoints, N_tc_actual)) 

267 else: 

268 assert F_q_t.shape[1] == len(time) 

269 

270 data_dict_corr['omega'] = w 

271 data_dict_corr[f'Fqt_coh_{key}'] = F_q_t 

272 data_dict_corr[f'Sqw_coh_{key}'] = S_q_w 

273 

274 # sum all partials to the total 

275 F_q_t_tot += F_q_t 

276 S_q_w_tot += S_q_w 

277 

278 if N_tc_actual < N_tc: 

279 logger.warning('Truncating ACF due to NaNs, likely time_window is longer than length of Trajectory') # noqa 

280 

281 dw = float(w[1] - w[0]) 

282 w_max = float(w[-1]) 

283 

284 data_dict_corr['time'] = time 

285 data_dict_corr['Fqt_coh'] = F_q_t_tot 

286 data_dict_corr['Sqw_coh'] = S_q_w_tot 

287 

288 if calculate_currents: 

289 Cl_q_t_tot = np.zeros((n_qpoints, N_tc_actual)) 

290 Ct_q_t_tot = np.zeros((n_qpoints, N_tc_actual)) 

291 Cl_q_w_tot = np.zeros((n_qpoints, N_tc_actual)) 

292 Ct_q_w_tot = np.zeros((n_qpoints, N_tc_actual)) 

293 for pair in pairs: 

294 key = '_'.join(pair) 

295 Cl_q_t = 1 / traj.n_atoms * truncate_nans(Cl_q_t_averager[pair].get_average_all()) 

296 Ct_q_t = 1 / traj.n_atoms * truncate_nans(Ct_q_t_averager[pair].get_average_all()) 

297 _, Cl_q_w = psd_from_acf_2d(Cl_q_t, delta_t) 

298 _, Ct_q_w = psd_from_acf_2d(Ct_q_t, delta_t) 

299 data_dict_corr[f'Clqt_{key}'] = Cl_q_t 

300 data_dict_corr[f'Ctqt_{key}'] = Ct_q_t 

301 data_dict_corr[f'Clqw_{key}'] = Cl_q_w 

302 data_dict_corr[f'Ctqw_{key}'] = Ct_q_w 

303 

304 # sum all partials to the total 

305 Cl_q_t_tot += Cl_q_t 

306 Ct_q_t_tot += Ct_q_t 

307 Cl_q_w_tot += Cl_q_w 

308 Ct_q_w_tot += Ct_q_w 

309 data_dict_corr['Clqt'] = Cl_q_t_tot 

310 data_dict_corr['Ctqt'] = Ct_q_t_tot 

311 data_dict_corr['Clqw'] = Cl_q_w_tot 

312 data_dict_corr['Ctqw'] = Ct_q_w_tot 

313 

314 if calculate_incoherent: 

315 Fs_q_t_tot = np.zeros((n_qpoints, N_tc_actual)) 

316 Ss_q_w_tot = np.zeros((n_qpoints, N_tc_actual)) 

317 for atom_type in atom_types: 

318 Fs_q_t = 1 / traj.n_atoms * truncate_nans(F_s_q_t_averager[atom_type].get_average_all()) 

319 _, Ss_q_w = psd_from_acf_2d(Fs_q_t, delta_t) 

320 data_dict_corr[f'Fqt_incoh_{atom_type}'] = Fs_q_t 

321 data_dict_corr[f'Sqw_incoh_{atom_type}'] = Ss_q_w 

322 

323 # sum all partials to the total 

324 Fs_q_t_tot += Fs_q_t 

325 Ss_q_w_tot += Ss_q_w 

326 

327 data_dict_corr['Fqt_incoh'] = Fs_q_t_tot 

328 data_dict_corr['Sqw_incoh'] = Ss_q_w_tot 

329 

330 # finalize results with additional metadata 

331 new_sample = DynamicSample( 

332 data_dict_corr, 

333 simulation_data=dict( 

334 atom_types=atom_types, pairs=pairs, 

335 particle_counts=particle_counts, 

336 cell=traj.cell, 

337 time_between_frames=delta_t, 

338 maximum_time_lag=float(time[-1]), 

339 angular_frequency_resolution=dw, 

340 maximum_angular_frequency=w_max, 

341 number_of_frames=traj.number_of_frames_read, 

342 )) 

343 new_sample._append_history( 

344 'compute_dynamic_structure_factors', 

345 dict( 

346 dt=dt, 

347 window_size=window_size, 

348 window_step=window_step, 

349 calculate_currents=calculate_currents, 

350 calculate_incoherent=calculate_incoherent, 

351 )) 

352 

353 return new_sample 

354 

355 

356def compute_static_structure_factors( 

357 traj: Trajectory, 

358 q_points: NDArray[float], 

359 logging_interval: Optional[int] = 1000, 

360) -> StaticSample: 

361 r"""Compute the static structure factors. The results are returned in the 

362 form of a :class:`StaticSample <dynasor.sample.StaticSample>` 

363 object. 

364 

365 The computational backend and precision are set globally via 

366 :func:`set_compute_config <dynasor.set_compute_config>`, not as parameters of this 

367 function; see :ref:`the backends reference page <backends>` for details. 

368 

369 Parameters 

370 ---------- 

371 traj 

372 Input trajectory. 

373 q_points 

374 Array of q-points in units of rad/Å with shape ``(N_qpoints, 3)`` in Cartesian coordinates. 

375 logging_interval 

376 Log progress at ``INFO`` level every this many frames. Set to ``0`` to disable 

377 progress logging. 

378 """ 

379 # sanity check input args 

380 if q_points.ndim != 2 or q_points.shape[1] != 3: 

381 raise ValueError('q-points array has the wrong shape.') 

382 if not traj.has_positions: 

383 raise ValueError('compute_static_structure_factors requires positions to be available ' 

384 'in the trajectory, but traj does not provide positions.') 

385 _validate_qpoints_commensurate(q_points, traj.cell) 

386 

387 n_qpoints = q_points.shape[0] 

388 logger.info(f'Number of q-points: {n_qpoints}') 

389 

390 # define all pairs 

391 pairs = list(combinations_with_replacement(traj.atom_types, r=2)) 

392 particle_counts = {key: len(val) for key, val in traj.atomic_indices.items()} 

393 logger.debug('Considering pairs:') 

394 for pair in pairs: 

395 logger.debug(f' {pair}') 

396 

397 # processing function / batch processor 

398 compute_config = get_compute_config() 

399 backend = compute_config.backend 

400 precision = compute_config.precision 

401 gpu_batch_size = compute_config.batch_size 

402 

403 is_batched, processor = get_frame_processor(q_points, backend, precision, gpu_batch_size) 

404 

405 # setup averager 

406 Sq_averager = dict() 

407 for pair in pairs: 

408 Sq_averager[pair] = TimeAverager(1, n_qpoints) # time average with only timelag=0 

409 

410 # main loop: GPU uses batched prefetch, numba uses per-frame map 

411 _frame_source = (_prefetch_batched_iter(traj, processor, batch_size=gpu_batch_size) 

412 if is_batched 

413 else map(processor, traj)) 

414 

415 for frame in _frame_source: 

416 

417 if logging_interval and frame.frame_index % logging_interval == 0: 

418 traj._log_progress(frame.frame_index) 

419 

420 for s1, s2 in pairs: 

421 # compute correlation 

422 Sq_pair = np.real(frame.rho_qs_dict[s1] * frame.rho_qs_dict[s2].conjugate()) 

423 if s1 != s2: 

424 Sq_pair += np.real(frame.rho_qs_dict[s2] * frame.rho_qs_dict[s1].conjugate()) 

425 Sq_averager[(s1, s2)].add_sample(0, Sq_pair) 

426 

427 # collect results 

428 data_dict = dict() 

429 data_dict['q_points'] = q_points 

430 S_q_tot = np.zeros((n_qpoints, 1)) 

431 for s1, s2 in pairs: 

432 Sq = 1 / traj.n_atoms * Sq_averager[(s1, s2)].get_average_at_timelag(0).reshape(-1, 1) 

433 data_dict[f'Sq_{s1}_{s2}'] = Sq 

434 S_q_tot += Sq 

435 data_dict['Sq'] = S_q_tot 

436 

437 # finalize results 

438 new_sample = StaticSample( 

439 data_dict, 

440 simulation_data=dict( 

441 atom_types=traj.atom_types, 

442 pairs=pairs, 

443 particle_counts=particle_counts, 

444 cell=traj.cell, 

445 number_of_frames=traj.number_of_frames_read, 

446 )) 

447 new_sample._append_history('compute_static_structure_factors') 

448 

449 return new_sample 

450 

451 

452def compute_spectral_energy_density( 

453 traj: Trajectory, 

454 ideal_supercell: Atoms, 

455 primitive_cell: Atoms, 

456 q_points: NDArray[float], 

457 dt: float, 

458 partial: Optional[bool] = False, 

459 logging_interval: Optional[int] = 1000, 

460) -> tuple[NDArray[float], NDArray[float]]: 

461 r""" 

462 Compute the spectral energy density (SED) at specific q-points. The results 

463 are returned in the form of a tuple, which comprises the angular 

464 frequencies in an array of length ``N_times`` in units of rad/fs and the 

465 SED in units of eV/(rad/fs) as an array of shape ``(N_qpoints, N_times)``. 

466 The normalization is chosen such that integrating the SED of a q-point 

467 together with the supplied angular frequencies omega (rad/fs) yields 

468 `1/2 kB T` * number of bands (where number of bands = `len(prim) * 3`) 

469 

470 More details can be found in Thomas *et al.*, Physical Review B **81**, 081411 (2010), 

471 which should be cited when using this function along with the dynasor reference. 

472 

473 **Note 1:** 

474 SED analysis is only suitable for crystalline materials without diffusion as 

475 atoms are assumed to move around fixed reference positions throughout the entire trajectory. 

476 

477 **Note 2:** 

478 This implementation reads the full trajectory and can thus consume a lot of memory. 

479 

480 Parameters 

481 ---------- 

482 traj 

483 Input trajectory. 

484 ideal_supercell 

485 Ideal structure defining the reference positions. Do not change the masses 

486 in the ASE :class:`~ase.Atoms` objects to dynasor internal units, this will be 

487 done internally. Its atom count is checked against :attr:`traj`; a mismatched 

488 cell only triggers a warning (some thermal expansion relative to the reference 

489 structure is normal), and the atom ordering is not checked at all, so it must 

490 match the trajectory's. 

491 primitive_cell 

492 Underlying primitive structure. Must be aligned correctly with :attr:`ideal_supercell`. 

493 q_points 

494 Array of q-points in units of rad/Å with shape ``(N_qpoints, 3)`` in Cartesian coordinates. 

495 dt 

496 Time difference in femtoseconds between two consecutive snapshots in 

497 the trajectory. Note that you should not change :attr:`dt` if you change 

498 :attr:`frame_step <dynasor.Trajectory.frame_step>` in :attr:`traj`. 

499 partial 

500 If True the SED will be returned decomposed per basis and Cartesian direction. 

501 The shape is ``(N_qpoints, N_frequencies, len(primitive_cell), 3)``. 

502 logging_interval 

503 Log progress at ``INFO`` level every this many frames. Set to ``0`` to disable 

504 progress logging. 

505 """ 

506 

507 if q_points.ndim != 2 or q_points.shape[1] != 3: 

508 raise ValueError('q-points array has the wrong shape.') 

509 if dt <= 0: 

510 raise ValueError(f'dt must be positive: dt= {dt}') 

511 

512 delta_t = traj.frame_step * dt 

513 

514 # logger 

515 logger.info('Running SED') 

516 logger.info(f'Time between consecutive frames (dt * frame_step): {delta_t} fs') 

517 logger.info(f'Number of atoms in primitive_cell: {len(primitive_cell)}') 

518 logger.info(f'Number of atoms in ideal_supercell: {len(ideal_supercell)}') 

519 logger.info(f'Number of q-points: {q_points.shape[0]}') 

520 

521 # check that the ideal supercell agrees with traj 

522 if traj.n_atoms != len(ideal_supercell): 

523 raise ValueError('ideal_supercell must contain the same number of atoms as the trajectory.') 

524 if not np.allclose(traj.cell, ideal_supercell.cell, atol=1e-5, rtol=0.0): 

525 logger.warning('ideal_supercell cell does not match the trajectory cell.') 

526 

527 if len(primitive_cell) > len(ideal_supercell): 

528 raise ValueError('primitive_cell contains more atoms than ideal_supercell.') 

529 

530 if not traj.has_velocities: 

531 raise ValueError('compute_spectral_energy_density requires velocities to be available ' 

532 'in the trajectory, but traj does not provide velocities.') 

533 

534 # q-points must be commensurate with the ideal supercell (which defines the 

535 # phase factors below), not with the possibly thermally-expanded traj cell 

536 _validate_qpoints_commensurate(q_points, ideal_supercell.cell) 

537 

538 # collect all velocities, and scale with sqrt(masses) 

539 masses = ideal_supercell.get_masses().reshape(-1, 1) * Dalton_to_dmu 

540 velocities = [] 

541 for it, frame in enumerate(traj): 

542 if logging_interval and it % logging_interval == 0: 

543 traj._log_progress(frame.frame_index) 

544 v = frame.get_velocities_as_array(traj.atomic_indices) # in Å/fs 

545 velocities.append(np.sqrt(masses) * v) 

546 logger.info(f'Number of snapshots: {len(velocities)}') 

547 

548 # Perform the FFT on the last axis for extra speed (maybe not needed) 

549 N_samples = len(velocities) 

550 velocities = np.array(velocities) 

551 # places time index last and makes a copy for continuity 

552 velocities = velocities.transpose(1, 2, 0).copy() 

553 # #atoms in supercell x 3 directions x #frequencies 

554 velocities = np.fft.rfft(velocities, axis=2) 

555 

556 # Calculate indices and offsets needed for the SED method 

557 offsets, indices = get_offset_index(primitive_cell, ideal_supercell) 

558 

559 # Phase factor for use in FT. #qpoints x #atoms in supercell 

560 cell_positions = np.dot(offsets, primitive_cell.cell) 

561 phase = np.dot(q_points, cell_positions.T) # #qpoints x #unit cells 

562 phase_factors = np.exp(1.0j * phase) 

563 

564 # This dict maps the offsets to an index so ndarrays can be over 

565 # offset,index instead of atoms in supercell 

566 offset_dict = {off: n for n, off in enumerate(set(tuple(offset) for offset in offsets))} 

567 

568 # Pick out some shapes 

569 n_super, _, n_w = velocities.shape 

570 n_qpts = len(q_points) 

571 n_prim = len(primitive_cell) 

572 n_offsets = len(offset_dict) 

573 

574 # This new array will be indexed by index and offset instead (and also transposed) 

575 new_velocities = np.zeros((n_w, 3, n_prim, n_offsets), dtype=velocities.dtype) 

576 

577 for i in range(n_super): 

578 j = indices[i] # atom with index i in the supercell is of basis type j ... 

579 n = offset_dict[tuple(offsets[i])] # and its offset has index n 

580 new_velocities[:, :, j, n] = velocities[i].T 

581 

582 velocities = new_velocities 

583 

584 # Same story with the spatial phase factors 

585 new_phase_factors = np.zeros((n_qpts, n_prim, n_offsets), dtype=phase_factors.dtype) 

586 

587 for i in range(n_super): 

588 j = indices[i] 

589 n = offset_dict[tuple(offsets[i])] 

590 new_phase_factors[:, j, n] = phase_factors[:, i] 

591 

592 phase_factors = new_phase_factors 

593 

594 # calculate the density in a numba function 

595 density = _sed_inner_loop(phase_factors, velocities) 

596 warn_if_numba_threading_layer_is_slow() 

597 

598 if not partial: 

599 density = np.sum(density, axis=(2, 3)) 

600 

601 # units 

602 # make so that the velocities were originally in Angstrom / fs to be compatible with eV and Da 

603 

604 # the time delta in the fourier transform 

605 density = density * delta_t**2 

606 

607 # Divide by the length of the time signal 

608 density = density / (N_samples * delta_t) 

609 

610 # Divide by the number of primitive cells 

611 density = density / (n_super / n_prim) 

612 

613 # Factor so the sed can be integrated together with the returned omega 

614 # numpy fft works with ordinary/linear frequencies and not angular freqs 

615 density = density / (2*np.pi) 

616 

617 # angular frequencies 

618 w = 2 * np.pi * np.fft.rfftfreq(N_samples, delta_t) # rad/fs 

619 

620 return w, density 

621 

622 

623@numba.njit(parallel=True, fastmath=True) 

624def _sed_inner_loop(phase_factors, velocities): 

625 """This numba function calculates the spatial 

626 Fourier transform using precomputed phase factors. 

627 

628 As the use case can be one or many q-points the parallelization is over the 

629 temporal frequency components instead. 

630 """ 

631 

632 n_qpts = phase_factors.shape[0] # q-point index 

633 n_prim = phase_factors.shape[1] # basis atom index 

634 n_super = phase_factors.shape[2] # unit cell index 

635 

636 n_freqs = velocities.shape[0] # frequency, direction, basis atom, unit cell 

637 

638 density = np.zeros((n_qpts, n_freqs, n_prim, 3), dtype=np.float64) 

639 

640 for w in numba.prange(n_freqs): 

641 for k in range(n_qpts): 

642 for a in range(3): 

643 for b in range(n_prim): 

644 tmp = 0.0j 

645 for n in range(n_super): 

646 tmp += phase_factors[k, b, n] * velocities[w, a, b, n] 

647 density[k, w, b, a] += np.abs(tmp)**2 

648 return density