Coverage for ase/md/analysis.py: 63.48%

115 statements  

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

1import numpy as np 

2 

3 

4class DiffusionCoefficient: 

5 def __init__(self, traj, timestep, atom_indices=None, molecule=False): 

6 """Diffusion coefficient from Einstein equation. 

7 

8 This class calculates the Diffusion Coefficient for the given 

9 Trajectory using the Einstein Equation: 

10 

11 ..math:: 

12 

13 \\left \\langle \\left 

14 | r(t) - r(0) \\right | ^{2} 

15 \\right \\rangle = 2nDt 

16 

17 where r(t) is the position of atom at time t, n is the degrees 

18 of freedom and D is the Diffusion Coefficient 

19 

20 Solved herein by fitting with 

21 :math:`y = mx + c`, i.e. :math:`\\frac{1}{2n} \\left \\langle \\left | 

22 r(t) - r(0) \\right | ^{2} \\right \\rangle = Dt` with m = D and c = 0 

23 

24 See also `wikibooks`_ on diffusion coefficients. 

25 

26 .. _wikibooks: 

27 https://en.wikibooks.org/wiki/Molecular_Simulation/ 

28 Diffusion_Coefficients 

29 

30 Parameters 

31 ---------- 

32 traj (Trajectory): 

33 Trajectory of atoms objects (images) 

34 timestep (Float): 

35 Timestep between *each image in the trajectory*, in ASE 

36 timestep units 

37 (For an MD simulation with timestep of N, and images written 

38 every M iterations, our timestep here is N * M) 

39 atom_indices (List of Int): 

40 The indices of atoms whose Diffusion Coefficient is to be 

41 calculated explicitly 

42 molecule (Boolean) 

43 Indicate if we are studying a molecule instead of atoms, 

44 therefore use centre of mass in calculations 

45 """ 

46 

47 self.traj = traj 

48 self.timestep = timestep 

49 

50 # Condition used if user wants to calculate diffusion coefficients for 

51 # specific atoms or all atoms 

52 self.atom_indices = atom_indices 

53 if self.atom_indices is None: 

54 self.atom_indices = [i for i in range(len(traj[0]))] 

55 

56 # Condition if we are working with the mobility of a molecule, need to 

57 # manage arrays slightly differently 

58 self.is_molecule = molecule 

59 if self.is_molecule: 

60 self.types_of_atoms = ['molecule'] 

61 self.no_of_atoms = [1] 

62 else: 

63 self.types_of_atoms = sorted( 

64 set(traj[0].symbols[self.atom_indices]) 

65 ) 

66 self.no_of_atoms = [ 

67 traj[0].get_chemical_symbols().count(symbol) 

68 for symbol in self.types_of_atoms 

69 ] 

70 

71 # Dummy initialisation for important results data object 

72 self._slopes = [] 

73 

74 @property 

75 def no_of_types_of_atoms(self): 

76 """ 

77 

78 Dynamically returns the number of different atoms in the system 

79 

80 """ 

81 return len(self.types_of_atoms) 

82 

83 @property 

84 def slopes(self): 

85 """Return slopes fitted to datapoints. 

86 

87 If undefined, calculate slopes. 

88 """ 

89 if len(self._slopes) == 0: 

90 self.calculate() 

91 return self._slopes 

92 

93 @slopes.setter 

94 def slopes(self, values): 

95 """Set slopes as fitted to datapoints.""" 

96 self._slopes = values 

97 

98 def _initialise_arrays(self, ignore_n_images, number_of_segments): 

99 """Private function to initialise data storage objects. This 

100 includes objects to store the total timesteps sampled, the 

101 average diffusivity for species in any given segment, and 

102 objects to store gradient and intercept from fitting. 

103 

104 Parameters 

105 ---------- 

106 ignore_n_images (Int): 

107 Number of images you want to ignore from the start of the 

108 trajectory, e.g. during equilibration 

109 number_of_segments (Int): 

110 Divides the given trajectory in to segments to allow 

111 statistical analysis 

112 """ 

113 

