Coverage for ase/gui/nanoparticle.py: 78.42%

292 statements  

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

1"""nanoparticle.py - Window for setting up crystalline nanoparticles.""" 

2 

3from copy import copy 

4 

5import numpy as np 

6 

7import ase.data 

8import ase.gui.ui as ui 

9from ase.cluster import wulff_construction 

10from ase.cluster.cubic import BodyCenteredCubic, FaceCenteredCubic, SimpleCubic 

11from ase.cluster.hexagonal import Graphite, HexagonalClosedPacked 

12from ase.gui.i18n import _ 

13from ase.gui.widgets import Element, pybutton 

14 

15# Delayed imports: 

16# ase.cluster.data 

17 

18 

19introtext = _("""\ 

20Create a nanoparticle either by specifying the number of layers, or using the 

21Wulff construction. Please press the [Help] button for instructions on how to 

22specify the directions. 

23WARNING: The Wulff construction currently only works with cubic crystals! 

24""") 

25 

26helptext = _(""" 

27The nanoparticle module sets up a nano-particle or a cluster with a given 

28crystal structure. 

29 

301) Select the element, the crystal structure and the lattice constant(s). 

31 The [Get structure] button will find the data for a given element. 

32 

332) Choose if you want to specify the number of layers in each direction, or if 

34 you want to use the Wulff construction. In the latter case, you must 

35 specify surface energies in each direction, and the size of the cluster. 

36 

37How to specify the directions: 

38------------------------------ 

39 

40First time a direction appears, it is interpreted as the entire family of 

41directions, i.e. (0,0,1) also covers (1,0,0), (-1,0,0) etc. If one of these 

42directions is specified again, the second specification overrules that specific 

43direction. For this reason, the order matters and you can rearrange the 

44directions with the [Up] and [Down] keys. You can also add a new direction, 

45remember to press [Add] or it will not be included. 

46 

47Example: (1,0,0) (1,1,1), (0,0,1) would specify the {100} family of directions, 

48the {111} family and then the (001) direction, overruling the value given for 

49the whole family of directions. 

50""") 

51 

52py_template_layers = """ 

53import ase 

54%(import)s 

55 

56surfaces = %(surfaces)s 

57layers = %(layers)s 

58lc = %(latconst)s 

59atoms = %(factory)s('%(element)s', surfaces, layers, latticeconstant=lc) 

60 

61# OPTIONAL: Cast to ase.Atoms object, discarding extra information: 

62# atoms = ase.Atoms(atoms) 

63""" 

64 

65py_template_wulff = """ 

66import ase 

67from ase.cluster import wulff_construction 

68 

69surfaces = %(surfaces)s 

70esurf = %(energies)s 

71lc = %(latconst)s 

72size = %(natoms)s # Number of atoms 

73atoms = wulff_construction('%(element)s', surfaces, esurf, 

74 size, '%(structure)s', 

75 rounding='%(rounding)s', latticeconstant=lc) 

76 

77# OPTIONAL: Cast to ase.Atoms object, discarding extra information: 

78# atoms = ase.Atoms(atoms) 

79""" 

80 

81 

82class SetupNanoparticle: 

83 "Window for setting up a nanoparticle." 

84 

85 structure_names = { 

86 'fcc': _('Face centered cubic (fcc)'), 

87 'bcc': _('Body centered cubic (bcc)'), 

88 'sc': _('Simple cubic (sc)'), 

89 'hcp': _('Hexagonal closed-packed (hcp)'), 

90 'graphite': _('Graphite'), 

91 } 

92 

93 needs_4index = { # 3 or 4 index dimension 

94 'fcc': False, 

95 'bcc': False, 

96 'sc': False, 

97 'hcp': True, 

98 'graphite': True, 

99 } 

100 

101 needs_2lat = { # 1 or 2 lattice parameters 

102 'fcc': False, 

103 'bcc': False, 

104 'sc': False, 

105 'hcp': True, 

106 'graphite': True, 

107 } 

108 

109 structure_factories = { 

110 'fcc': FaceCenteredCubic, 

111 'bcc': BodyCenteredCubic, 

112 'sc': SimpleCubic, 

113 'hcp': HexagonalClosedPacked, 

114 'graphite': Graphite, 

115 } 

116 

