Coverage for ase/_4/optimize/frechet.py: 99.07%

107 statements  

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

1from __future__ import annotations 

2 

3from collections.abc import Iterator 

4from dataclasses import asdict, dataclass 

5from typing import Any 

6 

7import numpy as np 

8from scipy.sparse import block_diag, coo_array 

9 

10from ase import Atoms 

11from ase._4.optimize.cellutil import CellUtility 

12from ase._4.optimize.optimizable import ( 

13 ForceGradient, 

14 Optimizable4, 

15 get_maxforce, 

16 initial_inverse_position_hessian, 

17 initial_position_hessian, 

18) 

19from ase.units import GPa 

20 

21 

22def get_maxstress(stress) -> float: 

23 return np.abs(stress).max() 

24 

25 

26def initial_frechet_hessian( 

27 position_dofs: int, 

28 volume: float, 

29 mask3x3: np.ndarray, 

30 bulk_modulus: float = 145 * GPa, 

31 poisson_ratio: float = 0.3, 

32 alpha: float = 70.0, 

33) -> np.ndarray: 

34 

35 ndofs = position_dofs + 9 

36 hessian = initial_position_hessian(ndofs, alpha) 

37 hessian[:-9, :-9] = initial_position_hessian(position_dofs) 

38 

39 cell_hessian = _make_initial_cell_hessian( 

40 volume=volume, 

41 mask3x3=mask3x3, 

42 bulk_modulus=bulk_modulus, 

43 poisson_ratio=poisson_ratio, 

44 alpha=alpha, 

45 ) 

46 hessian[position_dofs:, position_dofs:] = cell_hessian 

47 return hessian 

48 

49 

50def _make_initial_cell_hessian( 

51 *, 

52 volume: float, 

53 mask3x3: np.ndarray, 

54 bulk_modulus: float, 

55 poisson_ratio: float, 

56 alpha: float, 

57) -> np.ndarray: 

58 from ase.optimize.cellawarebfgs import calculate_isotropic_elasticity_tensor 

59 

60 C_ijkl = calculate_isotropic_elasticity_tensor( 

61 bulk_modulus, 

62 poisson_ratio, 

63 suppress_rotation=alpha, 

64 ) 

65 

66 mask_ind = np.where(mask3x3.ravel() != 0)[0] 

67 indices = np.ix_(mask_ind, mask_ind) 

68 # Instead of zeroing, can we make the Hessian smaller when we are not 

69 # optimizing all cell DOFs? 

70 # Also, instead of not assigning masked cell DOFs, can't we just assign 

71 # them unconditionally and rely on the algorithm to do what it likes? 

72 cell_hessian = alpha * np.eye(9) 

73 cell_hessian[indices] = C_ijkl.reshape((9, 9))[indices] * volume 

74 return cell_hessian 

75 

76 

77@dataclass 

78class FrechetGradient(ForceGradient): 

79 stress: np.ndarray 

80 conv_crit_stress: np.ndarray 

81 snorm: float 

82 volume: float 

83 

84 def loginfo(self) -> dict[str, float]: 

85 return {'fmax': self.fnorm, 'smax': self.snorm, 'vol': self.volume} 

86 

87 def datafy(self) -> dict[str, Any]: 

88 # XXX must be able to handle the type somehow. 

89 # The Target type would know what Gradient type to restore. 

90 return asdict(self) 

91 

92 @classmethod 

93 def undatafy(cls, dct: dict[str, Any]) -> FrechetGradient: 

94 return cls(**dct) 

95 

96 

97def default_mask(pbc) -> np.ndarray: 

98 mask = np.ones(6, bool) 

99 mask[:3] = pbc 

100 for i in range(3): 

101 if not mask[i]: 

102 mask[3 + (i + 1) % 3] = 0 

103 mask[3 + (i - 1) % 3] = 0 

104 return mask 

105 

106 

107class FrechetOptimizable(Optimizable4): 

108 iotype = 'frechet' 

109 

110 def __init__( 

111 self, 

112 atoms: Atoms, 

113 mask: Any = None, 

114 *, 

115 fmax: float, 

116 smax: float, 

117 orig_cell: np.ndarray | None = None, 

118 ): 

119 self.atoms = atoms 

120 if mask is None: 

121 mask = default_mask(atoms.pbc) 

122 self.optimizable = atoms.__ase_optimizable__() 

123 if orig_cell is None: 

124 orig_cell = atoms.cell.copy() 

125 self._utility = CellUtility(orig_cell, mask) 

126 

127 # XXX Should Target have the max values? Maybe, because 

128 # it knows what they mean. 

129 self.fmax = fmax 

130 self.smax = smax 

131 

132 def datafy(self) -> dict[str, Any]: 

133 return { 

134 'fmax': self.fmax, 

135 'smax': self.smax, 

136 'atoms': self.atoms, 

137 'mask': self._utility.mask3x3.tolist(), 

138 'orig_cell': self._utility.orig_cell.ravel().tolist(), 

139 # XXX We may need to save multiple things from the Utility. 

140 # But currently not, because we create the utility, and 

141 # don't set those things. 

142 } 