114 total_images = len(self.traj) - ignore_n_images 

115 self.no_of_segments = number_of_segments 

116 self.len_segments = total_images // self.no_of_segments 

117 

118 # These are the data objects we need when plotting information. First 

119 # the x-axis, timesteps 

120 self.timesteps = np.linspace( 

121 0, total_images * self.timestep, total_images + 1 

122 ) 

123 # This holds all the data points for the diffusion coefficients, 

124 # averaged over atoms 

125 self.xyz_segment_ensemble_average = np.zeros( 

126 ( 

127 self.no_of_segments, 

128 self.no_of_types_of_atoms, 

129 3, 

130 self.len_segments, 

131 ) 

132 ) 

133 # This holds all the information on linear fits, from which we get the 

134 # diffusion coefficients 

135 self.slopes = np.zeros( 

136 (self.no_of_types_of_atoms, self.no_of_segments, 3) 

137 ) 

138 self.intercepts = np.zeros( 

139 (self.no_of_types_of_atoms, self.no_of_segments, 3) 

140 ) 

141 

142 self.cont_xyz_segment_ensemble_average = 0 

143 

144 def calculate(self, ignore_n_images=0, number_of_segments=1): 

145 """Calculate the diffusion coefficients, using the previously 

146 supplied data. The user can break the data into segments and 

147 take the average over these trajectories, therefore allowing 

148 statistical analysis and derivation of standard deviations. 

149 Option is also provided to ignore initial images if data is 

150 perhaps unequilibrated initially. 

151 

152 Parameters 

153 ---------- 

154 ignore_n_images (Int): 

155 Number of images you want to ignore from the start of 

156 the trajectory, e.g. during equilibration 

157 number_of_segments (Int): 

158 Divides the given trajectory in to segments to allow 

159 statistical analysis 

160 

161 """ 

162 

163 # Setup all the arrays we need to store information 

164 self._initialise_arrays(ignore_n_images, number_of_segments) 

165 

166 for segment_no in range(self.no_of_segments): 

167 start = segment_no * self.len_segments 

168 end = start + self.len_segments 

169 seg = self.traj[ignore_n_images + start : ignore_n_images + end] 

170 

171 # If we are considering a molecular system, work out the 

172 # COM for the starting structure 

173 if self.is_molecule: 

174 com_orig = np.zeros(3) 

175 for atom_no in self.atom_indices: 

176 com_orig += seg[0].positions[atom_no] / len( 

177 self.atom_indices 

178 ) 

179 

180 # For each image, calculate displacement. I spent some 

181 # time deciding if this should run from 0 or 1, as the 

182 # displacement will be zero for t = 0, but this is a data 

183 # point that needs fitting too and so should be included 

184 for image_no in range(0, len(seg)): 

185 # This object collects the xyz displacements for all atom 

186 # species in the image 

187 xyz_disp = np.zeros((self.no_of_types_of_atoms, 3)) 

188 

189 # Calculating for each atom individually, grouping by species 

190 # type (e.g. solid state) 

191 if not self.is_molecule: 

192 # For each atom, work out displacement from start coordinate 

193 # and collect information with like atoms 

194 for atom_no in self.atom_indices: 

195 sym_index = self.types_of_atoms.index( 

196 seg[image_no].symbols[atom_no] 

197 ) 

198 xyz_disp[sym_index] += np.square( 

199 seg[image_no].positions[atom_no] 

200 - seg[0].positions[atom_no] 

201 ) 

202 

203 # Calculating for group of atoms (molecule) and work 

204 # out squared displacement 

205 else: 

206 com_disp = np.zeros(3) 

207 for atom_no in self.atom_indices: 

208 com_disp += seg[image_no].positions[atom_no] / len( 

209 self.atom_indices 

210 ) 

211 xyz_disp[0] += np.square(com_disp - com_orig) 

212 

213 # For each atom species or molecule, use xyz_disp to calculate 

214 # the average data 

215 for sym_index in range(self.no_of_types_of_atoms): 

216 # Normalise by degrees of freedom and average overall atoms 

