示例#1
0
def decode(instance, states, N_rules, mode):

    _g = Grid2D(4, 0.5, states, 1, 4, 1)
    rng = np.random.RandomState(instance)

    if mode == 0:
        #Uniform sampling
        rules = rng.randint(states, size=(N_rules, _g.rule_length))

    if mode == 1:
        #Binomial sampling with 100 different sub-divided distributions
        splits = 100
        K = N_rules // splits
        ps = np.linspace(0, 1, K + 2)[1:-1]
        _rules = np.zeros((K, splits, _g.rule_length)).astype(int)

        for k in range(K):
            _rules[k] = rng.binomial(states - 1,
                                     ps[k],
                                     size=(splits, _g.rule_length))
        rules = _rules.reshape((N_rules, _g.rule_length))
    return rules
示例#2
0
def main_loop():
    global states
    global symm
    states = int(input("Enter number of states: "))
    symm = 2  #int(input("Enter neighbourhood type (0,1 or 2): "))
    neighbours = 1  #int(input("Enter size of cell neighbourhood: "))
    global size
    size = int(input("Enter size of grid: "))
    global iterations
    iterations = int(input("Enter number of iterations: "))
    global g
    global screendata
    global matrix
    global data
    global colour
    colour = "gnuplot2"
    inp = "a"
    mu = 0.7
    sig = 0.3
    g = Grid2D(size, 0.5, states, neighbours, iterations, symm)

    while inp != "q":
        #inp = str(input(":"))
        inp = str(input(":"))
        if inp == "h":
            #Print help.txt to terminal
            f = open("text_resources/help.txt", "r")
            print(f.read())
            f.close()
        if inp == "r":
            #Rerun the same rule on different initial state
            g.run()
            ani_display()
        if inp == "":
            #Generate new rule and run
            g.rule_gen(mu, sig)
            g.run()
            ani_display()
        if inp == "fft":
            _, _, _, stat = g.fft()
            """
            s = g.size//2
            stat[:,s,s]=0
            for i in range(g.states):
                plt.imshow(np.abs(stat[i]),extent=[-s,s,-s,s],cmap=colour)
                plt.colorbar()
                plt.show()
            #print(g.fft())
            """
            ani_display(7)
            #ani_display()
        """
        if inp=="auto":
            d = int(input("Iteration depth: "))
            rs,ps = g.auto_evolve(d)
            print(ps)
            for i in range(d):
                g.rule=rs[i]
                g.run()
                ani_display()
        if inp=="metric":
            a = g.get_metrics(4)
            print(a)
            print(a.shape)
        if inp=="gol":
            g.rule = np.array([0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0])
            g.run()
            ani_display()
        """
        if inp == "info":
            g.print_info()

        if inp == "print":
            g.print_rule()
        """
        if inp=="dmat":
            mat,err_mean,err_var,err = g.density_matrix()
            print(err_mean)
            print(err_var)
            plt.matshow(mat)
            plt.ylabel("Inputs")
            plt.xlabel("Outputs")
            plt.show()
            plt.plot(err)
            plt.show()
        """
        if inp == "multi":
            read_saved_rules(neighbours, states, symm)
            file1 = str(input("Enter rule 1: "))
            g.rule_load(file1)
            rule1 = g.rule

            file2 = str(input("Enter rule 2: "))
            g.rule_load(file2)
            rule2 = g.rule

            file3 = str(input("Enter rule 3: "))
            g.rule_load(file3)
            rule3 = g.rule

            file4 = str(input("Enter rule 4: "))
            g.rule_load(file4)
            rule4 = g.rule

            g.run_parallel(rule1, rule2, rule3, rule4)
            ani_display()
        if inp == "c":
            g.run(False)
            ani_display()
        if inp == "ms":
            mu = float(input("Enter mu: "))
            sig = float(input("Enter sigma: "))
            g.rule_gen(mu, sig)
            g.run()
            ani_display()

        if inp == "t":
            #tranpose output
            #g.rule_gen(mu,sig)
            g.run()
            ani_display(mode=4)

        if inp == "sm":
            #Apply image smoothing to output
            g.run()
            ani_display(mode=1)
        if inp == "g":
            #Change rule generation mode
            g.rule_mode = 1 - g.rule_mode
        """
        #if inp=="tsmooth":
            #Apply image smoothing and tranpose output
        #    g.run()
        #    ani_display(mode=2)

        #if inp=="diff":
        #    #double derivative
        #    g.run()
        #    ani_display(mode=5)
        if inp=="rt":
            #Rerun same rule, transposed
            g.run()
            ani_display(mode=4)
        #if inp=="lyap":
        #    g.lyap()
        #    ani_display()
        """
        if inp == "s":
            #save current rule
            filename = str(input("Enter rule name: "))
            g.rule_save(filename)
        if inp == "l":
            #load from saved rules
            try:
                read_saved_rules(neighbours, states, symm)
                filename = str(input("Enter rule name: "))
                g.rule_load(filename)

            except Exception as e:
                print("No saved rules yet")
            g.run()
            ani_display()
        if inp == "p":
            #permute current rule and rerun
            g.rule_perm()
            g.run()
            ani_display()
        """
        if inp=="d":
            #Change initial state density  
            d = float(input("Enter initial density: "))
            g = Grid2D(size,d,states,neighbours,iterations)
        """
        if (inp == "+" or inp == "*" or inp == "-" or inp == "a" or inp == "z"
                or inp == "b"):
            #Combine 2 rules in some way
            read_saved_rules(neighbours, states, symm)
            rule1 = str(input("Enter first rule: "))
            rule2 = str(input("Enter second rule: "))
            g.rule_comb(rule1, rule2, inp)
            g.run()
            ani_display()
        if inp == "i":
            #Invert rule
            g.rule_inv()
            g.run()
            ani_display()
        if inp == "x":
            g.rule_swap()
            g.run()
            ani_display()
        if inp == "v":
            g.rule_roll(int(input("Enter roll amount: ")))
            g.run()
            ani_display()
        if inp == "w":
            #Smooth rule
            am = int(input("Enter smoothing amount: "))
            g.rule_smooth(am)
            g.run()
            ani_display()
        #if inp=="f":
        #fold rule
        #    am = int(input("Enter folding amount: "))
        #    g.rule_fold(am)
        #    g.run()
        #    ani_display()
        #if inp=="ch":
        #change initial conditon type
        #    g.change_start_type()
        #if inp=="e":
        #return rule entropy
        #    print(g.rule_entropy())
        #en = g.entropy()
        #plt.plot(en)
        #plt.show()
        if inp == "2d":
            #Project output onto 2d surface
            axis = int(input("Enter axis: "))
            snapshot(axis)

        if inp == "stat":

            stationary_summary()
            #axis = int(input("Enter axis: "))
            #if axis==0:
            #    plt.matshow(g.im_out()[iterations//2],cmap=colour)
            #if axis==1:
            #    plt.matshow(g.im_out()[:,size//2],cmap=colour)
            #if axis==2:
            #    plt.matshow(g.im_out()[:,:,size//2],cmap=colour)
            #plt.show()

        if inp == "m":
            am = float(input("Enter mutation amount (0-1): "))
            g.run_mutate(am)
            ani_display()
            best = int(input("Select best rule (1-4): "))
            g.choose_offspring(best)
            g.run()
            ani_display()
        """
示例#3
0
import os
#import itertools

N_rules = 1000
N_obs_reps = 4
states = int(sys.argv[1])
instance = int(sys.argv[2])
size = 128
iterations = 128

try:
    os.mkdir(str(states) + "_state_results")
except OSError:
    print("Failed to create directory")

g = Grid2D(size, 0.5, states, 1, iterations, 1)
rng = np.random.RandomState(instance)
rules = rng.randint(states, size=(N_rules, g.rule_length))
print(rules)
observables = np.zeros((N_rules, 18))
mats = np.zeros((N_rules, states, states))
e_data = np.zeros((N_rules, 512))
l_data = np.zeros((N_rules, g.size // 2))
mf_err = np.zeros((N_rules, 512))
for i in range(N_rules):
    print(i)
    g.rule = rules[i]
    observables[i], mats[i], e_data[i], l_data[i], _, mf_err[
        i] = g.get_metrics(N_obs_reps)

np.save(
示例#4
0
def main():
    #Start with population of rules
    np.seterr(all="ignore")
    global states
    global symm
    symm = 2
    neighbours = 1
    global size
    size = 128
    global iterations
    iterations = 256
    global g
    global screendata
    global matrix
    global data
    global colour
    colour = "gist_earth"
    #mu=0.5
    #sig=0.2

    N_obs_reps = 2
    states = int(sys.argv[1])
    instance = int(sys.argv[2])

    K = 20  # number of rules from breeding pool
    I = 100  # number of iterations
    N_rules = 100  # number of rules per generation
    mutation = 0.02  # chance of random mutations being applied

    try:
        os.mkdir(str(states) + "_state_genetic_results")
    except OSError:
        pass
        #print("Failed to create directory")
    print("Running " + str(states) + " state rules instance " + str(instance))

    g = Grid2D(size, 0.5, states, neighbours, iterations, symm)
    g.rule_mode = 1

    all_rules = np.zeros((I, N_rules, g.rule_length)).astype(int)
    all_preds = np.zeros((I, N_rules))
    all_obs = np.zeros((I, N_rules, 18))
    all_tmats = np.zeros((I, N_rules, states, states))

    #Initialise pool of rules to breed from
    for r in range(N_rules):
        g.rule_gen()
        all_rules[0, r] = g.rule
        all_preds[0, r], all_obs[0, r], all_tmats[0,
                                                  r] = g.predict_interesting()

#Iterate across generations
    for i in range(1, I):

        #Randomly sample best rules of previous generation
        ps = all_preds[i - 1] / np.sum(all_preds[i - 1])
        max_k = np.random.choice(N_rules, K, p=ps, replace=False)
        best_rules = all_rules[i - 1, max_k]
        best_preds = all_preds[i - 1, max_k]
        best_obs = all_obs[i - 1, max_k]
        best_tmats = all_tmats[i - 1, max_k]

        not_best_rules = np.delete(all_rules[i - 1], max_k, axis=0)
        not_best_preds = np.delete(all_preds[i - 1], max_k, axis=0)
        not_best_obs = np.delete(all_obs[i - 1], max_k, axis=0)
        not_best_tmats = np.delete(all_tmats[i - 1], max_k, axis=0)

        #Cross breed the best K rules from previous generation
        new_rules = rule_crossover(K, best_rules)
        new_preds = np.zeros(K)
        new_obs = np.zeros((K, 18))
        new_tmats = np.zeros((K, states, states))
        replace = np.random.choice(N_rules - K, K, replace=False)

        #Evaluate newly bred rules
        for k in range(K):
            g.rule = new_rules[k]
            #Apply mutation
            if np.random.random() < mutation:
                g.rule_random_mod()
                new_rules[k] = g.rule

            new_preds[k], new_obs[k], new_tmats[k] = g.predict_interesting()

            #Replace random bad rules with new generation of rules
            not_best_rules[replace[k]] = new_rules[k]
            not_best_preds[replace[k]] = new_preds[k]
            not_best_obs[replace[k]] = new_obs[k]
            not_best_tmats[replace[k]] = new_tmats[k]

        #Recombine breeder and mixed bad and bred rules
        all_rules[i] = np.vstack((best_rules, not_best_rules))
        all_preds[i] = np.concatenate((best_preds, not_best_preds))
        all_obs[i] = np.vstack((best_obs, not_best_obs))
        all_tmats[i] = np.vstack((best_tmats, not_best_tmats))

    #print(new_rules)
    #print(min_k)
    #print(max_k)
    np.save(
        str(states) + "_state_genetic_results/rules" + str(instance) + ".npy",
        all_rules)
    np.save(
        str(states) + "_state_genetic_results/predictions" + str(instance) +
        ".npy", all_preds)
    np.save(
        str(states) + "_state_genetic_results/observables" + str(instance) +
        ".npy", all_obs)
    np.save(
        str(states) + "_state_genetic_results/transition_mats" +
        str(instance) + ".npy", all_tmats)
    print(all_preds)
示例#5
0
def main():
    np.seterr("ignore")
    global states
    global symm
    states = 2
    symm = 2
    neighbours = 1
    global size
    size = 128
    global iterations
    iterations = 128
    global g
    global screendata
    global matrix
    global data
    global colour
    colour = "nipy_spectral"
    #mu=0.5
    #sig=0.2
    g = Grid2D(size, 0.5, states, neighbours, iterations, symm)

    #N=16
    #data = perm_explore(128)
    #data = hamming_explore(128,2)
    #print(data)

    #data = random_walk_explore(128)
    #print(data)
    #np.save("random_walk_gol_rules",data)

    #data = smooth_perm_explore(32)
    #np.save("4state_rules_sp_32_16",data)
    """
	r1 = np.load("8state_rules_sp_32_1.npy")
	r2 = np.load("8state_rules_sp_32_2.npy")
	r3 = np.load("8state_rules_sp_32_3.npy")
	r4 = np.load("8state_rules_sp_32_4.npy")
	r5 = np.load("8state_rules_sp_32_5.npy")
	r6 = np.load("8state_rules_sp_32_6.npy")
	r7 = np.load("8state_rules_sp_32_7.npy")
	r8 = np.load("8state_rules_sp_32_8.npy")
	r9 = np.load("8state_rules_sp_32_9.npy")
	r10 = np.load("8state_rules_sp_32_10.npy")
	r11 = np.load("8state_rules_sp_32_11.npy")
	r12 = np.load("8state_rules_sp_32_12.npy")
	r13 = np.load("8state_rules_sp_32_13.npy")
	r14 = np.load("8state_rules_sp_32_14.npy")
	r15 = np.load("8state_rules_sp_32_15.npy")
	r16 = np.load("8state_rules_sp_32_16.npy")
	rules = np.vstack((r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16))
	print(rules.shape)
	"""
    #np.save("Data/8state_rules_sp_combined",rules)

    #data = np.load("8state_ml_data.npy")
    #print(data.shape)

    ###rules = np.load("Data/2state_rules_combined.npy")
    ###generate_observables(4,rules)
    """	

	g.rule = rules[0,2:]
	states = g.states
	print(states)

	R = rules.shape[0]
	print("_"*R)
	
	mats = np.zeros((R,states,states))
	for i in range(R):
		g.rule = rules[i,2:]
	
		mats[i] = g.density_matrix()
		sys.stdout.write("#")
		sys.stdout.flush()

	#np.save(str(states)+"state_ml_data.npy",observables)
	np.save(str(states)+"state_transition_matrices.npy",mats)
	
	#observables = np.load("2state_ml_data.npy")
	print(observables[0])
	print(observables.shape)
	"""

    #print(rules.shape)
    #print(rules[1])
    #rules = np.load("8state_rules_sp_combined.npy")

    #plot_observables(3,7)

    #good mean field examples - 150, 170, 207, 280

    #mean_field(280,100)

    #--- Plotting stuff for report

    #ns = np.random.choice(512,size=128)
    #l_data = np.load("4state_divergence_raw.npy")[ns]
    #print(np.sum(rules[:,1]==1))
    #lyap_fit(l_data,rules[:,0],rules[:,1])

    #l_data = np.load("4state_divergence_raw.npy")[ns]
    #rules = np.load("4state_ml_data.npy")[ns]
    #print(np.sum(rules[:,1]==1))
    #lyap_fit(l_data,rules[:,0],rules[:,1])

    plot_observables(1, 4)
    plot_observables(7, 16)
    plot_observables(1, 7)
    plot_observables(7, 4)