Coverage for ase/geometry/dimensionality/rank_determination.py: 99.15%

118 statements  

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

1""" 

2Implements the Rank Determination Algorithm (RDA) 

3 

4Method is described in: 

5Definition of a scoring parameter to identify low-dimensional materials 

6components 

7P.M. Larsen, M. Pandey, M. Strange, and K. W. Jacobsen 

8Phys. Rev. Materials 3 034003, 2019 

9https://doi.org/10.1103/PhysRevMaterials.3.034003 

10""" 

11 

12from collections import defaultdict 

13 

14import numpy as np 

15 

16from ase.geometry.dimensionality.disjoint_set import DisjointSet 

17 

18# Numpy has a large overhead for lots of small vectors. The cross product is 

19# particularly bad. Pure python is a lot faster. 

20 

21 

22def dot_product(A, B): 

23 return sum(a * b for a, b in zip(A, B)) 

24 

25 

26def cross_product(a, b): 

27 return [a[i] * b[j] - a[j] * b[i] for i, j in [(1, 2), (2, 0), (0, 1)]] 

28 

29 

30def subtract(A, B): 

31 return [a - b for a, b in zip(A, B)] 

32 

33 

34def rank_increase(a, b): 

35 if len(a) == 0: 

36 return True 

37 elif len(a) == 1: 

38 return a[0] != b 

39 elif len(a) == 4: 

40 return False 

41 

42 L = a + [b] 

43 w = cross_product(subtract(L[1], L[0]), subtract(L[2], L[0])) 

44 if len(a) == 2: 

45 return any(w) 

46 elif len(a) == 3: 

47 return dot_product(w, subtract(L[3], L[0])) != 0 

48 else: 

49 raise Exception("This shouldn't be possible.") 

50 

51 

52def bfs(adjacency, start): 

53 """Traverse the component graph using BFS. 

54 

55 The graph is traversed until the matrix rank of the subspace spanned by 

56 the visited components no longer increases. 

57 """ 

58 visited = set() 

59 cvisited = defaultdict(list) 

60 queue = [(start, (0, 0, 0))] 

61 while queue: 

62 vertex = queue.pop(0) 

63 if vertex in visited: 

64 continue 

65 

66 visited.add(vertex) 

67 c, p = vertex 

68 if not rank_increase(cvisited[c], p): 

69 continue 

70 

71 cvisited[c].append(p) 

72 

73 for nc, offset in adjacency[c]: 

74 nbrpos = (p[0] + offset[0], p[1] + offset[1], p[2] + offset[2]) 

75 nbrnode = (nc, nbrpos) 

76 if nbrnode in visited: 

77 continue 

78 

79 if rank_increase(cvisited[nc], nbrpos): 

80 queue.append(nbrnode) 

81 

82 return visited, len(cvisited[start]) - 1 

83 

84 

85def traverse_component_graphs(adjacency): 

86 vertices = adjacency.keys() 

87 all_visited = {} 

88 ranks = {} 

89 for v in vertices: 

90 visited, rank = bfs(adjacency, v) 

91 all_visited[v] = visited 

92 ranks[v] = rank 

93 

94 return all_visited, ranks 

95 

96 

97def build_adjacency_list(parents, bonds): 

98 graph = np.unique(parents) 

99 adjacency = {e: set() for e in graph} 

100 for i, j, offset in bonds: 

101 component_a = parents[i] 

102 component_b = parents[j] 

103 adjacency[component_a].add((component_b, offset)) 

104 return adjacency 

105 

106 

107def get_dimensionality_histogram(ranks, roots): 

108 h = [0, 0, 0, 0] 

109 for e in roots: 

110 h[ranks[e]] += 1 

111 return tuple(h) 

112 

113 

114def merge_mutual_visits(all_visited, ranks, graph): 

115 """Find components with mutual visits and merge them.""" 

116 merged = False 

117 common = defaultdict(list) 

118 for b, visited in all_visited.items(): 

119 for offset in visited: 

120 for a in common[offset]: 

121 assert ranks[a] == ranks[b] 

122 merged |= graph.union(a, b) 

123 common[offset].append(b) 

124 

125 if not merged: 

126 return merged, all_visited, ranks 

127 

128 merged_visits = defaultdict(set) 

129 merged_ranks = {} 

130 parents = graph.find_all() 

131 for k, v in all_visited.items(): 

132 key = parents[k] 

133 merged_visits[key].update(v) 

134 merged_ranks[key] = ranks[key] 

135 return merged, merged_visits, merged_ranks 

136 

137 

138class RDA: 

139 def __init__(self, num_atoms): 

140 """ 

141 Initializes the RDA class. 

142 

143 A disjoint set is used to maintain the component graph. 

144 

145 Parameters 

146 ---------- 

147 

148 num_atoms: int The number of atoms in the unit cell. 

149 """ 

150 self.bonds = [] 

151 self.graph = DisjointSet(num_atoms) 

152 self.adjacency = None 

153 self.hcached = None 

154 self.components_cached = None 

155 self.cdim_cached = None 

156 

157 def insert_bond(self, i, j, offset): 

158 """ 

159 Adds a bond to the list of graph edges. 

160 

161 Graph components are merged if the bond does not cross a cell boundary. 

162 Bonds which cross cell boundaries can inappropriately connect 

163 components which are not connected in the infinite crystal. This is 

164 tested during graph traversal. 

165 

166 Parameters 

167 ---------- 

168 

169 i: int The index of the first atom. 

170 n: int The index of the second atom. 

171 offset: tuple The cell offset of the second atom. 

172 """ 

173 roffset = tuple(-np.array(offset)) 

174 

175 if offset == (0, 0, 0): # only want bonds in aperiodic unit cell 

176 self.graph.union(i, j) 

177 else: 

178 self.bonds += [(i, j, offset)] 

179 self.bonds += [(j, i, roffset)] 

180 

181 def check(self): 

182 """ 

183 Determines the dimensionality histogram. 

184 

185 The component graph is traversed (using BFS) until the matrix rank 

186 of the subspace spanned by the visited components no longer increases. 

187 

188 Returns 

189 ------- 

190 hist : tuple Dimensionality histogram. 

191 """ 

192 adjacency = build_adjacency_list(self.graph.find_all(), self.bonds) 

193 if adjacency == self.adjacency: 

194 return self.hcached 

195 

196 self.adjacency = adjacency 

197 self.all_visited, self.ranks = traverse_component_graphs(adjacency) 

198 res = merge_mutual_visits(self.all_visited, self.ranks, self.graph) 

199 _, self.all_visited, self.ranks = res 

200 

201 self.roots = np.unique(self.graph.find_all()) 

202 h = get_dimensionality_histogram(self.ranks, self.roots) 

203 self.hcached = h 

204 return h 

205 

206 def get_components(self): 

207 """ 

208 Determines the dimensionality and constituent atoms of each component. 

209 

210 Returns 

211 ------- 

212 components: array The component ID of every atom 

213 """ 

214 component_dim = {e: self.ranks[e] for e in self.roots} 

215 relabelled_components = self.graph.find_all(relabel=True) 

216 relabelled_dim = { 

217 relabelled_components[k]: v for k, v in component_dim.items() 

218 } 

219 self.cdim_cached = relabelled_dim 

220 self.components_cached = relabelled_components 

221 

222 return relabelled_components, relabelled_dim