Coverage for dynasor/qpoints/spherical_qpoints.py: 100%

63 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-08-10 08:27 +0000

1from typing import Optional 

2import itertools 

3import numpy as np 

4from numpy.typing import NDArray 

5from dynasor.logging_tools import logger 

6 

7 

8def get_spherical_qpoints( 

9 cell: NDArray[float], 

10 q_max: float, 

11 q_min: Optional[float] = 0.0, 

12 max_points: Optional[int] = None, 

13 seed: Optional[int] = 42, 

14 chunk_size: Optional[int] = 100000, 

15) -> NDArray[float]: 

16 r"""Generates all q-points on the reciprocal lattice inside a given radius 

17 :attr:`q_max`. This approach is suitable if an isotropic sampling of 

18 q-space is desired. The function returns the resulting q-points in 

19 Cartesian coordinates as an ``Nx3`` array. 

20 

21 If the number of generated q-points are large, points can be removed by 

22 specifying :attr:`max_points`. The q-points will be randomly removed in 

23 such a way that the q-points inside are roughly uniformly distributed with 

24 respect to :math:`|q|`. If the number of q-points are binned w.r.t. their 

25 norm the function would increase quadratically up until some distance P 

26 from which point the distribution would be constant. 

27 

28 Parameters 

29 ---------- 

30 cell 

31 Real cell with cell vectors as rows. 

32 q_max 

33 Maximum norm of generated q-points 

34 (in units of rad/Å, i.e. including factor of :math:`2\pi`). 

35 q_min 

36 Minimum norm of generated q-points 

37 (in units of rad/Å, i.e. including factor of :math:`2\pi`). 

38 max_points 

39 Optionally limit the set to __approximately__ :attr:`max_points` points 

40 by randomly removing points from a "fully populated mesh". The points 

41 are removed in such a way that for :math:`q > q_\mathrm{prune}`, the 

42 points will be radially uniformly distributed. The value of 

43 :math:`q_\mathrm{prune}` is calculated from :attr:`q_max`, 

44 :attr:`max_points`, and the shape of the cell. 

45 seed 

46 Seed used for stochastic pruning. 

47 chunk_size 

48 Number of q-points to process at once (controls memory use). 

49 """ 

50 

51 if q_min >= q_max: 

52 raise ValueError('q_min must be smaller than q_max.') 

53 if q_min < 0: 

54 raise ValueError('q_min cannot be negative.') 

55 if chunk_size < 1: 

56 raise ValueError('chunk_size must be a positive integer.') 

57 if max_points is not None and max_points < 1: 

58 raise ValueError('max_points must be a positive integer.') 

59 

60 # inv(A.T) == inv(A).T 

61 # The physicists reciprocal cell 

62 cell = cell.astype(np.float64) 

63 rec_cell = np.linalg.inv(cell.T) * 2 * np.pi 

64 

65 # We want to find all points on the lattice defined by the reciprocal cell 

66 # such that all points within q_max are in this set 

67 inv_rec_cell = np.linalg.inv(rec_cell.T) # cell / 2pi 

68 

69 # h is the height of the rec_cell perpendicular to the other two vectors 

70 h = 1 / np.linalg.norm(inv_rec_cell, axis=1) 

71 

72 # If a q_point has a coordinate larger than this number it must be further away than q_max 

73 N = np.ceil(q_max / h).astype(int) 

74 

75 # Generate q-points on the grid with in chunks to keep memory consumption low 

76 iterator = itertools.product(*[range(-n, n+1) for n in N]) 

77 q_points = [] 

78 

79 while True: 

80 

81 # Take a chunk of points 

82 lattice_points_chunk = list(itertools.islice(iterator, chunk_size)) 

83 if not lattice_points_chunk: 

84 break 

85 lattice_points_chunk = np.array(lattice_points_chunk) 

86 q_points_chunk = lattice_points_chunk @ rec_cell # (chunk, 3) 

87 

88 # Filter by norm 

89 q_distances = np.linalg.norm(q_points_chunk, axis=1) 

90 mask = np.logical_and(q_distances >= q_min, q_distances <= q_max) 

91 if np.any(mask): 

92 q_points.append(q_points_chunk[mask]) 

93 

94 if len(q_points) == 0: 

95 return np.empty((0, 3)) 

