Coverage for ase/cluster/wulff.py: 51.52%
99 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import numpy as np
3delta = 1e-10
6def wulff_construction(
7 symbol,
8 surfaces,
9 energies,
10 size,
11 structure,
12 rounding='closest',
13 latticeconstant=None,
14 debug=False,
15 maxiter=100,
16):
17 """Create a cluster using the Wulff construction.
19 A cluster is created with approximately the number of atoms
20 specified, following the Wulff construction, i.e. minimizing the
21 surface energy of the cluster.
23 Parameters
24 ----------
25 symbol : str or int
26 The chemical symbol (or atomic number) of the desired element.
28 surfaces : list
29 A list of surfaces. Each surface is an (h, k, l) tuple or list of
30 integers.
32 energies : list
33 A list of surface energies for the surfaces.
35 size : int
36 The desired number of atoms.
38 structure : {'fcc', bcc', 'sc'}
39 The desired crystal structure.
41 rounding : {'closest', 'above', 'below'}
42 Specifies what should be done if no Wulff construction corresponds
43 to exactly the requested number of atoms. 'above', 'below', and
44 'closest' mean that the nearest cluster above or below - or the
45 closest one - is created instead.
47 latticeconstant : float (optional)
48 The lattice constant. If not given, extracted from `ase.data`.
50 debug : bool, default False
51 If True, information about the iteration towards the right cluster
52 size is printed.
54 Examples
55 --------
57 This example sets up a nanoparticle of copper in the FCC crystal
58 structure, by specifying 6 layers in the (100) directions, 9 in
59 the (110) directions and 5 in the (111) directions::
61 >>> from ase.cluster.cubic import FaceCenteredCubic
63 >>> surfaces = [(1, 0, 0), (1, 1, 0), (1, 1, 1)]
64 >>> layers = [6, 9, 5]
65 >>> lc = 3.61000
66 >>> atoms = FaceCenteredCubic('Cu', surfaces, layers, latticeconstant=lc)
68 Note that the Wulff construction currently only work with cubic lattices.
69 """
71 if debug:
72 print('Wulff: Aiming for cluster with %i atoms (%s)' % (size, rounding))
74 if rounding not in ['above', 'below', 'closest']:
75 raise ValueError(f'Invalid rounding: {rounding}')
77 # Interpret structure, if it is a string.
78 if isinstance(structure, str):
79 if structure == 'fcc':
80 from ase.cluster.cubic import FaceCenteredCubic as structure
81 elif structure == 'bcc':
82 from ase.cluster.cubic import BodyCenteredCubic as structure
83 elif structure == 'sc':
84 from ase.cluster.cubic import SimpleCubic as structure
85 elif structure == 'hcp':
86 from ase.cluster.hexagonal import HexagonalClosedPacked as structure
87 elif structure == 'graphite':
88 from ase.cluster.hexagonal import Graphite as structure
89 else:
90 error = f'Crystal structure {structure} is not supported.'
91 raise NotImplementedError(error)
93 # Check number of surfaces
94 nsurf = len(surfaces)
95 if len(energies) != nsurf:
96 raise ValueError(
97 'The energies array should contain %d values.' % (nsurf,)
98 )
100 # Copy energies array so it is safe to modify it
101 energies = np.array(energies)
103 # We should check that for each direction, the surface energy plus
104 # the energy in the opposite direction is positive. But this is
105 # very difficult in the general case!
107 # Before starting, make a fake cluster just to extract the
108 # interlayer distances in the relevant directions, and use these
109 # to "renormalize" the surface energies such that they can be used
110 # to convert to number of layers instead of to distances.
111 atoms = structure(
112 symbol,
113 surfaces,
114 5 * np.ones(len(surfaces), int),
115 latticeconstant=latticeconstant,
116 )
117 for i, s in enumerate(surfaces):
118 d = atoms.get_layer_distance(s)
119 energies[i] /= d
121 # First guess a size that is not too large.
122 wanted_size = size ** (1.0 / 3.0)
123 max_e = max(energies)
124 factor = wanted_size / max_e
125 atoms, layers = make_atoms(
126 symbol, surfaces, energies, factor, structure, latticeconstant
127 )
128 if len(atoms) == 0:
129 # Probably the cluster is very flat
130 if debug:
131 print('First try made an empty cluster, trying again.')
132 factor = 1 / energies.min()
133 atoms, layers = make_atoms(
134 symbol, surfaces, energies, factor, structure, latticeconstant
135 )
136 if len(atoms) == 0:
137 raise RuntimeError('Failed to create a finite cluster.')
139 # Second guess: scale to get closer.
140 old_factor = factor
141 old_layers = layers
142 old_atoms = atoms
143 factor *= (size / len(atoms)) ** (1.0 / 3.0)
144 atoms, layers = make_atoms(
145 symbol, surfaces, energies, factor, structure, latticeconstant
146 )
147 if len(atoms) == 0:
148 print('Second guess gave an empty cluster, discarding it.')
149 atoms = old_atoms
150 factor = old_factor
151 layers = old_layers
152 else:
153 del old_atoms
155 # Find if the cluster is too small or too large (both means perfect!)
156 below = above = None
157 if len(atoms) <= size:
158 below = atoms
159 if len(atoms) >= size:
160 above = atoms
162 # Now iterate towards the right cluster
163 iter = 0
164 while below is None or above is None:
165 if len(atoms) < size:
166 # Find a larger cluster
167 if debug:
168 print('Making a larger cluster.')
169 factor = ((layers + 0.5 + delta) / energies).min()
170 atoms, new_layers = make_atoms(
171 symbol, surfaces, energies, factor, structure, latticeconstant
172 )
173 assert (new_layers - layers).max() == 1
174 assert (new_layers - layers).min() >= 0
175 layers = new_layers
176 else:
177 # Find a smaller cluster
178 if debug:
179 print('Making a smaller cluster.')
180 factor = ((layers - 0.5 - delta) / energies).max()
181 atoms, new_layers = make_atoms(
182 symbol, surfaces, energies, factor, structure, latticeconstant
183 )
184 assert (new_layers - layers).max() <= 0
185 assert (new_layers - layers).min() == -1
186 layers = new_layers
187 if len(atoms) <= size:
188 below = atoms
189 if len(atoms) >= size:
190 above = atoms
191 iter += 1
192 if iter == maxiter:
193 raise RuntimeError('Runaway iteration.')
194 if rounding == 'below':
195 if debug:
196 print('Choosing smaller cluster with %i atoms' % len(below))
197 return below
198 elif rounding == 'above':
199 if debug:
200 print('Choosing larger cluster with %i atoms' % len(above))
201 return above
202 else:
203 assert rounding == 'closest'
204 if (len(above) - size) < (size - len(below)):
205 atoms = above
206 else:
207 atoms = below
208 if debug:
209 print('Choosing closest cluster with %i atoms' % len(atoms))
210 return atoms
213def make_atoms(symbol, surfaces, energies, factor, structure, latticeconstant):
214 layers1 = factor * np.array(energies)
215 layers = np.round(layers1).astype(int)
216 atoms = structure(symbol, surfaces, layers, latticeconstant=latticeconstant)
217 return (atoms, layers)