phono3py-gpu 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,449 @@
1
+ """GPU three-phonon linewidths and collision rows with bounded batches."""
2
+
3
+ import numpy as np
4
+ from phono3py.conductivity.grid_point_data import ScatteringResult
5
+ from phono3py.conductivity.lbte_collision_solver import (
6
+ LBTECollisionResult,
7
+ LBTECollisionSolver,
8
+ )
9
+ from phono3py.conductivity.scattering_solvers import RTAScatteringSolver
10
+ from phono3py.file_IO import read_pp_from_hdf5
11
+ from phono3py.phonon3.imag_self_energy import ImagSelfEnergy
12
+ from phonopy.physical_units import get_physical_units
13
+
14
+ from phono3py_gpu.backend import cupy, host, kernel
15
+ from phono3py_gpu.integration import channel_bounds, sigma_weights
16
+
17
+
18
+ def average_initial(values, pp, gp):
19
+ """Average fully selected degenerate subspaces in upstream band order."""
20
+ cp = cupy()
21
+ ids = pp.phonons.degenerate_ids[gp]
22
+ for identifier in np.unique(ids):
23
+ full = np.flatnonzero(ids == identifier)
24
+ if len(full) > 1 and np.isin(full, pp.band_indices).all():
25
+ selected = cp.asarray(np.flatnonzero(np.isin(pp.band_indices, full)))
26
+ values[..., selected] = values[..., selected].mean(axis=-1, keepdims=True)
27
+ return values
28
+
29
+
30
+ def occupations(frequency, temperature, cutoff):
31
+ cp = cupy()
32
+ if temperature <= 0:
33
+ return cp.zeros_like(frequency)
34
+ u = get_physical_units()
35
+ x = cp.where(frequency > cutoff, frequency, 1.0) * u.THzToEv / (u.KB * temperature)
36
+ return 1 / cp.expm1(x)
37
+
38
+
39
+ def linewidth_detail(engine, triplets, strength, g, temperature, occupation=None):
40
+ """Unweighted per-triplet gamma in THz, with one fused CUDA kernel."""
41
+ cp = cupy()
42
+ if occupation is None:
43
+ occupation = occupations(
44
+ engine.frequencies, temperature, engine.pp.cutoff_frequency
45
+ )
46
+ result = cp.empty(strength.shape)
47
+ kernel("scattering.cu", "linewidth")(
48
+ ((result.size + 127) // 128,),
49
+ (128,),
50
+ (
51
+ result,
52
+ cp.ascontiguousarray(strength),
53
+ g,
54
+ engine.frequencies,
55
+ occupation,
56
+ cp.asarray(triplets),
57
+ np.int32(len(triplets)),
58
+ np.int32(strength.shape[1]),
59
+ np.int32(engine.nb),
60
+ np.float64(engine.pp.cutoff_frequency),
61
+ np.float64(ImagSelfEnergy(engine.pp).unit_conversion_factor),
62
+ ),
63
+ )
64
+ return result
65
+
66
+
67
+ def collision_layout(solver):
68
+ """Return target GR points, rotations and one-q collision row shape."""
69
+ collision, pp = solver._collision, solver._pp
70
+ nb0, nb = len(pp.band_indices), solver.engine.nb
71
+ if collision._is_reducible_collision_matrix:
72
+ targets = np.arange(np.prod(pp.mesh_numbers))[:, None]
73
+ return targets, np.eye(3)[None], (nb0, len(targets), nb), 1
74
+ targets = collision._rot_grid_points
75
+ return (
76
+ targets,
77
+ collision._rotations_cartesian,
78
+ (nb0, 3, len(targets), nb, 3),
79
+ 3,
80
+ )
81
+
82
+
83
+ def reduce_collision(strength, g, inv_sinh, triplets, unit):
84
+ """Reduce both scattering directions to a (2, triplet, band0, band) tensor."""
85
+ cp = cupy()
86
+ nt, nb0, nb = strength.shape[:3]
87
+ reduced = cp.empty((2, nt, nb0, nb))
88
+ kernel("scattering.cu", "collision_reduce")(
89
+ ((reduced.size + 127) // 128,),
90
+ (128,),
91
+ (
92
+ reduced,
93
+ cp.ascontiguousarray(strength),
94
+ g[2],
95
+ inv_sinh,
96
+ cp.asarray(triplets),
97
+ np.int32(nt),
98
+ np.int32(nb0),
99
+ np.int32(nb),
100
+ np.float64(unit),
101
+ ),
102
+ )
103
+ return reduced
104
+
105
+
106
+ def add_collision_rows(
107
+ row, reduced, triplet_map, swapped, rotations, *, start, num_cartesian, num_q
108
+ ):
109
+ """Accumulate reduced collision rows using triplet maps and Cartesian rotations."""
110
+ nt, nb0, nb = reduced.shape[1:]
111
+ ni, nr = triplet_map.shape[-2:]
112
+ kernel("scattering.cu", "collision_rows")(
113
+ ((row.size + 127) // 128,),
114
+ (128,),
115
+ (
116
+ row,
117
+ reduced,
118
+ triplet_map,
119
+ swapped,
120
+ rotations,
121
+ np.int32(nt),
122
+ np.int32(nb0),
123
+ np.int32(nb),
124
+ np.int32(ni),
125
+ np.int32(nr),
126
+ np.int32(start),
127
+ np.int32(num_cartesian),
128
+ np.int32(num_q),
129
+ ),
130
+ )
131
+
132
+
133
+ def sigma_groups(engine, sigmas, row_bytes=0, reuse=True):
134
+ """Bound extra sigma weights and collision rows to a quarter of free memory."""
135
+ width = 1
136
+ if reuse and len(sigmas) > 1 and engine.pp.constant_averaged_interaction is None:
137
+ # Account for resident FC3 before choosing how many sigmas to retain.
138
+ engine.fourier
139
+ bands = engine.band_block if engine.streamed else len(engine.pp.band_indices)
140
+ elements = engine.batch_size * bands * engine.nb**2
141
+ per_sigma = 25 * elements + row_bytes # Three FP64 channels and a byte mask.
142
+ width = max(
143
+ 1, min(len(sigmas), cupy().cuda.runtime.memGetInfo()[0] // 4 // per_sigma)
144
+ )
145
+ for first in range(0, len(sigmas), width):
146
+ yield range(first, min(first + width, len(sigmas)))
147
+
148
+
149
+ def interaction_batches(
150
+ engine,
151
+ sigmas,
152
+ sigma_cutoff,
153
+ collision=False,
154
+ full=False,
155
+ read_pp=False,
156
+ filename=None,
157
+ averaged=None,
158
+ ):
159
+ """Yield device weights and interactions without a full-triplet tensor."""
160
+ cp = cupy()
161
+ pp = engine.pp
162
+ triplets = pp.get_triplets_at_q()[0]
163
+ gp = triplets[0, 0]
164
+ loaded = loaded_zero = None
165
+ if read_pp:
166
+ assert len(sigmas) == 1
167
+ loaded, loaded_zero = read_pp_from_hdf5(
168
+ pp.mesh_numbers,
169
+ grid_point=int(gp),
170
+ sigma=sigmas[0],
171
+ sigma_cutoff=sigma_cutoff,
172
+ filename=filename,
173
+ )
174
+ bands = pp.band_indices
175
+ # An unbounded Gaussian makes the shared support dense; keep the GEMM path.
176
+ dense = full or (
177
+ (sigma_cutoff is None or sigma_cutoff <= 0)
178
+ and any(sigma is not None for sigma in sigmas)
179
+ )
180
+ # A streamed batch shares one reciprocal FC3 across all its initial-band tiles.
181
+ triplet_step = 1 if engine.streamed else engine.batch_size
182
+ band_step = engine.band_block if engine.streamed else len(bands)
183
+ for start in range(0, len(triplets), triplet_step):
184
+ batch = slice(start, start + triplet_step)
185
+ selected = triplets[batch]
186
+ vertices = engine.tetrahedron.vertices(selected) if None in sigmas else None
187
+ bounds = None
188
+ tensor = None
189
+ if engine.streamed:
190
+ if vertices is not None:
191
+ bounds = channel_bounds(engine.frequencies, vertices)
192
+ if (
193
+ loaded is None
194
+ and averaged is None
195
+ and pp.constant_averaged_interaction is None
196
+ ):
197
+ tensor = engine.fourier.components(selected[0])
198
+ for first in range(0, len(bands), band_step):
199
+ block = slice(first, first + band_step)
200
+ ids = bands[block]
201
+ integrations, zero = sigma_weights(
202
+ pp,
203
+ selected,
204
+ engine.frequencies,
205
+ engine.frequencies[gp, cp.asarray(ids)],
206
+ sigmas,
207
+ sigma_cutoff=sigma_cutoff,
208
+ collision=collision,
209
+ vertices=vertices,
210
+ bounds=bounds,
211
+ )
212
+ if loaded is not None:
213
+ if loaded_zero is not None and not collision:
214
+ if not cp.array_equal(zero, cp.asarray(loaded_zero[batch, block])):
215
+ raise ValueError("Inconsistency found in g_zero.")
216
+ strength = cp.asarray(loaded[batch, block])
217
+ elif averaged is not None:
218
+ value = cp.asarray(averaged[block])[:, None, None]
219
+ strength = cp.broadcast_to(value / np.prod(pp.mesh_numbers), zero.shape)
220
+ elif pp.constant_averaged_interaction is not None:
221
+ strength = cp.full(
222
+ zero.shape,
223
+ pp.constant_averaged_interaction / np.prod(pp.mesh_numbers),
224
+ )
225
+ elif engine.streamed:
226
+ strength = engine.project_slice(
227
+ tensor, selected[0], ids, None if dense else zero[0]
228
+ )[None]
229
+ strength *= pp.unit_conversion_factor
230
+ else:
231
+ strength = engine.compute(selected, None if full else zero)
232
+ shared = strength
233
+ masked = (
234
+ not full
235
+ and loaded is None
236
+ and averaged is None
237
+ and pp.constant_averaged_interaction is None
238
+ and not pp.symmetrize_fc3q
239
+ )
240
+ for j, (g, zero) in enumerate(integrations):
241
+ strength = (
242
+ cp.where(zero, 0, shared) if masked and len(sigmas) > 1 else shared
243
+ )
244
+ yield j, start, selected, block, g, zero, strength
245
+ del integrations, shared, strength
246
+ del tensor
247
+
248
+
249
+ class GPUScatteringSolver(RTAScatteringSolver):
250
+ """Upstream RTA solver contract with a shared CUDA interaction engine."""
251
+
252
+ def __init__(self, *args, engine, **kwargs):
253
+ super().__init__(*args, **kwargs)
254
+ self.engine = engine
255
+ self._occupations = [
256
+ occupations(engine.frequencies, t, engine.pp.cutoff_frequency)
257
+ for t in self._temperatures
258
+ ]
259
+
260
+ @property
261
+ def supports_rust_batching(self):
262
+ return False
263
+
264
+ def compute(self, grid_point, averaged_pp_interaction=None):
265
+ cp = cupy()
266
+ pp = self._pp
267
+ self.engine.set_grid_point(grid_point)
268
+ triplets, multiplicities = pp.get_triplets_at_q()[:2]
269
+ ns, nt, nb0 = len(self._sigmas), len(self._temperatures), len(pp.band_indices)
270
+ gamma = cp.zeros((ns, nt, nb0))
271
+ if self._is_N_U:
272
+ normal, umklapp = cp.zeros_like(gamma), cp.zeros_like(gamma)
273
+ detail = None
274
+ if self._is_gamma_detail:
275
+ detail = np.zeros((nt, len(triplets), nb0, self.engine.nb, self.engine.nb))
276
+ average = cp.zeros(nb0) if self._is_full_pp or self._use_const_ave_pp else None
277
+ if self._use_ave_pp and averaged_pp_interaction is None:
278
+ raise ValueError("use_ave_pp requires averaged_pp_interaction.")
279
+ if self._store_pp:
280
+ shape = (len(triplets), nb0, self.engine.nb, self.engine.nb)
281
+ saved = np.empty(shape, dtype=np.float64)
282
+ saved_zero = np.empty(shape, dtype=np.int8)
283
+ for group in sigma_groups(
284
+ self.engine, self._sigmas, reuse=not self._read_pp and not self._use_ave_pp
285
+ ):
286
+ for j, start, selected, block, g, zero, strength in interaction_batches(
287
+ self.engine,
288
+ [self._sigmas[i] for i in group],
289
+ self._sigma_cutoff,
290
+ full=self._is_full_pp,
291
+ read_pp=self._read_pp,
292
+ filename=self._pp_filename,
293
+ averaged=averaged_pp_interaction if self._use_ave_pp else None,
294
+ ):
295
+ j += group.start
296
+ end = start + len(selected)
297
+ w = cp.asarray(multiplicities[start:end])
298
+ if self._is_N_U:
299
+ is_normal = cp.asarray(
300
+ np.all(pp.bz_grid.addresses[selected].sum(axis=1) == 0, axis=1)
301
+ )
302
+ if average is not None and j == 0:
303
+ average[block] += (strength.sum(axis=(2, 3)) * w[:, None]).sum(
304
+ axis=0
305
+ ) / self.engine.nb**2
306
+ for k, temperature in enumerate(self._temperatures):
307
+ values = linewidth_detail(
308
+ self.engine,
309
+ selected,
310
+ strength,
311
+ g,
312
+ temperature,
313
+ self._occupations[k],
314
+ )
315
+ weighted = values.sum(axis=(2, 3)) * w[:, None]
316
+ gamma[j, k, block] += weighted.sum(axis=0)
317
+ if self._is_N_U:
318
+ normal[j, k, block] += (weighted * is_normal[:, None]).sum(
319
+ axis=0
320
+ )
321
+ umklapp[j, k, block] += (weighted * (~is_normal)[:, None]).sum(
322
+ axis=0
323
+ )
324
+ if detail is not None:
325
+ detail[k, start:end, block] = host(values)
326
+ if self._store_pp and j == ns - 1:
327
+ saved[start:end, block] = host(strength)
328
+ saved_zero[start:end, block] = host(zero)
329
+ if self._store_pp:
330
+ pp.set_interaction_strength(saved, g_zero=saved_zero)
331
+ average_initial(gamma, pp, grid_point)
332
+ if self._is_N_U:
333
+ average_initial(normal, pp, grid_point)
334
+ average_initial(umklapp, pp, grid_point)
335
+ self._gamma_N = host(normal) if self._is_N_U else None
336
+ self._gamma_U = host(umklapp) if self._is_N_U else None
337
+ self._gamma_detail_at_q = detail
338
+ result = host(average) if average is not None else averaged_pp_interaction
339
+ return ScatteringResult(gamma=host(gamma), averaged_pp_interaction=result)
340
+
341
+
342
+ class GPUCollisionSolver(LBTECollisionSolver):
343
+ """GPU collision rows using upstream integer symmetry maps."""
344
+
345
+ def __init__(self, *args, engine, retain_pp=False, **kwargs):
346
+ super().__init__(*args, **kwargs)
347
+ self.engine = engine
348
+ self.retain_pp = retain_pp
349
+ if not retain_pp:
350
+ self._pp.delete_interaction_strength()
351
+ self._occupations = [
352
+ occupations(engine.frequencies, t, engine.pp.cutoff_frequency)
353
+ for t in self._temperatures
354
+ ]
355
+
356
+ cp = cupy()
357
+ u = get_physical_units()
358
+ valid = engine.frequencies > engine.pp.cutoff_frequency
359
+ f = cp.where(valid, engine.frequencies, 1)
360
+ self._inv_sinh = [
361
+ cp.where(valid, 1 / cp.sinh(f * u.THzToEv / (2 * u.KB * t)), 0)
362
+ if t > 0
363
+ else cp.zeros_like(f)
364
+ for t in self._temperatures
365
+ ]
366
+
367
+ def compute(self, grid_point):
368
+ cp = cupy()
369
+ pp, collision = self._pp, self._collision
370
+ collision.set_grid_point(grid_point)
371
+ triplets, multiplicities = pp.get_triplets_at_q()[:2]
372
+ gp2tp, _, swapped = collision._get_gp2tp_map()
373
+ nb0, nb = len(pp.band_indices), self.engine.nb
374
+ ns, nt = len(self._sigmas), len(self._temperatures)
375
+ targets, rotations, rowshape, nc = collision_layout(self)
376
+ gamma = cp.zeros((ns, nt, nb0))
377
+ rows = np.zeros((ns, nt, *rowshape))
378
+ average = cp.zeros(nb0) if self._is_full_pp else None
379
+ unit = collision.unit_conversion_factor
380
+ target_triplets = cp.asarray(gp2tp[targets])
381
+ target_swapped = cp.asarray(swapped[targets])
382
+ device_rotations = cp.asarray(rotations)
383
+ if self.retain_pp:
384
+ shape = (len(triplets), nb0, nb, nb)
385
+ saved = np.empty(shape, dtype=np.float64)
386
+ saved_zero = np.empty(shape, dtype=np.int8)
387
+ for group in sigma_groups(
388
+ self.engine,
389
+ self._sigmas,
390
+ row_bytes=nt * int(np.prod(rowshape)) * 8,
391
+ reuse=not self._read_pp,
392
+ ):
393
+ row = cp.zeros((len(group), nt, *rowshape))
394
+ for j, start, selected, block, g, zero, strength in interaction_batches(
395
+ self.engine,
396
+ [self._sigmas[i] for i in group],
397
+ self._sigma_cutoff,
398
+ collision=True,
399
+ full=self._is_full_pp,
400
+ read_pp=self._read_pp,
401
+ filename=self._pp_filename,
402
+ ):
403
+ j += group.start
404
+ end = start + len(selected)
405
+ w = cp.asarray(multiplicities[start:end])
406
+ if average is not None and j == 0:
407
+ average[block] += (strength.sum(axis=(2, 3)) * w[:, None]).sum(
408
+ axis=0
409
+ ) / nb**2
410
+ for k, temperature in enumerate(self._temperatures):
411
+ values = linewidth_detail(
412
+ self.engine,
413
+ selected,
414
+ strength,
415
+ g,
416
+ temperature,
417
+ self._occupations[k],
418
+ )
419
+ gamma[j, k, block] += (values.sum(axis=(2, 3)) * w[:, None]).sum(
420
+ axis=0
421
+ )
422
+ if temperature <= 0:
423
+ continue
424
+ reduced = reduce_collision(
425
+ strength, g, self._inv_sinh[k], selected, unit
426
+ )
427
+ add_collision_rows(
428
+ row[j - group.start, k, block],
429
+ reduced,
430
+ target_triplets,
431
+ target_swapped,
432
+ device_rotations,
433
+ start=start,
434
+ num_cartesian=nc,
435
+ num_q=1,
436
+ )
437
+ if self.retain_pp and j == ns - 1:
438
+ saved[start:end, block] = host(strength)
439
+ saved_zero[start:end, block] = host(zero)
440
+ rows[group.start : group.stop] = host(row)
441
+ del row
442
+ if self.retain_pp:
443
+ pp.set_interaction_strength(saved, g_zero=saved_zero)
444
+ average_initial(gamma, pp, grid_point)
445
+ return LBTECollisionResult(
446
+ gamma=host(gamma),
447
+ collision_row=rows,
448
+ averaged_pp=None if average is None else host(average),
449
+ )
@@ -0,0 +1,175 @@
1
+ """CUDA group velocities and the finite-difference Wigner velocity operator."""
2
+
3
+ import numpy as np
4
+ from phono3py.conductivity.grid_point_data import HeatCapacityResult, VelocityResult
5
+ from phono3py.conductivity.heat_capacity_solvers import ModeHeatCapacitySolver
6
+ from phono3py.conductivity.utils import VOIGT_INDEX_PAIRS
7
+ from phono3py.conductivity.velocity_solvers import GroupVelocitySolver
8
+ from phonopy.phonon.degeneracy import degenerate_sets
9
+ from phonopy.phonon.grid import (
10
+ get_grid_points_by_rotations,
11
+ get_qpoints_from_bz_grid_points,
12
+ )
13
+ from phonopy.physical_units import get_physical_units
14
+
15
+ from phono3py_gpu.backend import cupy, eigh, host
16
+
17
+
18
+ class GPUVelocitySolver(GroupVelocitySolver):
19
+ """Bulk velocity protocol; finite differences and eigensolutions stay on CUDA."""
20
+
21
+ def __init__(self, *args, harmonic, wte=False, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+ self.harmonic = harmonic
24
+ self.wte = wte
25
+ self.produces_vm_by_vm = wte
26
+ self.produces_gv_by_gv = not wte
27
+ self.velocity_operator = None
28
+
29
+ def _derivatives(self, q, length, square_root=False):
30
+ cp = cupy()
31
+ offsets = self._pp.primitive.cell.T * length
32
+ zero_acoustic = np.linalg.norm(q) < np.linalg.norm(offsets, axis=1)
33
+ if (
34
+ square_root
35
+ and self.harmonic.nb <= 32
36
+ and not (self.harmonic.is_gl and zero_acoustic.any())
37
+ ):
38
+ # Batch the six small matrices; directional Gamma NAC stays below.
39
+ points = q + offsets[:, None, :] * np.array([1, -1])[None, :, None]
40
+ matrices = self.harmonic.matrices(points.reshape(-1, 3))
41
+ roots = self._sqrt(matrices, np.repeat(zero_acoustic, 2))
42
+ return (roots[::2] - roots[1::2]) / (2 * length)
43
+ results = []
44
+ for direction in np.eye(3):
45
+ dq = self._pp.primitive.cell @ direction * length
46
+ zero_acoustic = np.linalg.norm(q) < np.linalg.norm(dq)
47
+ if square_root and zero_acoustic and self.harmonic.is_gl:
48
+ # WTE specifies the NAC approach direction even when |q| is
49
+ # below the dynamical matrix's Gamma tolerance.
50
+ plus, minus = [
51
+ self.harmonic.matrices(
52
+ [point], q_direction=point / np.linalg.norm(point)
53
+ )[0]
54
+ for point in (q + dq, q - dq)
55
+ ]
56
+ else:
57
+ plus, minus = self.harmonic.matrices([q + dq, q - dq])
58
+ if square_root:
59
+ plus = self._sqrt(plus, zero_acoustic)
60
+ minus = self._sqrt(minus, zero_acoustic)
61
+ results.append((plus - minus) / (2 * length))
62
+ return cp.stack(results)
63
+
64
+ def _sqrt(self, dm, zero_acoustic):
65
+ cp = cupy()
66
+ val, e = eigh(dm)
67
+ if np.any(zero_acoustic):
68
+ e[..., :3] *= cp.asarray(~np.asarray(zero_acoustic))[..., None, None]
69
+ # Use the complex principal square root, including unstable modes.
70
+ roots = cp.sqrt(val.astype(cp.complex128))
71
+ return (e * roots[..., None, :]) @ e.swapaxes(-1, -2).conj()
72
+
73
+ def compute(self, grid_points):
74
+ cp = cupy()
75
+ pp = self._pp
76
+ qs = get_qpoints_from_bz_grid_points(np.asarray(grid_points), pp.bz_grid)
77
+ bands = cp.asarray(pp.band_indices)
78
+ rotations = cp.asarray(self._rotations_cartesian)
79
+ first, second = np.asarray(VOIGT_INDEX_PAIRS).T
80
+ first, second = cp.asarray(first), cp.asarray(second)
81
+ velocities, products, operators = [], [], []
82
+ for gp, q in zip(grid_points, qs, strict=True):
83
+ if self.wte:
84
+ # Supplied per-band linewidths require WTE's canonical basis,
85
+ # including the arbitrary rotation within degenerate spaces.
86
+ self._pp.dynamical_matrix.run(q)
87
+ val_host, e_host = np.linalg.eigh(
88
+ self._pp.dynamical_matrix.dynamical_matrix
89
+ )
90
+ val, e = cp.asarray(val_host), cp.asarray(e_host)
91
+ else:
92
+ val, e = eigh(self.harmonic.matrices([q])[0])
93
+ freq = cp.sign(val) * cp.sqrt(cp.abs(val)) * pp.frequency_factor_to_THz
94
+ if self.wte:
95
+ derivative = self._derivatives(q, self._gv_delta_q or 5e-6, True)
96
+ op = (
97
+ e.conj().T[None] @ derivative @ e[None]
98
+ ) * pp.frequency_factor_to_THz
99
+ op = (op + op.swapaxes(-1, -2).conj()) / 2
100
+ gv = cp.diagonal(op, axis1=1, axis2=2).real.T.copy()
101
+ for deg in degenerate_sets(host(freq)):
102
+ if len(deg) > 1:
103
+ ids = cp.asarray(deg)
104
+ gv[ids] = eigh(op[:, ids[:, None], ids[None, :]])[0].T
105
+ vector = op.transpose(1, 2, 0)[bands]
106
+ operators.append(host(vector))
107
+ else:
108
+ derivative = (
109
+ self.harmonic.matrices([q], derivative=True)[0]
110
+ if self._gv_delta_q is None
111
+ else self._derivatives(q, self._gv_delta_q)
112
+ )
113
+ direction = cp.asarray([1.0, 2.0, 3.0]) / np.sqrt(14)
114
+ lifting = cp.einsum("d,dij->ij", direction, derivative)
115
+ if self._gv_delta_q is not None:
116
+ dq = pp.primitive.cell @ host(direction) * self._gv_delta_q
117
+ mats = self.harmonic.matrices([q + dq, q - dq])
118
+ lifting = (mats[0] - mats[1]) / (2 * self._gv_delta_q)
119
+ rotated = e.copy()
120
+ for deg in degenerate_sets(host(freq)):
121
+ if len(deg) == 1:
122
+ continue
123
+ ids = cp.asarray(deg)
124
+ block = e[:, ids]
125
+ _, rotation = eigh(block.conj().T @ lifting @ block)
126
+ rotated[:, ids] = block @ rotation
127
+ gv = cp.einsum("ij,dij->jd", rotated.conj(), derivative @ rotated).real
128
+ gv *= cp.where(
129
+ freq > 1e-4,
130
+ pp.frequency_factor_to_THz**2
131
+ / (2 * cp.where(freq > 1e-4, freq, 1)),
132
+ 0,
133
+ )[:, None]
134
+ rmean = self._velocity_obj._get_r_cart_mean(q - np.rint(q))
135
+ gv = gv @ cp.asarray(rmean).T
136
+ vector = gv[bands]
137
+ velocities.append(host(gv[bands]))
138
+ if self._is_kappa_star:
139
+ mapped = get_grid_points_by_rotations(
140
+ int(gp), pp.bz_grid, with_surface=False
141
+ )
142
+ multi = len(mapped) // len(np.unique(mapped))
143
+ else:
144
+ multi = 1
145
+ v = cp.einsum("...a,rba->r...b", vector, rotations)
146
+ outer = (v[..., first] * v[..., second].conj()).sum(axis=0) / multi
147
+ products.append(host(outer))
148
+ gv = np.asarray(velocities).reshape(len(grid_points), len(bands), 3)
149
+ if self.wte:
150
+ self.velocity_operator = np.asarray(operators)
151
+ return VelocityResult(
152
+ group_velocities=gv,
153
+ vm_by_vm=np.asarray(products),
154
+ )
155
+ return VelocityResult(group_velocities=gv, gv_by_gv=np.asarray(products))
156
+
157
+
158
+ class GPUHeatCapacitySolver(ModeHeatCapacitySolver):
159
+ """Einstein heat capacities, keeping upstream cutoffs and zero-T convention."""
160
+
161
+ def compute(self, grid_points):
162
+ cp = cupy()
163
+ u = get_physical_units()
164
+ f = cp.asarray(
165
+ self._pp.phonons.frequencies[grid_points][:, self._pp.band_indices]
166
+ )
167
+ t = cp.asarray(self._temperatures)[:, None, None]
168
+ x = f[None] * u.THzToEv / (u.KB * cp.where(t > 0, t, 1))
169
+ # Stable form of x**2 * exp(x) / expm1(x)**2.
170
+ z = cp.exp(-x)
171
+ cv = u.KB * x**2 * z / cp.expm1(-x) ** 2
172
+ cv = cp.where(
173
+ (t > 0) & (f[None] > self._pp.cutoff_frequency) & cp.isfinite(cv), cv, 0
174
+ )
175
+ return HeatCapacityResult(heat_capacities=host(cv))