96 q_points = np.vstack(q_points) 

97 

98 # Pruning based on max_points 

99 if max_points is not None and max_points < len(q_points): 

100 

101 q_vol = abs(np.linalg.det(rec_cell)) 

102 q_prune = _get_prune_distance(max_points, q_min, q_max, q_vol) 

103 

104 if q_prune < q_max: 

105 logger.info(f'Pruning q-points from the range {q_prune:.3} < |q| < {q_max}') 

106 

107 # Keep point with probability min(1, (q_prune/|q|)^2) -> 

108 # aim for an equal number of points per equally thick "onion peel" 

109 # to get equal number of points per radial unit. 

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

111 p = np.divide(q_prune**2, q_distances**2, out=np.ones_like(q_distances), 

112 where=np.logical_not(np.isclose(q_distances, 0))) 

113 

114 rs = np.random.RandomState(seed) 

115 q_points = q_points[p > rs.rand(len(q_points))] 

116 

117 logger.info(f'Pruned from {len(q_distances)} q-points to {len(q_points)}') 

118 

119 return q_points 

120 

121 

122def _get_prune_distance( 

123 max_points: int, 

124 q_min: float, 

125 q_max: float, 

126 q_vol: float, 

127) -> NDArray[float]: 

128 r"""Determine distance in q-space beyond which to prune 

129 the q-point mesh to achieve near-isotropic sampling of q-space. 

130 

131 If points are selected from the full mesh with probability 

132 :math:`\min(1, (q_\mathrm{prune} / |q|)^2)`, q-space will 

133 on average be sampled with an equal number of points per radial unit 

134 (for :math:`q > q_\mathrm{prune}`). 

135 

136 The general idea is as follows. 

137 We know that the number of q-points inside a radius :math:`Q` is given by 

138 

139 .. math: 

140 

141 n = v^{-1} \int_0^Q dq 4 \pi q^2 = v^{-1} 4/3 \pi Q^3 

142 

143 where :math:`v` is the volume of one q-point. Now we want to find 

144 a distance :math:`P` such that if all points outside this radius 

145 are weighted by the function :math:`w(q)` the total number of 

146 q-points will equal the target :math:`N` (:attr:`max_points`) 

147 while the number of q-points increases linearly from :math:`P` 

148 outward. One additional constraint is that the weighting function 

149 must be 1 at :math:`P`. The weighting function which accomplishes 

150 this is :math:`w(q)=P^2/q^2` 

151 

152 .. math: 

153 

154 N = v^{-1} \left( \int_0^P 4 \pi q^2 + \int_P^Q 4 \pi q^2 P^2 / q^2 dq \right). 

155 

156 This results in a `cubic equation <https://en.wikipedia.org/wiki/Cubic_equation>`_ 

157 for :math:`P`, which is solved by this function. 

158 

159 Parameters 

160 ---------- 

161 max_points 

162 Maximum number of resulting q-points; :math:`N` below. 

163 q_min 

164 Minimum q-value in the resulting q-point set. 

165 q_max 

166 Maximum q-value in the resulting q-point set; :math:`Q` below. 

167 q_vol 

168 q-space volume for a single q-point. 

169 """ 

170 

171 Q = q_max 

172 V = q_vol 

173 N = max_points 

174 

175 # Coefs 

176 a = 1.0 

177 b = -3 / 2 * Q 

178 c = 0.0 

179 d = 3 / 2 * V * N / (4 * np.pi) + 0.5 * q_min**3 

180 

181 # Eq tol solve 

182 def original_eq(x): 

183 return a * x**3 + b * x**2 + c * x + d 

184 # original_eq = lambda x: a * x**3 + b * x**2 + c * x + d 

185 

186 # Discriminant 

187 p = (3 * a * c - b**2) / (3 * a**2) 

188 q = (2 * b**3 - 9 * a * b * c + 27 * a**2 * d) / (27 * a**3) 

189 

190 D_t = - (4 * p**3 + 27 * q**2) 

191 if D_t < 0: 

192 return q_max 

193 

194 x = Q * (np.cos(1 / 3 * np.arccos(1 - 4 * d / Q**3) - 2 * np.pi / 3) + 0.5) 

195 

196 assert np.isclose(original_eq(x), 0), original_eq(x) 

197 

198 return x