117 # A list of import statements for the Python window. 

118 import_names = { 

119 'fcc': 'from ase.cluster.cubic import FaceCenteredCubic', 

120 'bcc': 'from ase.cluster.cubic import BodyCenteredCubic', 

121 'sc': 'from ase.cluster.cubic import SimpleCubic', 

122 'hcp': 'from ase.cluster.hexagonal import HexagonalClosedPacked', 

123 'graphite': 'from ase.cluster.hexagonal import Graphite', 

124 } 

125 

126 # Default layer specifications for the different structures. 

127 default_layers = { 

128 'fcc': [((1, 0, 0), 6), ((1, 1, 0), 9), ((1, 1, 1), 5)], 

129 'bcc': [((1, 0, 0), 6), ((1, 1, 0), 9), ((1, 1, 1), 5)], 

130 'sc': [((1, 0, 0), 6), ((1, 1, 0), 9), ((1, 1, 1), 5)], 

131 'hcp': [((0, 0, 0, 1), 5), ((1, 0, -1, 0), 5)], 

132 'graphite': [((0, 0, 0, 1), 5), ((1, 0, -1, 0), 5)], 

133 } 

134 

135 def __init__(self, gui): 

136 self.atoms = None 

137 self.no_update = True 

138 self.old_structure = 'fcc' 

139 

140 win = self.win = ui.Window(_('Nanoparticle')) 

141 win.add(ui.Text(introtext)) 

142 

143 self.element = Element('', self.apply) 

144 lattice_button = ui.Button(_('Get structure'), self.set_structure_data) 

145 self.elementinfo = ui.Label(' ') 

146 win.add(self.element) 

147 win.add(self.elementinfo) 

148 win.add(lattice_button) 

149 

150 # The structure and lattice constant 

151 labels = [] 

152 values = [] 

153 for abbrev, name in self.structure_names.items(): 

154 labels.append(name) 

155 values.append(abbrev) 

156 self.structure_cb = ui.ComboBox( 

157 labels=labels, values=values, callback=self.update_structure 

158 ) 

159 win.add([_('Structure:'), self.structure_cb]) 

160 

161 self.a = ui.SpinBox(3.0, 0.0, 1000.0, 0.01, self.update) 

162 self.c = ui.SpinBox(3.0, 0.0, 1000.0, 0.01, self.update) 

163 win.add([_('Lattice constant: a ='), self.a, ' c =', self.c]) 

164 

165 # Choose specification method 

166 self.method_cb = ui.ComboBox( 

167 labels=[_('Layer specification'), _('Wulff construction')], 

168 values=['layers', 'wulff'], 

169 callback=self.update_gui_method, 

170 ) 

171 win.add([_('Method: '), self.method_cb]) 

172 

173 self.layerlabel = ui.Label('Missing text') # Filled in later 

174 win.add(self.layerlabel) 

175 self.direction_table_rows = ui.Rows() 

176 win.add(self.direction_table_rows) 

177 self.default_direction_table() 

178 

179 win.add(_('Add new direction:')) 

180 self.new_direction_and_size_rows = ui.Rows() 

181 win.add(self.new_direction_and_size_rows) 

182 self.update_new_direction_and_size_stuff() 

183 

184 # Information 

185 win.add(_('Information about the created cluster:')) 

186 self.info = [ 

187 _('Number of atoms: '), 

188 ui.Label('-'), 

189 _(' Approx. diameter: '), 

190 ui.Label('-'), 

191 ] 

192 win.add(self.info) 

193 

194 # Finalize setup 

195 self.update_structure() 

196 self.update_gui_method() 

197 self.no_update = False 

198 

199 self.auto = ui.CheckButton(_('Automatic Apply')) 

200 win.add(self.auto) 

201 

202 win.add( 

203 [ 

204 pybutton(_('Creating a nanoparticle.'), self.makeatoms), 

205 ui.helpbutton(helptext), 

206 ui.Button(_('Apply'), self.apply), 

207 ui.Button(_('OK'), self.ok), 

208 ] 

209 ) 

210 

211 self.gui = gui 

212 self.smaller_button = None 

213 self.largeer_button = None 

214 

215 self.element.grab_focus() 

216 

217 def default_direction_table(self): 

218 "Set default directions and values for the current crystal structure." 

