Search code examples
pythonalgorithmmatplotlibmathpath-finding

Algorithm to find the longest cluster. (Python ideally, possibly Matlab)



I am experimenting with something called "bond percolation theory" Effectively you have some n by n lattice grid and then (randomly) with some probability p you keep or delete an edge. Here is an example: yo

Here is my code:
enter image description here


I have 2 questions for this fantastic community:

  1. How do I get the grid I inserted to appear on all the integer values, so far it is only displaying on multiples of 5. (the thin grey lines)
  2. I wish to have an algorithm that provides something called the "longest cluster" A cluster is a connected graph of edges (thick black lines) for example in the top left corner we have a cluster of 6 (upside down f shape) , a cluster of 2 (the little arrow head), a cluster of 4 (the square) and a cluster of 3 (the backwards upside L) The longest cluster is simply the longest one.

Any help is very appreciated. If I have posed this question badly please let me know or if any clarification is needed.

def graph_contruction(n,p):
for i in range(0,n):
    for t in range(0,n):
        if coin(p):
            plt.hlines(i,t,t+1)
        if coin(p):
            plt.vlines(i,t,t+1)
plt.title('A '+str(n)+ ' by ' +str(n) + ' grid with probability ' +str(p))
plt.show()

Solution

  • To give you some construct of how to think about problem 2):

    Step 1) Build a function that checks each point's associated points and returns a set of those points. Which for (0,0) would be nothing. But for (0,1) this function would return {(0,1), (1,0), (1,1), (2,0)} - a.k.a a set of associated points with the pivot point (0,1) also in it.

    Step 2) Once you have built the function in step one, iterate through all of your points to get a set of associated points for each point.

    Step 3) Now you can join sets if they have a common point in them. See below:

    set_1 = {(1,0), (1,1), (2,0)}
    
    set_2 = {(1,2), (1,1), (2,1), (1,0)}
    
    if any(x in set_1 for x in set_2):
        set_1.update(set_2) 
    

    So I've just tried to frame your thinking rather than to give you the exact code. You will probably want to use comprehension to keep the set comparisons pythonic.

    If you are really struggling I can find my code where I implemented something similar. I have looked for it today but couldn't find it. It will solve this problem if you have truly given up, but it is a fun challenge so give it a go.