-
Notifications
You must be signed in to change notification settings - Fork 1
/
cluster_funcs.py
430 lines (340 loc) · 13.1 KB
/
cluster_funcs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import numpy as np
import matplotlib.pyplot as plt
from Observables_functions import get_energy_per_spin_per_lattice
from scipy.ndimage import convolve
def get_cluster_borders(array):
"""
Get the positions of each cluster in array.
Parameters:
-----------
array: nd.array
Returns:
-------
nd.array: positions ordered by columns
"""
addresses_clusters = []
borders_clusters = []
for i in range(1,np.max(array)+1):
cluster = np.where(array == i)
borders_clusters.append(get_borders(positions=cluster, L=len(array)))
return borders_clusters
def get_borders(positions, L):
"""
A cluster is represented as zeros and ones in a numpy array.
This function finds the border of a cluster and returns the position
of every element of the border.
"""
#print(positions)
if len(positions[0]) == 1:
#print(positions)
return np.array(positions).flatten()
else:
cluster = np.zeros((L,L))
borders = np.zeros((L,L))
cluster[positions] = 1
kernel = np.array([[0, 1, 0],[1, 0, 1],[0, 1, 0]])
neighbour_sums = convolve(cluster, kernel, mode='wrap')
borders[np.where(neighbour_sums == 1)] = 1
borders[np.where(neighbour_sums == 2)] = 1
borders[np.where(neighbour_sums == 3)] = 1
borders = borders*cluster
border = np.where(borders != 0)
#print('border: '+str(border))
return np.array(border).T
def temp_prob(temperature, J=1):
return 1 - np.exp(-J/np.abs(temperature))
def index_format(direction):
"""
Position in matrix transformed for use in
"""
return np.split(direction, 2)
def get_random_cluster_element(addresses):
"""
Returns a random element of a list addresses.
"""
length = len(addresses)
#print('addresses: '+str(addresses))
if len(np.shape(addresses)) == 1:
#print('normal element: '+str(addresses))
return addresses
else:
element = addresses[np.random.choice(len(addresses))]
#print('border element: '+str(element))
return element
def get_random_neighbor(array=[[0, 1], [0, -1], [1, 0], [-1, 0]]):
"""
Returns a random element from array.
"""
return np.array(array[np.random.choice(range(len(array)))])
def propagate_xy(array, boolean_array, spins, random_vector, center, direction, temperature):
initial = index_format(center)
final = index_format((center+direction) % len(array))
# check array not used before
if boolean_array[final] and boolean_array[initial]:
# check not previously part of the same cluster
if not array[initial][0] == array[final][0]:
# check spin dependent conditions
if spins_aligned(element=center,
direction=direction,
spins=spins,
random_vector=random_vector):
if temp_prob(temperature) > np.random.rand():
#print(temp_prob(temperature))
# add to cluster
array[np.where(array == array[final])] = array[initial]
# update boolean array
boolean_array[initial] = False
boolean_array[final] = False
return array, boolean_array
def propagation_round_xy(array, spins, random_vector, temperature):
"""
Propagate all the clusters in an array a single time according to the xy model.
"""
#print('propagation round...')
# Initialize boolean array at the beggining of the round
boolean_array = array < np.max(array)+1
cluster_elements = get_cluster_borders(array)
#print('cluster elements: '+str(cluster_elements))
#cluster_elements = np.delete(cluster_elements, np.where(len(cluster_elements) == 1))
random_elements = [get_random_cluster_element(element) for element in cluster_elements][1::]
#print(random_elements)
for element in random_elements:
direction = get_random_neighbor()
array, boolean_array = propagate_xy(array=array,
boolean_array=boolean_array,
center=element,
direction=direction,
spins=spins,
random_vector=random_vector,
temperature=temperature)
array = relabel_clusters(array)
return array
def sweden_wang_cluster(spins, p, random_vector, temp):
L = len(spins)
array = np.resize(np.arange(1, L*L+1), (L, L))
boolean_array = array < np.max(array)+1
cluster_elements = get_cluster_borders(array)
random_elements = [get_random_cluster_element(element) for element in cluster_elements]
neighbors = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])
for element in random_elements:
initial = index_format(element)
for neighbor in neighbors:
final = index_format((element+neighbor) % len(array))
# Check if the site to move to hasn't been already used
# Check if they are already in the same cluster
if boolean_array[final] and not array[initial] == array[final]:
spins_projection = spins_aligned(element, neighbor, spins, random_vector)
if spins_projection > 0:
if np.random.rand() < get_probability(temp, spins_projection):
array[np.where(array == array[final])] = array[initial]
#array[final] = array[initial]
boolean_array[initial] = False
return array
def get_probability(temp, spins_pojection, J=1):
#print(spins_pojection)
p = 1 - np.exp(-2*J*spins_pojection/temp)
return p
def sweden_wang_evolution(spins, temperature):
random_vector = get_vector_components(2*np.pi*np.random.rand())
clusters = sweden_wang_cluster(spins, temperature, random_vector, temperature)
spins = rotate_percolated_cluster(spins, clusters, random_vector)
return spins
def percolation_cluster(p, L):
array = np.resize(np.arange(1, L*L+1), (L, L))
boolean_array = array < np.max(array)+1
cluster_elements = get_cluster_borders(array)
random_elements = [get_random_cluster_element(element) for element in cluster_elements][1::]
neighbors = np.array([[0, -1], [1, 0], [-1, 0], [0, 1]])
for element in random_elements:
initial = index_format(element)
for neighbor in neighbors:
final = index_format((element+neighbor) % len(array))
if boolean_array[final] and not array[initial][0] == array[final][0]:
if np.random.rand() < p:
array[np.where(array == array[final])] = array[initial]
boolean_array[initial] = False
return array
def propagation_round(array, p):
"""
Propagate all the clusters in an array a single time according to a percolation model with probability p.
"""
boolean_array = array < np.max(array)+1
cluster_elements = get_cluster_borders(array)
#print('cluster elements: '+str(cluster_elements))
#cluster_elements = np.delete(cluster_elements, np.where(len(cluster_elements) == 1))
random_elements = [get_random_cluster_element(element) for element in cluster_elements][1::]
#print('random elements: '+str(random_elements))
for element in random_elements:
direction = get_random_neighbor()
if np.random.rand() < p:
array, boolean_array = propagate(array=array,
boolean_array=boolean_array,
center=element,
direction=direction)
array = relabel_clusters(array)
return array
def propagate(array, boolean_array, center, direction):
"""
Execute round of propagation in array for a single cluster.
Parameters:
----------
array: nd.darray
boolean_array: nd.darray
center: nd.array
direction: n.array
Returns:
-------
array: nd.array
boolean_array:
"""
#center = np.array(center).flatten()
#print('center: '+str(center))
initial = index_format(center)
final = index_format((center+direction) % len(array))
if boolean_array[final] and boolean_array[initial]:
if not array[initial][0] == array[final][0]:
array[np.where(array == array[final])] = array[initial]
boolean_array[initial] = False
boolean_array[final] = False
#array = relabel_clusters(array)
return array, boolean_array
def spins_aligned(element, direction, spins, random_vector):
"""
Check if two spins are aligned.
Parameters:
----------
element: nd.array
direction: nd.array
spins: nd.darray
random_vector: nd.array
Returns:
-------
boolean
"""
initial = index_format(element)
final = index_format((element+direction) % len(spins))
#print(get_vector_components(spins[initial]).flatt)
#print(random_vector)
proj1 = np.dot(get_vector_components(spins[initial]).flatten(), random_vector)
proj2 = np.dot(get_vector_components(spins[final]).flatten(), random_vector)
return proj1*proj2
def get_vector_components(angle):
"""Get x and y components of a unit vector with angle"""
return np.array([np.cos(angle), np.sin(angle)])
def percolation(invaded):
"""
Check if percolation happened in invaded. That is, check if there is a cluster
spanning the lattice along a given direction.
Parameters:
----------
invaded: nd.array
Returns:
-------
boolean
"""
L = len(invaded)
ones_vec = np.ones(L)
ones_cluster = np.zeros((L, L))
ones_cluster[np.where(invaded == np.max(invaded))] = 1
path_1 = ones_cluster.dot(ones_vec)
path_2 = ones_cluster.T.dot(ones_vec)
if 0. not in path_1 or 0. not in path_2:
percolation = True
else:
percolation = False
return percolation
def relabel_clusters(array):
"""
At the end of a propagation round, clusters label reorders the cluster from
1 to the total number of clusters than can be found by the number of different
elements in array.
Parameters:
----------
array: nd.array
Returns:
-------
array: nd.array
"""
aux = np.copy(array)
bins = np.bincount(aux.flatten())
dat = np.nonzero(bins)[0]
i = 1
sorted_dat = np.array(sorted(zip(bins[bins != 0], dat)))
for element in sorted_dat:
if element[0] != 0:
array[np.where(aux == element[1])] = i
i += 1
return array
def xy_model(L, n_steps=1):
"""
Executes IC algorithm for xy model of size L x L during
n_step for temperature.
"""
spins = 2*np.pi*np.random.rand(L, L)
invaded = np.resize(np.arange(1, L*L+1), (L, L))
temperature = 1E-10
ts = []
ims = []
n = 0
perc = False
while n < n_steps:
while not perc:
random_vector = get_vector_components(2*np.pi*np.random.rand())
invaded = propagation_round_xy(invaded, spins, random_vector, temperature)
perc = percolation(invaded)
spins = rotate_percolated_cluster(spins, invaded, random_vector)
im = plt.imshow(spins, animated=True)
ims.append([im])
ts.append(temperature)
temperature = get_temperature(spins)
n += 1
return spins, invaded, ts, ims
def rotate_percolated_cluster(spins, invaded, random_vector):
"""
Rotate spins for each cluster from invaded around random vector
with probability 1/2.
"""
random_angle = np.arctan(random_vector[0]/random_vector[1])
for i in range(np.max(invaded.flatten())):
if np.random.rand() < 1/2:
spins[np.where(invaded == i+1)] += random_angle
spins = spins % (2*np.pi)
return spins
def rotate_clusters(spins, invaded, random_vector):
"""
Rotate spins for each cluster from invaded around random vector
with probability 1/2.
"""
x, y = random_vector
rot_mat = np.array([[x,-y],[y,x]])
for i in range(int(np.max(invaded.flatten()))):
if np.random.rand() < 1/2:
spins_vec = get_vector_components(spins[np.where(invaded == i+1)][0][0])
spins[np.where(invaded == i+1)] = rot_mat.dot(spins[np.where(invaded == i+1)].T).T
return spins
def get_temperature(spins):
"""Use equipartition theorem to calculate kbT"""
return -(2/3)*np.sum(np.sum(get_energy_per_spin_per_lattice(J=1, lattice=spins)))
def percolation_model(L, p):
"""
Execute percolation model with probability p on a lattice of size L x L.
Parameters:
----------
L: int
P:float
Returns:
-------
ims: nd.darray of plt.axes objects
invaded: np.darray
"""
invaded = np.resize(np.arange(1, L*L+1), (L,L))
ims = [[plt.imshow(invaded, animated=True)]]
#step = 1
perc = False
while not perc:
invaded = propagation_round(invaded, p)
im = plt.imshow(invaded, animated=True)
ims.append([im])
perc = percolation(invaded)
# print(percolation(invaded), invaded)
return ims, invaded