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
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 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 __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))
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
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, 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 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)
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)
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)
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 __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
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
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
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 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)
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