Coverage for ase/geometry/dimensionality/isolation.py: 99.34%
152 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
1"""
2Implements functions for extracting ('isolating') a low-dimensional material
3component in its own unit cell.
5This uses the rank-determination method described in:
6Definition of a scoring parameter to identify low-dimensional materials
7components
8P.M. Larsen, M. Pandey, M. Strange, and K. W. Jacobsen
9Phys. Rev. Materials 3 034003, 2019
10https://doi.org/10.1103/PhysRevMaterials.3.034003
11"""
13import collections
14import itertools
16import numpy as np
18from ase import Atoms
19from ase.geometry.cell import complete_cell
20from ase.geometry.dimensionality import (
21 analyze_dimensionality,
22 rank_determination,
23)
24from ase.geometry.dimensionality.bond_generator import next_bond
25from ase.geometry.dimensionality.interval_analysis import merge_intervals
28def orthogonal_basis(X, Y=None):
30 is_1d = Y is None
31 b = np.zeros((3, 3))
32 b[0] = X
33 if not is_1d:
34 b[1] = Y
35 b = complete_cell(b)
37 Q = np.linalg.qr(b.T)[0].T
38 if np.dot(b[0], Q[0]) < 0:
39 Q[0] = -Q[0]
41 if np.dot(b[2], Q[1]) < 0:
42 Q[1] = -Q[1]
44 if np.linalg.det(Q) < 0:
45 Q[2] = -Q[2]
47 if is_1d:
48 Q = Q[[1, 2, 0]]
50 return Q
53def select_cutoff(atoms):
54 intervals = analyze_dimensionality(atoms, method='RDA', merge=False)
55 dimtype = max(merge_intervals(intervals), key=lambda x: x.score).dimtype
56 m = next(e for e in intervals if e.dimtype == dimtype)
57 if m.b == float('inf'):
58 return m.a + 0.1
59 else:
60 return (m.a + m.b) / 2
63def traverse_graph(atoms, kcutoff):
64 if kcutoff is None:
65 kcutoff = select_cutoff(atoms)
67 rda = rank_determination.RDA(len(atoms))
68 for k, i, j, offset in next_bond(atoms):
69 if k > kcutoff:
70 break
71 rda.insert_bond(i, j, offset)
73 rda.check()
74 return rda.graph.find_all(), rda.all_visited, rda.ranks
77def build_supercomponent(atoms, components, k, v, anchor=True):
78 # build supercomponent by mapping components into visited cells
79 positions = []
80 numbers = []
82 for c, offset in dict(v[::-1]).items():
83 indices = np.where(components == c)[0]
84 ps = atoms.positions + np.dot(offset, atoms.get_cell())
85 positions.extend(ps[indices])
86 numbers.extend(atoms.numbers[indices])
87 positions = np.array(positions)
88 numbers = np.array(numbers)
90 # select an 'anchor' atom, which will lie at the origin
91 anchor_index = next(i for i in range(len(atoms)) if components[i] == k)
92 if anchor:
93 positions -= atoms.positions[anchor_index]
94 return positions, numbers
97def select_chain_rotation(scaled):
99 best = (-1, [1, 0, 0])
100 for s in scaled:
101 vhat = np.array([s[0], s[1], 0])
102 norm = np.linalg.norm(vhat)
103 if norm < 1e-6:
104 continue
105 vhat /= norm
106 obj = np.sum(np.dot(scaled, vhat) ** 2)
107 best = max(best, (obj, vhat), key=lambda x: x[0])
108 _, vhat = best
109 cost, sint, _ = vhat
110 rot = np.array([[cost, -sint, 0], [sint, cost, 0], [0, 0, 1]])
111 return np.dot(scaled, rot)
114def isolate_chain(atoms, components, k, v):
116 # identify the vector along the chain; this is the new cell vector
117 basis_points = np.array([offset for c, offset in v if c == k])
118 assert len(basis_points) >= 2
119 assert (0, 0, 0) in [tuple(e) for e in basis_points]
121 sizes = np.linalg.norm(basis_points, axis=1)
122 index = np.argsort(sizes)[1]
123 basis = basis_points[index]
124 vector = np.dot(basis, atoms.get_cell())
125 norm = np.linalg.norm(vector)
126 vhat = vector / norm
128 # project atoms into new basis
129 positions, numbers = build_supercomponent(atoms, components, k, v)
130 scaled = np.dot(positions, orthogonal_basis(vhat).T / norm)
132 # move atoms into new cell
133 scaled[:, 2] %= 1.0
135 # subtract barycentre in x and y directions
136 scaled[:, :2] -= np.mean(scaled, axis=0)[:2]
138 # pick a good chain rotation (i.e. non-random)
139 scaled = select_chain_rotation(scaled)
141 # make cell large enough in x and y directions
142 init_cell = norm * np.eye(3)
143 pos = np.dot(scaled, init_cell)
144 rmax = np.max(np.linalg.norm(pos[:, :2], axis=1))
145 rmax = max(1, rmax)
146 cell = np.diag([4 * rmax, 4 * rmax, norm])
148 # construct a new atoms object containing the isolated chain
149 return Atoms(numbers=numbers, positions=pos, cell=cell, pbc=[0, 0, 1])
152def construct_inplane_basis(atoms, k, v):
154 basis_points = np.array([offset for c, offset in v if c == k])
155 assert len(basis_points) >= 3
156 assert (0, 0, 0) in [tuple(e) for e in basis_points]
158 sizes = np.linalg.norm(basis_points, axis=1)
159 indices = np.argsort(sizes)
160 basis_points = basis_points[indices]
162 # identify primitive basis
163 best = (float('inf'), None)
164 for u, v in itertools.combinations(basis_points, 2):
165 basis = np.array([[0, 0, 0], u, v])
166 if np.linalg.matrix_rank(basis) < 2:
167 continue
169 a = np.dot(u, atoms.get_cell())
170 b = np.dot(v, atoms.get_cell())
171 norm = np.linalg.norm(np.cross(a, b))
172 best = min(best, (norm, a, b), key=lambda x: x[0])
173 _, a, b = best
174 return a, b, orthogonal_basis(a, b)
177def isolate_monolayer(atoms, components, k, v):
179 a, b, basis = construct_inplane_basis(atoms, k, v)
181 # project atoms into new basis
182 c = np.cross(a, b)
183 c /= np.linalg.norm(c)
184 init_cell = np.dot(np.array([a, b, c]), basis.T)
186 positions, numbers = build_supercomponent(atoms, components, k, v)
187 scaled = np.linalg.solve(init_cell.T, np.dot(positions, basis.T).T).T
189 # move atoms into new cell
190 scaled[:, :2] %= 1.0
192 # subtract barycentre in z-direction
193 scaled[:, 2] -= np.mean(scaled, axis=0)[2]
195 # make cell large enough in z-direction
196 pos = np.dot(scaled, init_cell)
197 zmax = np.max(np.abs(pos[:, 2]))
198 cell = np.copy(init_cell)
199 cell[2] *= 4 * zmax
201 # construct a new atoms object containing the isolated chain
202 return Atoms(numbers=numbers, positions=pos, cell=cell, pbc=[1, 1, 0])
205def isolate_bulk(atoms, components, k, v):
206 positions, numbers = build_supercomponent(
207 atoms, components, k, v, anchor=False
208 )
209 atoms = Atoms(
210 numbers=numbers, positions=positions, cell=atoms.cell, pbc=[1, 1, 1]
211 )
212 atoms.wrap(eps=0)
213 return atoms
216def isolate_cluster(atoms, components, k, v):
217 positions, numbers = build_supercomponent(atoms, components, k, v)
218 positions -= np.min(positions, axis=0)
219 cell = np.diag(np.max(positions, axis=0))
220 return Atoms(numbers=numbers, positions=positions, cell=cell, pbc=False)
223def isolate_components(atoms, kcutoff=None):
224 """Isolates components by dimensionality type.
226 Given a k-value cutoff the components (connected clusters) are
227 identified. For each component an Atoms object is created, which contains
228 that component only. The geometry of the resulting Atoms object depends
229 on the component dimensionality type:
231 0D: The cell is a tight box around the atoms. pbc=[0, 0, 0].
232 The cell has no physical meaning.
234 1D: The chain is aligned along the z-axis. pbc=[0, 0, 1].
235 The x and y cell directions have no physical meaning.
237 2D: The layer is aligned in the x-y plane. pbc=[1, 1, 0].
238 The z cell direction has no physical meaning.
240 3D: The original cell is used. pbc=[1, 1, 1].
242 Parameters
243 ----------
245 atoms: ASE atoms object
246 The system to analyze.
247 kcutoff: float
248 The k-value cutoff to use. Default=None, in which case the
249 dimensionality scoring parameter is used to select the cutoff.
251 Returns
252 -------
254 components: dict
255 key: the component dimenionalities.
256 values: a list of Atoms objects for each dimensionality type.
257 """
258 data = {}
259 components, all_visited, ranks = traverse_graph(atoms, kcutoff)
261 for k, v in all_visited.items():
262 v = sorted(list(v))
264 # identify the components which constitute the component
265 key = tuple(np.unique([c for c, offset in v]))
266 dim = ranks[k]
268 if dim == 0:
269 data[('0D', key)] = isolate_cluster(atoms, components, k, v)
270 elif dim == 1:
271 data[('1D', key)] = isolate_chain(atoms, components, k, v)
272 elif dim == 2:
273 data[('2D', key)] = isolate_monolayer(atoms, components, k, v)
274 elif dim == 3:
275 data[('3D', key)] = isolate_bulk(atoms, components, k, v)
277 result = collections.defaultdict(list)
278 for (dim, _), atoms in data.items():
279 result[dim].append(atoms)
280 return result