217 # for each axes over entire segment 

218 denominator = 2 * self.no_of_atoms[sym_index] 

219 for xyz in range(3): 

220 self.xyz_segment_ensemble_average[segment_no][ 

221 sym_index 

222 ][xyz][image_no] = ( 

223 xyz_disp[sym_index][xyz] / denominator 

224 ) 

225 

226 # We've collected all the data for this entire segment, so now to 

227 # fit the data. 

228 for sym_index in range(self.no_of_types_of_atoms): 

229 ( 

230 self.slopes[sym_index][segment_no], 

231 self.intercepts[sym_index][segment_no], 

232 ) = self._fit_data( 

233 self.timesteps[start:end], 

234 self.xyz_segment_ensemble_average[segment_no][sym_index], 

235 ) 

236 

237 def _fit_data(self, x, y): 

238 """Private function that returns slope and intercept for 

239 linear fit to mean square diffusion data 

240 

241 Parameters 

242 ---------- 

243 x (Array of floats): 

244 Linear list of timesteps in the calculation 

245 y (Array of floats): 

246 Mean square displacement as a function of time. 

247 """ 

248 

249 # Simpler implementation but disabled as fails Conda tests. 

250 # from scipy.stats import linregress 

251 # slope, intercept, r_value, p_value, std_err = linregress(x,y) 

252 

253 # Initialise objects 

254 slopes = np.zeros(3) 

255 intercepts = np.zeros(3) 

256 

257 # Convert into suitable format for lstsq 

258 x_edited = np.vstack([np.array(x), np.ones(len(x))]).T 

259 # Calculate slopes for x, y and z-axes 

260 for xyz in range(3): 

261 slopes[xyz], intercepts[xyz] = np.linalg.lstsq( 

262 x_edited, y[xyz], rcond=-1 

263 )[0] 

264 

265 return slopes, intercepts 

266 

267 def get_diffusion_coefficients(self): 

268 """Returns diffusion coefficients for atoms (in alphabetical 

269 order) along with standard deviation. 

270 

271 All data is currently passed out in units of Å^2/<ASE time units> 

272 To convert into Å^2/fs => multiply by ase.units.fs 

273 To convert from Å^2/fs to cm^2/s => 

274 multiply by (10^-8)^2 / 10^-15 = 10^-1 

275 

276 """ 

277 

278 slopes = [ 

279 np.mean(self.slopes[sym_index]) 

280 for sym_index in range(self.no_of_types_of_atoms) 

281 ] 

282 std = [ 

283 np.std(self.slopes[sym_index]) 

284 for sym_index in range(self.no_of_types_of_atoms) 

285 ] 

286 

287 return slopes, std 

288 

289 def plot(self, ax=None, show=False): 

290 """Auto-plot of Diffusion Coefficient data. Provides basic 

291 framework for visualising analysis. 

292 

293 Parameters 

294 ---------- 

295 ax (Matplotlib.axes.Axes) 

296 Axes object on to which plot can be created 

297 show (Boolean) 

298 Whether or not to show the created plot. Default: False 

299 

300 """ 

301 

302 # Necessary if user hasn't supplied an axis. 

303 import matplotlib.pyplot as plt 

304 

305 # Convert from ASE time units to fs (aesthetic) 

306 from ase.units import fs as fs_conversion 

307 

308 if ax is None: 

309 ax = plt.gca() 

310 

311 # Define some aesthetic variables 

312 color_list = plt.cm.Set3(np.linspace(0, 1, self.no_of_types_of_atoms)) 

313 xyz_labels = ['X', 'Y', 'Z'] 

314 xyz_markers = ['o', 's', '^'] 

315 

316 # Create an x-axis that is in a more intuitive format for the view 

317 graph_timesteps = self.timesteps / fs_conversion 

318 

319 for segment_no in range(self.no_of_segments): 

320 start = segment_no * self.len_segments 

321 end = start + self.len_segments 

322 label = None 

323 

324 for sym_index in range(self.no_of_types_of_atoms): 

