예제 #1
0
    def Stats(self):
        from percolation import Percolation
        from random import randint

        self.scores = []

        for i in range(self.trials):
            grid = Percolation(N=self.n)

            # open random location until the graph percolates
            while not grid.percolates():
                grid.Open(randint(1, self.n), randint(1, self.n))

            # save the # of squares that were "open" when the grid first percolated
            self.scores.append(sum(grid.open[1:-1]) / (self.n**2))

        # generate aggregate statistics
        from numpy import mean, std
        # sample mean of percolation threshold
        self.mean = mean(self.scores)
        # sample standard deviation of percolation threshold
        self.stddev = std(self.scores)

        # get high and low endpoints of 95% confidence interval
        import numpy as np, scipy.stats as st
        self.confidenceLo, self.confidenceHi = st.t.interval(
            0.95,
            len(self.scores) - 1,
            loc=np.mean(self.scores),
            scale=st.sem(self.scores))

        return
예제 #2
0
def test_percolate(file_name):
    with open('./percolation/%s' % file_name) as f:
        a = [line.strip().split() for line in f]
    q = Percolation(int(a[0][0]))
    for x in a[1:]:
        if len(x) == 2:
            q.open(int(x[0]), int(x[1]))
    return q.percolates()
 def test_str_1(self):
     pg = Percolation(4)
     pg.open(1, 1)
     actual = io.StringIO()
     with redirect_stdout(actual):
         print(pg)
     expected = ".███\n████\n████\n████\n\n"
     self.assertEqual(expected, actual.getvalue())
 def test_str_2(self):
     pg = Percolation(4)
     for row, col in ((1, 1), (2, 2), (3, 3), (4, 4), (4, 1), (3, 2),
                      (2, 3), (1, 4)):
         pg.open(row, col)
     actual = io.StringIO()
     with redirect_stdout(actual):
         print(pg)
     expected = ".██.\n█  █\n█  █\n ██ \n\n"
     self.assertEqual(expected, actual.getvalue())
예제 #5
0
 def test(self):
     m = max(self.shape)
     rand = list(product(range(m), repeat =2))
     random.shuffle(rand)
     perco = Percolation(self.shape)
     for i in rand:
         l,c = i
         if not (perco.percolates()):
             try:
                 perco.open(l,c)
             except IndexError:
                 pass
     self.exper.append(perco)
     return None
 def __init__(self, N):
   self.visual_grid = self.make_empty_grid(N)
   self.perc = Percolation(N)
   self.N = N
   self.to_open = range(N**2)
   self.open_sites = 0
   self.run_simulation()
 def test_number_open_sites_2_b(self):
     pg = Percolation(4)
     pg.open(1, 2)
     pg.open(1, 2)  # already open, should not be counted twice
     pg.open(2, 2)
     expected, actual = 2, pg.number_of_open_sites()
     self.assertEqual(expected, actual)
예제 #8
0
 def trial_stats(self):
     p_list = []
     for i in range(self.T):
         perco = Percolation(self.N)
         while (True):
             row = random.randint(1, N)
             col = random.randint(1, N)
             perco.open(row, col)
             if perco.percolated():
                 p = float(perco.grid.count(1) / (self.N * self.N))
                 # print('P = ' + str(p))
                 break
         p_list.append(p)
     print(str(self.T) + ' Times trial Mean: ' + str(self.mean(p_list)))
     print(str(self.T) + ' Times trial Stddev: ' + str(self.stddev(p_list)))
     print(
         str(self.T) + ' Times trial confidence interval: ' +
         str(self.confidence_interval(p_list)))
예제 #9
0
    def __init__(self, n, t):
        if n <= 0 or t <= 0:
            raise ValueError("N and T should be greater than 0")

        self._vals = []
        self._t = t

        for _ in range(t):
            p = Percolation(n)
            count = 0.0
            while not p.percolates():
                x = np.random.random_integers(1, n)
                y = np.random.random_integers(1, n)
                if p.is_open(x, y):
                    continue
                else:
                    p.open(x, y)
                    count += 1
            ans = count / (n * n)
            self._vals.append(ans)
예제 #10
0
 def _simulate(self, n):
     """ Process independent percolation experiment """
     p = Percolation(n)
     while True:
         p.open(random.randint(0, n - 1), random.randint(0, n - 1))
         if p.is_percolates():
             return p.number_of_open_sites() / (n * n)