143 

144 @classmethod 

145 def undatafy(cls, dct: dict, calc) -> FrechetOptimizable: 

146 # XXX Here we depend directly on calculator since it's the only thing 

147 # we don't know how to restore. 

148 atoms = dct['atoms'].copy() 

149 atoms.calc = calc 

150 mask = np.array(dct['mask']).reshape(3, 3) 

151 assert mask.dtype == bool 

152 orig_cell = np.array(dct['orig_cell']).reshape(3, 3) 

153 return cls( 

154 atoms, 

155 mask, 

156 fmax=dct['fmax'], 

157 smax=dct['smax'], 

158 orig_cell=orig_cell, 

159 ) 

160 

161 @classmethod 

162 def undatafy_gradient(cls, dct: dict) -> FrechetGradient: 

163 return FrechetGradient.undatafy(dct) 

164 

165 def get_value(self) -> float: 

166 return ( 

167 self.optimizable.get_value() 

168 + self._utility.get_energy_correction(self.atoms.cell.volume) 

169 ) 

170 

171 def get_gradient(self) -> FrechetGradient: 

172 atoms_forces = self.atoms.get_forces() 

173 if self._utility.mask3x3.any(): 

174 stress = self.atoms.get_stress() 

175 else: 

176 stress = np.zeros(6) 

177 

178 frechet_forces, conv_crit_stress = self._utility.get_forces_frechet( 

179 atoms_forces=atoms_forces, 

180 stress=stress, 

181 cell=self.atoms.get_cell(), 

182 exp_cell_factor=self._exp_cell_factor, 

183 ) 

184 

185 # (Convergence criterion and maybe metric should be more pluggable) 

186 fnorm = get_maxforce(atoms_forces) 

187 snorm = get_maxstress(conv_crit_stress) 

188 converged = fnorm < self.fmax and snorm < self.smax 

189 

190 return FrechetGradient( 

191 gradient=-frechet_forces.ravel(), 

192 forces=atoms_forces, 

193 stress=stress, 

194 conv_crit_stress=conv_crit_stress, 

195 fnorm=fnorm, 

196 snorm=snorm, 

197 converged=converged, 

198 volume=self.atoms.cell.volume, 

199 ) 

200 

201 @property 

202 def _cell_factor(self) -> float: 

203 # XXX Default behaviour taken from unitcellfilter: 

204 return float(len(self.atoms)) 

205 

206 @property 

207 def _exp_cell_factor(self) -> float: 

208 return 1.0 # always 1.0 with 'cellaware' 

209 

210 def get_x(self) -> np.ndarray: 

211 return self._utility.get_positions_frechet( 

212 self.atoms.get_positions(), 

213 self.atoms.get_cell(), 

214 cell_factor=self._cell_factor, 

215 exp_cell_factor=self._exp_cell_factor, 

216 ).ravel() 

217 

218 def set_x(self, x: np.ndarray) -> None: 

219 self._utility.set_positions_frechet( 

220 x.reshape(-1, 3), 

221 self.atoms, 

222 self._cell_factor, 

223 self._exp_cell_factor, 

224 ) 

225 

226 def gradient_norm(self, gradient: np.ndarray) -> float: 

227 return self.optimizable.gradient_norm(gradient) 

228 

229 def initial_hessian( 

230 self, 

231 bulk_modulus: float = 145 * GPa, 

232 poisson_ratio: float = 0.3, 

233 alpha: float = 70.0, 

234 ) -> np.ndarray: 

235 return initial_frechet_hessian( 

236 len(self.atoms) * 3, 

237 # XXX volume should be set intelligently in lowdim cases. 

238 # What happens currently in 1d/2d? 

239 # We need a test of that. 

240 self.atoms.cell.volume, 

241 self._utility.mask3x3, 

242 bulk_modulus, 

243 poisson_ratio, 

244 alpha, 

245 ) 

246 

247 def initial_inverse_hessian( 

248 self, 

249 bulk_modulus: float = 145 * GPa, 

250 poisson_ratio: float = 0.3, 

251 alpha: float = 70.0, 

252 ) -> coo_array: 

253 ndofs = len(self.atoms) * 3 

254 inv_position_hessian = initial_inverse_position_hessian(ndofs, alpha) 

255 cell_hessian = _make_initial_cell_hessian( 

256 volume=self.atoms.cell.volume, 

257 mask3x3=self._utility.mask3x3, 

258 bulk_modulus=bulk_modulus, 

259 poisson_ratio=poisson_ratio, 

260 alpha=alpha, 

261 ) 

262 inv_cell_hessian = np.linalg.inv(cell_hessian) 

263 return block_diag( 

264 (inv_position_hessian, inv_cell_hessian), 

265 format='coo', 

266 ) 

267 

268 def iterimages(self) -> Iterator[Atoms]: 

269 yield self.atoms