325 for xyz in range(3): 

326 if segment_no == 0: 

327 label = 'Species: {} ({})'.format( 

328 self.types_of_atoms[sym_index], xyz_labels[xyz] 

329 ) 

330 # Add scatter graph for the mean square displacement data 

331 # in this segment 

332 ax.scatter( 

333 graph_timesteps[start:end], 

334 self.xyz_segment_ensemble_average[segment_no][ 

335 sym_index 

336 ][xyz], 

337 color=color_list[sym_index], 

338 marker=xyz_markers[xyz], 

339 label=label, 

340 linewidth=1, 

341 edgecolor='grey', 

342 ) 

343 

344 # Print the line of best fit for segment 

345 line = np.mean( 

346 self.slopes[sym_index][segment_no] 

347 ) * fs_conversion * graph_timesteps[start:end] + np.mean( 

348 self.intercepts[sym_index][segment_no] 

349 ) 

350 if segment_no == 0: 

351 label = ( 

352 'Segment Mean : %s' % (self.types_of_atoms[sym_index]) 

353 ) 

354 ax.plot( 

355 graph_timesteps[start:end], 

356 line, 

357 color='C%d' % (sym_index), 

358 label=label, 

359 linestyle='--', 

360 ) 

361 

362 # Plot separator at end of segment 

363 x_coord = graph_timesteps[end - 1] 

364 ax.plot( 

365 [x_coord, x_coord], 

366 [-0.001, 1.05 * np.amax(self.xyz_segment_ensemble_average)], 

367 color='grey', 

368 linestyle=':', 

369 ) 

370 

371 # Aesthetic parts of the plot 

372 ax.set_ylim(-0.001, 1.05 * np.amax(self.xyz_segment_ensemble_average)) 

373 ax.legend(loc='best') 

374 ax.set_xlabel('Time (fs)') 

375 ax.set_ylabel(r'Mean Square Displacement ($\AA^2$)') 

376 

377 if show: 

378 plt.show() 

379 

380 def print_data(self): 

381 """Output of statistical analysis for Diffusion Coefficient 

382 data. Provides basic framework for understanding calculation.""" 

383 

384 from ase.units import fs as fs_conversion 

385 

386 # Collect statistical data for diffusion coefficient over all segments 

387 slopes, std = self.get_diffusion_coefficients() 

388 

389 # Useful notes for any consideration of conversion. 

390 # Converting gradient from Å^2/fs to more common units of 

391 # cm^2/s => multiplying by (10^-8)^2 / 10^-15 = 10^-1 

392 # Converting intercept from Å^2 to more common units of cm^2 

393 # => multiply by (10^-8)^2 = 10^-16 

394 # 

395 # Note currently in ASE internal time units 

396 # Converting into fs => divide by 1/(fs_conversion) => multiply by 

397 # (fs_conversion) 

398 

399 # Print data for each atom, in each segment. 

400 for sym_index in range(self.no_of_types_of_atoms): 

401 print('---') 

402 print(r'Species: %4s' % self.types_of_atoms[sym_index]) 

403 print('---') 

404 for segment_no in range(self.no_of_segments): 

405 print( 

406 r'Segment %3d: Diffusion Coefficient = ' 

407 r'%.10f Å^2/fs; Intercept = %.10f Å^2;' 

408 % ( 

409 segment_no, 

410 np.mean(self.slopes[sym_index][segment_no]) 

411 * fs_conversion, 

412 np.mean(self.intercepts[sym_index][segment_no]), 

413 ) 

414 ) 

415 

416 # Print average overall data. 

417 print('---') 

418 for sym_index in range(self.no_of_types_of_atoms): 

419 print( 

420 'Mean Diffusion Coefficient (X, Y and Z) : ' 

421 '%s = %.10f Å^2/fs; Std. Dev. = %.10f Å^2/fs' 

422 % ( 

423 self.types_of_atoms[sym_index], 

424 slopes[sym_index] * fs_conversion, 

425 std[sym_index] * fs_conversion, 

426 ) 

427 ) 

428 print('---')