예제 #11
0
def percolateFromFile(file_name):
    '''(str) -> None '''
    try:
        f = open(file_name)
    except:
        print("ERRO: arquivo '%s' não foi encontrado" % file_name)
        return

    # leia a dimensão da grade: nos arquivos é apenas um inteiro
    # já que neles as grades são quadradas
    line = f.readline()
    n = int(line)

    # crie um objeto Percolation
    perc = Percolation((n, n))

    # crie a janela
    screen = setScreen((n, n))

    # desenhe a grade
    drawPercolation(perc, screen)

    # leia posições a serem abertas
    line = f.readline()
    running = True

    while line and running:
        # Limpa a string e Le as coordenadas
        pos = line.split()
        lin = int(pos[0])
        col = int(pos[1])

        # abra o sítio
        perc.open(lin, col)

        # desenhe a nova grade na janela
        drawPercolation(perc, screen)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # espere um pouco
        pygame.time.delay(DELAY)

        # pegue a nova posição
        line = f.readline()

    # espere o usuário fechar a janela
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

    print("Percolates: ", perc.percolates())
    print("Open sites: ", perc.no_open())
    f.close()
def stats(size, trials):
    samples = []
    total = 0.0

    for i in range(trials):
        p1 = Percolation(size)
        result = p1.threshold()
        samples.append(result)
        total = total + result

    mean = total / float(trials)

    stdev = 0.0
    for i in range(trials):
        stdev += (samples[i] - mean)**2

    stdev = sqrt(stdev / float(trials - 1))

    confLo = (mean - 1.96 * stdev) / sqrt(float(trials))
    confHi = (mean + 1.96 * stdev) / sqrt(float(trials))

    print "Sample Mean                      = %f" % mean
    print "Standard Deviation               = %f" % stdev
    print "95%% Confidence Interval         = [%f, %f]" % (confLo, confHi)
class PercolationSimulation:

  def __init__(self, N):
    self.visual_grid = self.make_empty_grid(N)
    self.perc = Percolation(N)
    self.N = N
    self.to_open = range(N**2)
    self.open_sites = 0
    self.run_simulation()

  def make_empty_grid(self, N):
    grid = []
    for i in range(N):
      grid.append([])
      for j in range(N):
        grid[i].append('0')
    return grid

  def print_grid(self, grid):
    print('\n'.join(''.join(x) for x in grid))

  def open_next_block(self):
    next_index = int(random()*len(self.to_open))
    next = self.to_open[next_index]
    del self.to_open[next_index]
    i = int(next/self.N + 1)
    j = next%self.N
    self.perc.open(i, j)
    self.visual_grid[i-1][j] = ' '
    self.open_sites += 1

  def run_simulation(self):
    while not self.perc.percolates():
      self.open_next_block()
    # self.print_grid(self.visual_grid)
    self.threshold = 1.0*self.open_sites/self.N**2
예제 #14
0
 def __init__(self, shape, T):
     self.shape = shape
     self.T = T
     n, m = shape
     tests = []
     for i in range(T):
         perc = Percolation((n, m))
         while not perc.percolates():
             lin = random.randint(0, n - 1)
             col = random.randint(0, m - 1)
             if not perc.is_open(lin, col):
                 perc.open(lin, col)
         tests.append(perc.no_open())
     testes = np.array(tests)
     self.testes = testes / (n * m)
 def __init__(self, n, trials):
     # Perform independent trials on an n-by-n grid
     if n <= 0 or trials <= 0:
         raise Exception('N and trials both need to be larger than 0')
     self.threshold = []
     self.n = n
     self.trials = trials
     for i in range(trials):
         p = Percolation(n)
         while not p.percolates():
             p.open(randint(1, n), randint(1, n))
         self.threshold.append(p.number_open_sites() / (n**2))
예제 #16
0
 def percolationStats(self):
     for board in range(self.trials):
         percolation = Percolation(self.n, self.n, board)
         print(percolation.n)
         while 1:
             percolation.open(self.randomField(), self.randomField())
             if percolation.percolates():
                 print("Percolates")
                 threshold = percolation.numberOfOpenSites() / (self.n *
                                                                self.n)
                 yield threshold
                 break