219 self.direction_table = [] 

220 struct = self.structure_cb.value 

221 for direction, layers in self.default_layers[struct]: 

222 self.direction_table.append((direction, layers, 1.0)) 

223 

224 def update_direction_table(self): 

225 self.direction_table_rows.clear() 

226 for direction, layers, energy in self.direction_table: 

227 self.add_direction(direction, layers, energy) 

228 self.update() 

229 

230 def add_direction(self, direction, layers, energy): 

231 i = len(self.direction_table_rows) 

232 

233 if self.method_cb.value == 'wulff': 

234 spin = ui.SpinBox(energy, 0.0, 1000.0, 0.1, self.update) 

235 else: 

236 spin = ui.SpinBox(layers, 1, 100, 1, self.update) 

237 

238 up = ui.Button(_('Up'), self.row_swap_next, i - 1) 

239 down = ui.Button(_('Down'), self.row_swap_next, i) 

240 delete = ui.Button(_('Delete'), self.row_delete, i) 

241 

242 self.direction_table_rows.add( 

243 [str(direction) + ':', spin, up, down, delete] 

244 ) 

245 up.active = i > 0 

246 down.active = False 

247 delete.active = i > 0 

248 

249 if i > 0: 

250 down, delete = self.direction_table_rows[-2][3:] 

251 down.active = True 

252 delete.active = True 

253 

254 def update_new_direction_and_size_stuff(self): 

255 if self.needs_4index[self.structure_cb.value]: 

256 n = 4 

257 else: 

258 n = 3 

259 

260 rows = self.new_direction_and_size_rows 

261 

262 rows.clear() 

263 

264 self.new_direction = row = ['('] 

265 for i in range(n): 

266 if i > 0: 

267 row.append(',') 

268 row.append(ui.SpinBox(0, -100, 100, 1)) 

269 row.append('):') 

270 

271 if self.method_cb.value == 'wulff': 

272 row.append(ui.SpinBox(1.0, 0.0, 1000.0, 0.1)) 

273 else: 

274 row.append(ui.SpinBox(5, 1, 100, 1)) 

275 

276 row.append(ui.Button(_('Add'), self.row_add)) 

277 

278 rows.add(row) 

279 

280 if self.method_cb.value == 'wulff': 

281 # Extra widgets for the Wulff construction 

282 self.size_radio = ui.RadioButtons( 

283 [_('Number of atoms'), _('Diameter')], 

284 ['natoms', 'diameter'], 

285 self.update_gui_size, 

286 ) 

287 self.size_natoms = ui.SpinBox( 

288 100, 1, 100000, 1, self.update_size_natoms 

289 ) 

290 self.size_diameter = ui.SpinBox( 

291 5.0, 0, 100.0, 0.1, self.update_size_diameter 

292 ) 

293 self.round_radio = ui.RadioButtons( 

294 [_('above '), _('below '), _('closest ')], 

295 ['above', 'below', 'closest'], 

296 callback=self.update, 

297 ) 

298 self.smaller_button = ui.Button(_('Smaller'), self.wulff_smaller) 

299 self.larger_button = ui.Button(_('Larger'), self.wulff_larger) 

300 rows.add(_('Choose size using:')) 

301 rows.add(self.size_radio) 

302 rows.add( 

303 [_('atoms'), self.size_natoms, _('ų'), self.size_diameter] 

304 ) 

305 rows.add( 

306 _('Rounding: If exact size is not possible, choose the size:') 

307 ) 

308 rows.add(self.round_radio) 

309 rows.add([self.smaller_button, self.larger_button]) 

310 self.update_gui_size() 

311 else: 

312 self.smaller_button = None 

313 self.larger_button = None 

314 

315 def update_structure(self, s=None): 

316 "Called when the user changes the structure." 

317 s = self.structure_cb.value 

318 if s != self.old_structure: 

319 old4 = self.needs_4index[self.old_structure] 

320 if self.needs_4index[s] != old4: 

321 # The table of directions is invalid. 

322 self.update_new_direction_and_size_stuff() 

323 self.default_direction_table() 

324 self.update_direction_table() 

325 self.old_structure = s 

326 self.c.active = self.needs_2lat[s] 

327 self.update() 

328 

329 def update_gui_method(self, *args): 

