-
Notifications
You must be signed in to change notification settings - Fork 2
/
optimized_percolation.py
44 lines (37 loc) · 1.16 KB
/
optimized_percolation.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
import numpy as np
import matplotlib.pyplot as plt
def label(Lw, p):
R = np.random.rand(Lw, Lw) <= p
label = np.zeros((Lw, Lw), dtype=int)
current_label = 1
for i in range(Lw):
for j in range(Lw):
if R[i, j]:
above = label[i-1, j] if i > 0 else 0
left = label[i, j-1] if j > 0 else 0
if above == 0 and left == 0:
label[i, j] = current_label
current_label += 1
elif above != 0 and left == 0:
label[i, j] = above
elif above == 0 and left != 0:
label[i, j] = left
else:
label = find_and_replace(label, i, j, above, left)
label[i, j] = left
return label
def find_and_replace(label, i, j, above, left):
row, col = np.where(label == above)
for r, c in zip(row, col):
label[r, c] = left
return label
def main():
Lw = 34
p = 0.6
L = label(Lw, p)
print(L)
plt.imshow(L)
plt.colorbar()
plt.show()
if __name__ == "__main__":
main()