예제 #17
0
 def __init__(self, shape, T):
     grade = Percolation(shape)
     self.grade = Percolation(shape)
     self.T = T
     self.x = []  #inicia a lista de armazena os limiares de percolação
     self.numsitios = grade.op  #guarda o numero de sitios da grade
     for i in range(T):
         contagem = 0  #reinicia a contagem de sitios abertos
         while grade.percolates() == False:
             valorlinha = random.randint(
                 0, grade.lin - 1
             )  #produz um valor inteiro aleatorio dentro do shape da grade
             valorcoluna = random.randint(0, grade.col - 1)
             if grade.is_open(
                     valorlinha, valorcoluna
             ) == False:  #caso não seja BLOCKED abre o ponto da grade
                 grade.open(valorlinha,
                            valorcoluna)  #e adiciona +1 na contagem
                 contagem += 1
         self.x.append(
             contagem /
             self.numsitios)  #adiciona um valor de limiar na lista
         grade = Percolation(shape)  #refaz a grade
예제 #18
0
def main():
    L = 20
    trials = 15
    values = []

    for _ in range(trials):
        lattice = Percolation(L)
        sites = list(product(range(L), repeat=2))
        numpy.random.shuffle(sites)

        while not lattice.percolates():
            i, j = sites[0]
            sites.remove(sites[0])
            lattice.open(i, j)
            plot_lattice(lattice, labels=True)

    print(lattice.numberOfOpenSites() / L * L)
예제 #19
0
 def __init__(self, shape, T):
     self.T = T
     if type(shape) == int:
         a = shape
         b = shape
     elif type(shape) == tuple:
         a = shape[0]
         b = shape[1]
     self.abertos = np.zeros(T, dtype = int)
     self.limiares = np.zeros(T)
     for i in range (0, T):
         p = Percolation(shape)
         n = 0
         while p.percolates() != True:
             v = p.get_grid()
             lin = random.randint(0, a - 1)
             col = random.randint(0, b - 1)
             if v[lin][col] == 0:
                 p.open(lin, col)
                 n = n + 1
             self.abertos[i] = n
         self.limiares[i] = self.abertos[i]/(a*b)
예제 #20
0
def percolateIt():
    # pegue a dimensão da grade
    dim_str = input("Digite a dimensão da grade (nlins e ncols): ")
    dim_lst = dim_str.split()
    try:
        nlins = int(dim_lst[0])
        ncols = int(dim_lst[1])
    except:
        print("ERRO: dimensão devem ser dois inteiros positivos")
        return

    # crie o objeto Percolation
    perc = Percolation((nlins, ncols))

    # crie a janela
    screen = setScreen((nlins, ncols))

    # desenhe a grade inicial
    drawPercolation(perc, screen)

    # comece a abrir sítios
    running = True
    while running:
        # examine a fila de eventos
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:  # usuário clicou
                # localize o sítio clicado
                col, lin = findRec(event.pos)
                # abra o sítio [lin][col]
                perc.open(lin, col)
                # desenhe a nova grade
                drawPercolation(perc, screen)

    # relatório
    print("Percolates: ", perc.percolates())
    print("Open sites: ", perc.no_open())
 def test_n_equal_0(self):
     with self.assertRaises(ValueError):
         pg = Percolation(0)
예제 #22
0
        for log in self.log:
            (operation, data) = log.split(" ")

            if operation == "open":
                index = int(data)
                self.__draw_square(index)
                opened.append(index)
                self.p_open.config(text="{p:.2f}%".format(p=len(opened) /
                                                          (self.num**2)))
            elif operation == "percolation":
                indices = [int(s) for s in data.split(",") if int(s) in opened]
                indices.sort()
                indices = indices[:-2]

                for index in indices:
                    self.__draw_square(index, True)

                self.p_percolated.config(text="{p:.2f}%".format(
                    p=len(indices) / (self.num**2)))

            self.canvas.pack()
            self.top.update_idletasks()
            self.top.update()
            time.sleep(0.00001)


if __name__ == "__main__":
    p = Percolation(111, logging=True)
    p.percolate()
    v = Visualizer(p.log)
예제 #23
0
from percolation import Percolation
import random
from itertools import product

perco = Percolation((3, 5))
m = max(perco.shape)
lit = random.sample(list(product(range(m), repeat=2)), k=m**2)

for i in lit:
    i, j = i
    if not (perco.percolates()):
        try:
            perco.open(i, j)
            print('\n', perco)
        except IndexError:
            pass