330 "Switch between layer specification and Wulff construction." 

331 self.update_direction_table() 

332 self.update_new_direction_and_size_stuff() 

333 if self.method_cb.value == 'wulff': 

334 self.layerlabel.text = _( 

335 'Surface energies (as energy/area, NOT per atom):' 

336 ) 

337 else: 

338 self.layerlabel.text = _('Number of layers:') 

339 

340 self.update() 

341 

342 def wulff_smaller(self, widget=None): 

343 "Make a smaller Wulff construction." 

344 n = len(self.atoms) 

345 self.size_radio.value = 'natoms' 

346 self.size_natoms.value = n - 1 

347 self.round_radio.value = 'below' 

348 self.apply() 

349 

350 def wulff_larger(self, widget=None): 

351 "Make a larger Wulff construction." 

352 n = len(self.atoms) 

353 self.size_radio.value = 'natoms' 

354 self.size_natoms.value = n + 1 

355 self.round_radio.value = 'above' 

356 self.apply() 

357 

358 def row_add(self, widget=None): 

359 "Add a row to the list of directions." 

360 if self.needs_4index[self.structure_cb.value]: 

361 n = 4 

362 else: 

363 n = 3 

364 idx = tuple(a.value for a in self.new_direction[1 : 1 + 2 * n : 2]) 

365 if not any(idx): 

366 ui.error(_('At least one index must be non-zero'), '') 

367 return 

368 if n == 4 and sum(idx) != 0: 

369 ui.error( 

370 _( 

371 'Invalid hexagonal indices', 

372 'The sum of the first three numbers must be zero', 

373 ) 

374 ) 

375 return 

376 new = [idx, 5, 1.0] 

377 if self.method_cb.value == 'wulff': 

378 new[1] = self.new_direction[-2].value 

379 else: 

380 new[2] = self.new_direction[-2].value 

381 self.direction_table.append(new) 

382 self.add_direction(*new) 

383 self.update() 

384 

385 def row_delete(self, row): 

386 del self.direction_table[row] 

387 self.update_direction_table() 

388 

389 def row_swap_next(self, row): 

390 dt = self.direction_table 

391 dt[row], dt[row + 1] = dt[row + 1], dt[row] 

392 self.update_direction_table() 

393 

394 def update_gui_size(self, widget=None): 

395 "Update gui when the cluster size specification changes." 

396 self.size_natoms.active = self.size_radio.value == 'natoms' 

397 self.size_diameter.active = self.size_radio.value == 'diameter' 

398 

399 def update_size_natoms(self, widget=None): 

400 at_vol = self.get_atomic_volume() 

401 dia = 2.0 * (3 * self.size_natoms.value * at_vol / (4 * np.pi)) ** ( 

402 1 / 3 

403 ) 

404 self.size_diameter.value = dia 

405 self.update() 

406 

407 def update_size_diameter(self, widget=None, update=True): 

408 if self.size_diameter.active: 

409 at_vol = self.get_atomic_volume() 

410 n = round(np.pi / 6 * self.size_diameter.value**3 / at_vol) 

411 self.size_natoms.value = int(n) 

412 if update: 

413 self.update() 

414 

415 def update(self, *args): 

416 if self.no_update: 

417 return 

418 self.element.Z # Check 

419 if self.auto.value: 

420 self.makeatoms() 

421 if self.atoms is not None: 

422 self.gui.new_atoms(self.atoms) 

423 self.gui.clear_history() 

424 else: 

425 self.clearatoms() 

426 self.makeinfo() 

427 

428 def set_structure_data(self, *args): 

429 "Called when the user presses [Get structure]." 

430 z = self.element.Z 

431 if z is None: 

432 return 

433 ref = ase.data.reference_states[z] 

434 if ref is None: 

435 structure = None 

436 else: 

437 structure = ref['symmetry'] 

438 

439 if ref is None or structure not in self.structure_names: 

440 ui.error( 

441 _('Unsupported or unknown structure'), 

442 _('Element = {0}, structure = {1}').format( 

443 self.element.symbol, structure 

444 ), 

445 ) 

446 return 

447 

448 self.structure_cb.value = self.structure_names[structure] 

449 

450 a = ref['a'] 

451 self.a.value = a 

452 if self.needs_4index[structure]: 

