from sage.all import * #This is a helper function for some of our experiments: it calculates the #empirical expectation value of a given statistic by drawing, for each c in c_range, K graphs of size n #from G(n,scale(n,c)) and applying the statistic function to them. def empirical_means(n,c_range,statistic,K,verbose=False,scale= lambda n,c: c/n): ''' Generic function to run some Monte-Carlo experiments: - Scale is assumed to be a function f(n,c) between 0 and 1. - For each c in c_range, we sample K graphs from G(n,p=f(n,c)) - For each graph G we sample, we compute statistic(G) - We take return a list of relative frequencies: 1/K sum_{i=1}^K statistic(G) - Verbose tells us what we're currently sampling from (useful to track progress) ''' data = [] for current_c in c_range: if verbose: print("Currently sampling with c =",current_c) s = 0 for k in range(K): rand_G = graphs.RandomGNP(n,scale(n,current_c)) s += statistic(rand_G) data.append((current_c, s/K)) return data from collections import Counter #same but for the full distribution: returns a list of lists where #for each c in c_range we sample from G(n,scale(n,c)) the corresponding list #records pairs of values observed and their relative frequency def empirical_dists(n,c_range,statistic,K,verbose=False,scale= lambda n,c: c/n): data = [] for current_c in c_range: if verbose: print("Currently sampling with c =",current_c) histo = [] #full histogram of values for k in range(K): rand_G = graphs.RandomGNP(n,scale(n,current_c)) histo.append(statistic(rand_G)) counts = Counter(histo) if verbose: print("Data points:",counts) values_freqs = sorted([(value, count / K) for value, count in counts.items()],key=lambda x: x[0]) data.append((current_c, values_freqs)) return data