예제 #24
0
for row in range(rows):
    grid.append([])
    for column in range(columns):
        grid[row].append(0)
random_rows = random.sample(range(0, rows), rows)
random_columns = random.sample(range(0, columns), columns)

# Pygame initialization
WINDOW_SIZE = [(columns * WIDTH + (MARGIN * columns) + MARGIN),
               (rows * HEIGHT + (MARGIN * rows) + MARGIN) + 20]
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("Percolation Finder")
clock = pygame.time.Clock()
pygame.init()

percolation = Percolation(rows)

# Does it percolate label initialization
does_it_percolate_text = pygame.font.SysFont("monospace", 12)
does_it_percolate_label = does_it_percolate_text.render(
    "Percolates: False", 1, (255, 255, 255))
screen.blit(does_it_percolate_label, (50, 565))

# Number of open sites label initialization
number_of_open_sites_text = pygame.font.SysFont("monospace", 12)
number_of_open_sites_label = number_of_open_sites_text.render(
    "Number of open sites: 0", 1, (255, 255, 255))
screen.blit(number_of_open_sites_label, (200, 565))

done = False
 def test_type(self):
     pg = Percolation(6)
     self.assertIsInstance(pg, Percolation)
예제 #26
0
from percolation import Percolation

perc = Percolation(4)
perc.open(1,0)
perc.open(2,0)
perc.open(3,0)
print perc.percolates()
perc.open(4,0)
print perc.percolates()
 def test_number_open_sites_2_a(self):
     pg = Percolation(4)
     pg.open(1, 2)
     pg.open(2, 2)
     expected, actual = 2, pg.number_of_open_sites()
     self.assertEqual(expected, actual)
 def test_number_open_sites_0(self):
     pg = Percolation(4)
     expected, actual = 0, pg.number_of_open_sites()
     self.assertEqual(expected, actual)
 def test_open_valid_site(self):
     pg = Percolation(4)
     pg.open(1, 2)
     self.assertTrue(pg.isopen(1, 2))
 def test_isopen_not(self):
     pg = Percolation(4)
     self.assertFalse(pg.isopen(1, 1))
예제 #31
0
            col = i % self.N + 1
            x1 = [col - 1, col - 1, col, col]
            y1 = [
                self.N - row + 1, self.N - row, self.N - row, self.N - row + 1
            ]
            #检查和上面连通来避免backwash问题
            if grid_value == 1:
                self.ax.fill(x1, y1, color='w')
            if self.perco.wqu2.find(i) == self.perco.wqu2.find(
                    self.perco.virtual_top):
                self.ax.fill(x1, y1, color='b')


if __name__ == '__main__':
    N = int(input('Enter your N: '))
    perco = Percolation(N)
    #手动输入
    #while(True):
    #    s = input('Enter a site as x y: ')
    #    [row,col] = [int(i) for i in s.split()]
    #    perco.open(row,col)
    #    count = count+1
    #    if perco.percolated():
    #        print(str(count)+' open site(s) to percolate the grid with size'+str(N)+'*'+str(N))
    #       break

    #随机open
    while (True):
        row = random.randint(1, N)
        col = random.randint(1, N)
        perco.open(row, col)
예제 #32
0
    def single_threshold(self):
        perc = Percolation(self.n)

        while not perc.percolates():
            perc.open(row=randint(0, self.n - 1), col=randint(0, self.n - 1))
        return perc.number_of_open_sites() / (self.n * self.n)
예제 #33
0
import random

from percolation import Percolation

parser = argparse.ArgumentParser(description='Calculate the percolation ratio')
parser.add_argument('-n', action='store', dest='n', type=int,
                    help='The grid size n * n')
parser.add_argument('-t', action='store', dest='t', type=int,
                    help='How often should the experiment be executed.')


results = parser.parse_args()
n = results.n
t = results.t

percolation_results = []
for i in range(0, results.t):
    perc = Percolation(n)
    open_sites = 0
    while not perc.percolates():
        row = random.randint(1, n)
        column = random.randint(1, n)
        if not perc.is_open(row, column):
            perc.open(row, column)
            open_sites += 1
    percolation = (open_sites * 1.0) / (n * n)
    print percolation
    percolation_results.append(percolation)

mean = sum(percolation_results) / len(percolation_results)
print "Mean: ", mean
 def test_n_equal_minus_100(self):
     with self.assertRaises(ValueError) as e:
         pg = Percolation(-100)