453 try: 

454 c = ref['c'] 

455 except KeyError: 

456 c = ref['c/a'] * a 

457 self.c.value = c 

458 

459 self.update_structure() 

460 

461 def makeatoms(self, *args): 

462 "Make the atoms according to the current specification." 

463 symbol = self.element.symbol 

464 if symbol is None: 

465 self.clearatoms() 

466 self.makeinfo() 

467 return False 

468 struct = self.structure_cb.value 

469 if self.needs_2lat[struct]: 

470 # a and c lattice constants 

471 lc = {'a': self.a.value, 'c': self.c.value} 

472 lc_str = str(lc) 

473 else: 

474 lc = self.a.value 

475 lc_str = f'{lc:.5f}' 

476 if self.method_cb.value == 'wulff': 

477 # Wulff construction 

478 surfaces = [x[0] for x in self.direction_table] 

479 surfaceenergies = [ 

480 x[1].value for x in self.direction_table_rows.rows 

481 ] 

482 self.update_size_diameter(update=False) 

483 rounding = self.round_radio.value 

484 self.atoms = wulff_construction( 

485 symbol, 

486 surfaces, 

487 surfaceenergies, 

488 self.size_natoms.value, 

489 self.structure_factories[struct], 

490 rounding, 

491 lc, 

492 ) 

493 python = py_template_wulff % { 

494 'element': symbol, 

495 'surfaces': str(surfaces), 

496 'energies': str(surfaceenergies), 

497 'latconst': lc_str, 

498 'natoms': self.size_natoms.value, 

499 'structure': struct, 

500 'rounding': rounding, 

501 } 

502 else: 

503 # Layer-by-layer specification 

504 surfaces = [x[0] for x in self.direction_table] 

505 layers = [x[1].value for x in self.direction_table_rows.rows] 

506 self.atoms = self.structure_factories[struct]( 

507 symbol, copy(surfaces), layers, latticeconstant=lc 

508 ) 

509 imp = self.import_names[struct] 

510 python = py_template_layers % { 

511 'import': imp, 

512 'element': symbol, 

513 'surfaces': str(surfaces), 

514 'layers': str(layers), 

515 'latconst': lc_str, 

516 'factory': imp.split()[-1], 

517 } 

518 self.makeinfo() 

519 

520 return python 

521 

522 def clearatoms(self): 

523 self.atoms = None 

524 

525 def get_atomic_volume(self): 

526 s = self.structure_cb.value 

527 a = self.a.value 

528 c = self.c.value 

529 if s == 'fcc': 

530 return a**3 / 4 

531 elif s == 'bcc': 

532 return a**3 / 2 

533 elif s == 'sc': 

534 return a**3 

535 elif s == 'hcp': 

536 return np.sqrt(3.0) / 2 * a * a * c / 2 

537 elif s == 'graphite': 

538 return np.sqrt(3.0) / 2 * a * a * c / 4 

539 

540 def makeinfo(self): 

541 """Fill in information field about the atoms. 

542 

543 Also turns the Wulff construction buttons [Larger] and 

544 [Smaller] on and off. 

545 """ 

546 if self.atoms is None: 

547 self.info[1].text = '-' 

548 self.info[3].text = '-' 

549 else: 

550 at_vol = self.get_atomic_volume() 

551 dia = 2 * (3 * len(self.atoms) * at_vol / (4 * np.pi)) ** (1 / 3) 

552 self.info[1].text = str(len(self.atoms)) 

553 self.info[3].text = f'{dia:.1f} Å' 

554 

555 if self.method_cb.value == 'wulff': 

556 if self.smaller_button is not None: 

557 self.smaller_button.active = self.atoms is not None 

558 self.larger_button.active = self.atoms is not None 

559 

560 def apply(self, callbackarg=None): 

561 self.makeatoms() 

562 if self.atoms is not None: 

563 self.gui.new_atoms(self.atoms) 

564 self.gui.clear_history() 

565 return True 

566 else: 

567 ui.error( 

568 _('No valid atoms.'), 

569 _( 

570 'You have not (yet) specified a consistent set of ' 

571 'parameters.' 

572 ), 

573 ) 

574 return False 

575 

576 def ok(self): 

577 if self.apply(): 

578 self.win.close()