def printBestFitness(pop):
    e,ellipse,p = GA.getEllipse(pop)
    r = np.zeros((100,100))
    for i in range (m.shape[0]):
        for j in range (m.shape[1]):
            r[i][j]=m[i][j]
    for j in range(len(ellipse)):
        r[ellipse[j][0],ellipse[j][1]]=150
    I.Matrix2Image(r)
Esempio n. 2
0
def parallel_run(ga:callable, runs:int):
    #logging.basicConfig(level=logging.DEBUG, format='%(message)s')
    #my_log()

    solutions = []
    N_process = 7
    hits = 0
    tp = ThreadPool(processes=N_process)

    results = mp.Queue(2*N_process)
    completedTasks = 0

    debug = DebugExecutions()

    for i in range(min(N_process, runs)):
        population = CryptoArithmetic.makeSpecimen(100)
        tp.apply_async(ga, args= (population,), callback=results.put)

    while completedTasks < runs:
        res = results.get()
        completedTasks += 1
        GA.debug(res['population'], res['best'])
        solution = debug.inspect(res)
        if solution:
            solutions.append(solution)

        if completedTasks >= runs:
            break
        population = CryptoArithmetic.makeSpecimen(100)
        tp.apply_async(ga, args= (population,), callback=results.put)
    tp.close()
    tp.terminate()

    hits = debug.hits
    hits_rate = round((hits/runs)*100, 2)
    logging.info("   CONVERGENCE of {}% ; {} times in {}!".format(hits_rate, hits, runs))
    logging.info("   Needed, in general, {} Generations.".format(debug.generation))
    for s in solutions:
        logging.debug(s)
        logging.debug(CryptoArithmetic.CA_str_values(s.chromosome))
    #GA.init.first_time = True
    return hits_rate
Esempio n. 3
0
def AG_pequeno():
    logging.basicConfig(level=logging.DEBUG, format='%(message)s', filename="AG_pequeno.txt", filemode='w')
    #my_log()

    CryptoArithmetic.getExpression("robert", "donald", "gerald")
    #CryptoArithmetic.getExpression("money", "send", "more")
    population = CryptoArithmetic.makeSpecimen(10)

    Selection.Tournament.__defaults__ = (2,)
    #GA.SELECT = Selection.Tournament
    population, generation, best = GA.init(population, num_generations=10, birthRate=40, mutationRate=10)
Esempio n. 4
0
 def mutWithProb(self, child):
     newChild = GeneticAlgorithm.timetable(self.problem)
     newChild.matrix = [x[:] for x in child.matrix]
     newChild.mutate()
     newChild.objective()
     if newChild.obj <= child.obj:
             child.matrix = newChild.matrix
             child.obj = newChild.obj
             child.rowcosts = newChild.rowcosts
     elif random.random() < math.exp(-(newChild.obj-child.obj) / self.T):
             child.matrix = newChild.matrix
             child.obj = newChild.obj
Esempio n. 5
0
def main():
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    my_log()

    hits = 0
    for i in range(40):
        CryptoArithmetic.getExpression("send", 9567, "more", 1085, "money", 10652)
        population = CryptoArithmetic.makeSpecimen(40)

        population = GA.init(population)
        best = Selection.getBestSpecimen(population)
        if best.fitness == CryptoArithmetic.MAX_VALUE:
            hits += 1
    print("\n  the GA found the answer {} times in 100!".format(hits))
Esempio n. 6
0
def AG_padrao_serial(runs:int):
    #logging.basicConfig(level=logging.DEBUG, format='%(message)s')
    CryptoArithmetic.getExpression("money", "send", "more")

    hits = 0
    for i in range(runs):
        #file = 'ag' + str(i) + '.txt'
        #logging.basicConfig(level=logging.DEBUG, format='%(message)s', filename=file)
        #random.seed(i)

        population = CryptoArithmetic.makeSpecimen(100)
        population = GA.init(population, num_generations=50, birthRate=60, mutationRate=5)
        hits = debug_execs(population)
    print("\n  Convergence of {}% !".format((hits/runs)*100))
    print("  the GA found the answer {} times in {}!".format(hits, runs))
Esempio n. 7
0
import tkinter as tk
import random
import os
import math

# Input layer structure
il = np.array([(0, 0, 0, 0, 0, 0)])
il.shape = (6, 1)
# Hidden layer structure
hl1 = np.zeros((4, 1))
# Output layer structure
ol = np.zeros((2, 1))
# The complete layer structure
layers = [il, hl1, ol]

geneticAlgorithm = ga.GeneticAlgorithm(layers, os.getcwd() + "/DNA")

window = tk.Tk()
window.title("Text Color Picker")


def rgb(inputRgb):
    return "#%02x%02x%02x" % inputRgb


genePoolSize = 50
repeatSize = 25

# Creates random gene pool of 15
geneticAlgorithm.generateGenePool(
    genePoolSize,
Esempio n. 8
0
def main():

    seed = 100
    random.seed(seed)
    np.random.seed(seed)

    SampleNum = 1000  #Number of Monte Carlo Sample
    numNodes = 30  #Number of nodes
    emerg_nodes = [9, 17]

    #genetic algorithm parameters
    GA_Reinfoce_open = 1  #run GA solve the repairment problem
    GA_Construct_open = 0  #run GA solve the construction problem
    pareto = 1  #run GA to find the pareto frontier when the objectives are conflict
    #GA parameters
    num_population = 10  #number of populations
    max_iteration = 500  #maximum number of iterations
    max_time = 60  #maximum runtime
    crossover_rate = 0.7  #probabilty of crossover
    mutation_rate = 0.3  #probability of crossover
    top = 4  #number of chromos selected fromthe top of ranked population
    investment = 0  #budget

    #V = range(1,numNodes+1) #set of nodes or vertices representing the cities in the network

    #set of edges or arcs representingthe roalds connected to nodes in the network
    E = [(1, 2), (1, 4), (2, 5), (3, 5), (4, 9), (5, 6), (5, 9), (6, 10),
         (6, 11), (7, 11), (8, 9), (9, 10), (9, 12), (10, 13), (10, 14),
         (11, 14), (12, 13), (13, 16), (13, 17), (15, 16), (16, 19), (17, 18),
         (17, 19), (17, 22), (18, 20), (19, 21), (19, 22), (20, 22), (20, 23),
         (21, 26), (22, 24), (22, 29), (22, 30), (23, 25), (23, 24), (26, 27),
         (27, 28)]

    print "number of bridge", len(E)

    #****************************input end***************************************

    #create the network according to above input

    G = Network()
    G.addnode(numNodes)
    G.addemergenode(emerg_nodes)
    G.addarc(E)
    G.addlength()

    #devide the bridges to two classes with 19 and 18 respectively

    bridgeclass1, bridgeclass2 = [], []
    for headnode, tailnode in G.arcs:
        if headnode < tailnode:
            if random.random() < 0.5:
                if len(bridgeclass1) < 38:
                    bridgeclass1.append((headnode, tailnode))
                    bridgeclass1.append((tailnode, headnode))
                else:
                    bridgeclass2.append((headnode, tailnode))
                    bridgeclass2.append((tailnode, headnode))

            else:
                if len(bridgeclass2) < 38:
                    bridgeclass2.append((headnode, tailnode))
                    bridgeclass2.append((tailnode, headnode))
                else:
                    bridgeclass1.append((headnode, tailnode))
                    bridgeclass1.append((tailnode, headnode))

    #assign same mean for each class
    reliability_mean1, reliability_mean2 = [], []
    for headnode, tailnode in bridgeclass1:
        if headnode < tailnode:
            reliability_mean1.append(0.7)

    for headnode, tailnode in bridgeclass2:
        if headnode < tailnode:
            reliability_mean2.append(0.6)

    #use these mean values to generate 19 random number from MVND

    reliability_COV1 = []
    with open('reliability_COV1.txt', 'r') as f:
        for line in f:
            reliability_COV1.append(map(float, line.split(',')))

    f.close()

    reliability_COV2 = []
    with open('reliability_COV2.txt', 'r') as f:
        for line in f:
            reliability_COV2.append(map(float, line.split(',')))

    f.close()

    #check the length of mean and cov
    if len(reliability_mean1) == len(reliability_COV1):
        #change the coefficients fo variation to covariance: var = (mean*cov)**2
        reliability_Covar1 = cov_to_covar(reliability_mean1, reliability_COV1)
        true_reliability_mean_list1 = MNDNgenerator(reliability_mean1,
                                                    reliability_COV1)
    elif len(reliability_mean1) == len(reliability_COV2):
        #change the coefficients fo variation to covariance: var = (mean*cov)**2
        reliability_Covar1 = cov_to_covar(reliability_mean1, reliability_COV2)
        true_reliability_mean_list1 = MNDNgenerator(reliability_mean1,
                                                    reliability_COV2)
        pass
    else:
        sys.exit(
            "Numpy Error message:  mean and cov must have same length, mean is {} and cov is {}"
            .format(len(reliability_mean1), len(reliability_COV1)))

    #assign these random values to each bridge in class1
    bridge_true_reliability_mean = {}
    i = 0
    for headnode, tailnode in bridgeclass1:
        if headnode < tailnode:

            bridge_true_reliability_mean[
                headnode, tailnode] = true_reliability_mean_list1[i]
            bridge_true_reliability_mean[
                tailnode, headnode] = bridge_true_reliability_mean[headnode,
                                                                   tailnode]
            i += 1

    #use these mean values to generate 16 random numbers  from MVND

    #check the length of mean and cov
    if len(reliability_mean2) == len(reliability_COV2):
        #change the coefficients fo variation to covariance: var = (mean*cov)**2
        reliability_Covar2 = cov_to_covar(reliability_mean2, reliability_COV2)
        true_reliability_mean_list2 = MNDNgenerator(reliability_mean2,
                                                    reliability_COV2)
    elif len(reliability_mean2) == len(reliability_COV1):
        #change the coefficients fo variation to covariance: var = (mean*cov)**2
        reliability_Covar2 = cov_to_covar(reliability_mean2, reliability_COV1)
        true_reliability_mean_list2 = MNDNgenerator(reliability_mean2,
                                                    reliability_COV1)
    else:
        sys.exit(
            "Numpy Error message:  mean and cov must have same length, mean is {} and cov is {}"
            .format(len(reliability_mean2), len(reliability_COV2)))

    #assign these random values to each bridge in class2
    i = 0
    for headnode, tailnode in bridgeclass2:
        if headnode < tailnode:
            if (headnode, tailnode) in bridge_true_reliability_mean.keys() or (
                    tailnode, headnode) in bridge_true_reliability_mean.keys():
                sys.exit("Duplicate edges in both bridge classes")
                print headnode, tailnode

            bridge_true_reliability_mean[
                headnode, tailnode] = true_reliability_mean_list2[i]
            bridge_true_reliability_mean[
                tailnode, headnode] = bridge_true_reliability_mean[headnode,
                                                                   tailnode]
            i += 1

    #use bridge_true_reliability_mean to generate distribution for each bridge named hazard correlation

    hazard_mean = []
    for headnode, tailnode in G.arcs:
        if headnode < tailnode:
            hazard_mean.append(bridge_true_reliability_mean[headnode,
                                                            tailnode])

    hazard_matrix = hazard_matrix_compute.generate_hazard()

    #generate ADT mean from a Uniform distribution
    ADT_mean = {}
    for headnode, tailnode in G.arcs:
        if headnode < tailnode:
            ADT_mean[headnode, tailnode] = random.randint(200, 3000)

    #generate cost mean from a normal distribution
    cost_mean = {}
    for headnode, tailnode in G.arcs:
        if headnode < tailnode:
            cost_mean[headnode, tailnode] = 5 * (
                G.length[headnode, tailnode] / 100 +
                (1 - bridge_true_reliability_mean[headnode, tailnode]))

    #export the parameters of bridges
    f = open('bridge_parameters.txt', 'w')
    f.write('bridge :  reliability, ADT, length, cost\n')
    for key, value in bridge_true_reliability_mean.items():
        if key[0] < key[1]:
            f.write('{}:{},{},{}, {}\n'.format(key, value, ADT_mean[key],
                                               G.length[key], cost_mean[key]))
    f.close()

    f1 = open('network original resilience.txt', 'w')
    f1.close()
    f2 = open('network GA Repair resilience.txt', 'w')
    f2.close()

    #Monete Carlo Sampling Starts---------------------------------------------------------------------------------
    for sample_ID in xrange(1, 2):  #SampleNum

        seed = 7
        random.seed(seed)
        np.random.seed(seed)

        #Monte Carlo Sampling on ADT
        ADT_sample = []

        for key, value in ADT_mean.items():
            #ADT_sample.append(value)
            #ADT_sample.append(random.normalvariate(value, 0.08*value))
            ADT_sample.append(random.normalvariate(value, 0.08 * value))
        #print ADT_sample

        G.addADTT(ADT_sample)

        #print G.ADTT

        #Monte Carlo Sampling on ADT
        cost_sample = []
        for key, value in cost_mean.items():
            cost_sample.append(value)
            #cost_sample.append(random.normalvariate(value, 0.08*value))

        G.addcost(cost_sample)

        #print G.cost

        #Generate SampleNum of Monete Carlo Samples
        #check the length of mean and cov
        true_reliability_sample_list = []
        if len(hazard_mean) == len(hazard_matrix):
            #transfer hazard cov to hazard covar
            hazard_covar_matrix = cov_to_covar(hazard_mean, hazard_matrix)
            true_reliability_sample_list = MNDNgenerator(
                hazard_mean, hazard_covar_matrix)
        else:
            sys.exit(
                "Numpy Error message:  mean and cov must have same length, mean is {} and cov is {}"
                .format(len(hazard_mean), len(hazard_matrix)))

        #true_reliability_sample_list = hazard_mean

        G.addresilience(true_reliability_sample_list.tolist())
        #G.addresilience(true_reliability_sample_list)

        #G.resilience[1,2], G.resilience[2,1] = 1,1

        #for key, value in G.resilience.items():
        #G.resilience[key] = 0.99
        #G.resilience[23,24], G.resilience[24,23] = 0.99, 0.99
        #G.resilience[23,25], G.resilience[25,23] = 0.99, 0.99

        nodelist = copy.deepcopy(G.nodes)  #store the orginal node list
        edgelist = copy.deepcopy(G.arcs)  #store the orginal node list

        maxADTT = max(G.ADTT.values())
        minADTT = min(G.ADTT.values())
        #Normal_ADTT = minnormalize(G.ADTT, maxADTT, minADTT, 1)
        #Normal_ADTT = sumnormalize(G.ADTT, 1)

        L, Length_Path, Fresilience_Path, Path_ADTT = PS.main(
            G.nodes, G.arcs, G.emergnode, G.length, G.resilience,
            G.ADTT)  #all passageway between node pair i and j, for all i and j

        f = open('Independet_Paths.txt', 'w')
        f.write('Sample ID {}\n'.format(sample_ID))
        for i, j in L.keys():
            f.write(
                'nodes pair: ({},{}), Total independent paths {} \n '.format(
                    i, j, len(L[i, j].keys())))
            for k in L[i, j].keys():
                f.write('{},{},{},{},{}\n'.format(k, L[i, j][k],
                                                  Length_Path[i, j][k],
                                                  Fresilience_Path[i, j][k],
                                                  Path_ADTT[i, j][k]))

        f.close()

        #get the max and min value from L_pk(i,j)
        #Max_Length_Path, Min_Length_Path, Sum_Length_Path = -float("inf"), float("inf"), 0
        #for key1,key2 in Length_Path.keys():
        #for key3,value in Length_Path[key1,key2].items():
        #Sum_Length_Path += value
        #if value < Min_Length_Path:
        #Min_Length_Path = value
        #if value > Max_Length_Path:
        #Max_Length_Path = value

        #Normal_Path_Length = {}    #normalized length of path
        #for key1,key2 in Length_Path.keys():
        #Normal_Path_Length[key1,key2] = {}
        #for key3,value in Length_Path[key1,key2].items():
        #Normal_Path_Length[key1,key2][key3] = (Max_Length_Path - value)/(Max_Length_Path - Min_Length_Path)

        #normmalize the path length
        Normal_Path_Length = {}
        for headnode, tailnode in Length_Path.keys():
            Normal_Path_Length[headnode, tailnode] = {}
            if len(Length_Path[headnode, tailnode].keys()) == 1:
                Normal_Path_Length[headnode, tailnode][1] = 1
            elif len(Length_Path[headnode, tailnode].keys()) > 1:
                Temp_Sum = 0
                for k, value in Length_Path[headnode, tailnode].items():
                    Temp_Sum += value
                Normal_sum = 0
                for k, value in Length_Path[headnode, tailnode].items():
                    Normal_sum += Temp_Sum - value
                for k, value in Length_Path[headnode, tailnode].items():
                    Normal_Path_Length[headnode, tailnode][k] = (
                        (Temp_Sum - value) / Normal_sum) * len(
                            Length_Path[headnode, tailnode].keys())

        #normalize ADTT
        Normal_Path_ADTT = {}
        for headnode, tailnode in Path_ADTT.keys():
            Normal_Path_ADTT[headnode, tailnode] = {}
            if len(Path_ADTT[headnode, tailnode].keys()) == 1:
                Normal_Path_ADTT[headnode, tailnode][1] = 1
            elif len(Path_ADTT[headnode, tailnode].keys()) > 1:
                Temp_Sum = 0
                for k, value in Path_ADTT[headnode, tailnode].items():
                    Temp_Sum += value
                for k, value in Path_ADTT[headnode, tailnode].items():
                    Normal_Path_ADTT[headnode,
                                     tailnode][k] = (value / Temp_Sum) * len(
                                         Path_ADTT[headnode, tailnode].keys())

        #shortest distance of node i with all emergency nodes
        omega = {}
        for node in G.nodes:
            if node in G.emergnode:
                omega[node] = 1
            else:
                omega[node] = 0

        for head, tail in Length_Path.keys():
            if head in G.emergnode or tail in G.emergnode:
                omega[head] = max(omega[head], 1 / Length_Path[head, tail][1])
                omega[tail] = max(omega[tail], 1 / Length_Path[head, tail][1])

        #compute the weight of each node
        NodeWeight = {}
        sumomega = sum(omega.values())
        for node in G.nodes:
            NodeWeight[node] = omega[node] / sumomega

        G_Resilience = resilience_evaluation(G.nodes, L, Normal_Path_Length,
                                             Fresilience_Path, NodeWeight,
                                             Normal_Path_ADTT)

        total_cost = sum(G.cost.values()) / 2.0

        #result = FE.friability_evaluation(V,E,u,q,R_G)

        #F_G = result[0]     #friability of the whole network
        #F_max = result[1]   #maximum friability of nodes

        print "The resilience of network G is: ", G_Resilience
        #print "The friability of network G is: ", F_G
        #print "The maximum friability of network G is: ", F_max

        f1 = open('network original resilience.txt', 'a')
        f1.write('{}\n'.format(G_Resilience))
        f1.close()

        if GA_Reinfoce_open == 1:  #case 1 reinforcement
            #next use GA to solve the optimization problem
            BinVar = []
            #for i in V:    #these are loop to find out all the complementary edges
            #for j in V:
            #if j != i:
            #if (i,j) not in E:
            #BinVar.append((i,j))
            #BinVar.append((j,i))

            #BinVar = [(1,5),(1,3),(1,8),(1,10), (2,10),(3,10),(3,7),(6,8),(7,10)]

            for headnode, tailnode in G.arcs:
                if headnode < tailnode:
                    BinVar.append((headnode, tailnode))

            BinVar_swap = swap(BinVar)
            BinVar = combine(BinVar, BinVar_swap)

            #for (i,j) in BinVar:
            #q[i,j] = 0.99

            if pareto == 0:
                GA_iteration, GA_run_time, GA_best_fitness, GA_best_solution = GA.main(
                    nodelist, edgelist, BinVar, num_population, max_iteration,
                    max_time, crossover_rate, mutation_rate, top, seed,
                    investment, GA_Reinfoce_open, GA_Construct_open, G,
                    sample_ID)

                GA_best_solution2 = {}
                for headnode, tailnode in GA_best_solution.keys():
                    if headnode < tailnode:
                        if GA_best_solution[headnode, tailnode] == 1:
                            GA_best_solution2[headnode, tailnode] = 1

                Total_cost = 0
                for headnode, tailnode in GA_best_solution2.keys():
                    if headnode < tailnode:
                        Total_cost += GA_best_solution[
                            headnode, tailnode] * G.cost[headnode, tailnode]

                print 'GA_iteration', GA_iteration, 'GA_run_time', GA_run_time, 'GA_best_fitness', GA_best_fitness, 'Total number of bridges', sum(
                    GA_best_solution2.values()
                ), 'Total cost', Total_cost, 'GA_best_solution', GA_best_solution2

                f2 = open('network GA Repair resilience.txt', 'a')
                f2.write('{} \t {} \t {} \t {}\n'.format(
                    GA_best_fitness, sum(GA_best_solution2.values()),
                    Total_cost, GA_best_solution2))
                f2.close()

            if pareto == 1:
                for investment in range(0, 190, 3):
                    print investment

                    GA_iteration, GA_run_time, GA_best_fitness, GA_best_solution = GA.main(
                        nodelist, edgelist, BinVar, num_population,
                        max_iteration, max_time, crossover_rate, mutation_rate,
                        top, seed, investment, GA_Reinfoce_open,
                        GA_Construct_open, G, sample_ID)

                    GA_best_solution2 = {}
                    for headnode, tailnode in GA_best_solution.keys():
                        if headnode < tailnode:
                            if GA_best_solution[headnode, tailnode] == 1:
                                GA_best_solution2[headnode, tailnode] = 1

                    Total_cost = 0
                    for headnode, tailnode in GA_best_solution2.keys():
                        if headnode < tailnode:
                            Total_cost += GA_best_solution[
                                headnode, tailnode] * G.cost[headnode,
                                                             tailnode]

                    print 'budget', investment, 'GA_iteration', GA_iteration, 'GA_run_time', GA_run_time, 'GA_best_fitness', GA_best_fitness, 'Total number of bridges', sum(
                        GA_best_solution2.values()
                    ), 'Total cost', Total_cost, 'GA_best_solution', GA_best_solution2

                    f2 = open('network GA Repair resilience.txt', 'a')
                    f2.write('{} \t {} \t {} \t {} \t {}\n'.format(
                        investment, GA_best_fitness,
                        sum(GA_best_solution2.values()), Total_cost,
                        GA_best_solution2))
                    f2.close()
from GeneticAlgorithm import *


def function1(value):
    return value * math.sin(10 * math.pi * value) + 1


def function2(value):
    return (math.exp(value) * math.sin(10 * math.pi * value) + 1) / value


if __name__ == '__main__':
    print("GeneticAlgorithm:")

    a = 0.5
    b = 2.5

    pop_size = 5
    precision = 3

    pc = 0.25
    pm = 0.01
    epochs = 10

    genetic = GeneticAlgorithm(function2, a, b, precision)
    #genetic.draw_basic_function()
    genetic.perform(pop_size, pc, pm, epochs)
#
#     plt.xlabel('Generation')
#     plt.xscale('log')
#
#     plt.ylabel("Fitness per generation")
#     plt.title("200 Individuals and "+str(algorithm.mutationProbability)+" mutation rate")
#     plt.savefig("mutation_rate" + str(algorithm.mutationProbability) + ".png")
#     plt.show()
#
#
#
# print(execution_times)

#Uncomment here and comment above if you want a single algorithm pass
hamiltonian_genetic_algorithm = GeneticAlgorithm.GeneticAlgorithm(100, 0.06, number_of_genes, fitness_function,
                                                                  generator_function, alphabet,
                                                                  maxNumberOfIterations=1000)

#Plotting
start = time.time()

hamiltonian_genetic_algorithm.runWithAccFitness()
end = time.time()

generations = [i for i in range(hamiltonian_genetic_algorithm.maximumIterationReached)]
fitness = [fitness for fitness in hamiltonian_genetic_algorithm.fitnessPerGeneration]
plt.plot(generations, fitness, '-', label='Fitness')

plt.legend()

plt.xlabel('Generation')
Esempio n. 11
0
    dirname = './logs/'
    makedir(dirname)

    for no_of_items in [100, 250, 500]:
        for capacity_type in ['restrictive', 'average']:
            for correlation in ['none', 'weak', 'strong']:
                data = Generator.gen_data(n=no_of_items,
                                          capacity_type=capacity_type,
                                          correlation=correlation)

                optimal_solution = None
                if capacity_type != 'average':
                    optimal_solution = BNBAlgorithm.knapsack(data)

                for method in ['vanilla', 'repair', 'penalty']:
                    algorithm = GeneticAlgorithm.genetic_algorithm(
                        data, method=method)

                    results = {
                        'vars': [
                            no_of_items, capacity_type, correlation, method,
                            data['seed']
                        ],
                        'optimal':
                        optimal_solution,
                        'fitness': [],
                        'fitness_avg': [],
                        'best_fitness':
                        0,
                        'best_gene':
                        None
                    }
    plt.plot(a,'r-',label='Best Fitness',linewidth=2.0)
    plt.plot(b,'b-',label='Fitness Average',linewidth=2.0)
    plt.legend(loc="upper left")
    plt.axis([0,e,0,1])
    plt.show()

mutationPercentage = 15
populationSize = 200
numberOfSelectedIndividuals = 125
generations=100
pltBestFitness = []
pltFitnessAverage = []

I.transformSquareImage('1.png')
m = I.image2Matrix('sample.png')
population = GA.initialize_population(populationSize)
for i in range(generations):
    print "Generation: "+ str(i)
    fitnessvalues = GA.fitness(population,m)
    fitnessvalues,population = Ordenation.selectionsort(fitnessvalues,population)
    print "     Best fitness: "+str(fitnessvalues[0])
    print "     Fitness average: "+str(sum(fitnessvalues)/len(fitnessvalues))
    pltBestFitness.append(fitnessvalues[0])
    pltFitnessAverage.append(sum(fitnessvalues)/len(fitnessvalues))
    population = GA.selection(population,numberOfSelectedIndividuals)
    population = GA.crossover(population,populationSize)
    population = GA.mutation(population,mutationPercentage)

printBestFitness(population[0])
printGraphic(pltBestFitness,pltFitnessAverage,generations)
Esempio n. 13
0
def create_genom(length):
    """
    引数で指定された桁のランダムな遺伝子情報を生成、格納したgenomClassで返します。
    遺伝子は5つで1ペア

    genom[n + 0] = 移動したx座標(0 to 1)
    genom[n + 1] = 移動したy座標 (-3 to 3(絶対y座標位置))
    genom[n + 2] = x絶対座標
    genom[n + 3] = y絶対座標
    genom[n + 4] = 精製する形の種類の識別番号 
         nペア(GENOM_LENGTH / 5)

    :param length: 遺伝子情報の長さ
    :return: 生成した個体集団genomClass
    """
    abs_X = 0
    abs_Y = 0
    genome_list = []

    for i in range(int(float(length) / 5)):

        temp = [
            random.randint(0, 1),
            random.randint(-1, 1),
            random.randint(1, 6)
        ]

        if (i > 0):
            ly = genome_list[len(genome_list) - 2]
            ls = genome_list[len(genome_list) - 1]

            temp[1] = random.randint((0 - ly), (HIGHT - 1 - ly))

            if (ls == 2):
                if (temp[0] == 0):
                    temp[1] += 3
            if (ls == 3):
                if (temp[0] == 1):
                    temp[0] += 2

            if (ls == 4):
                temp[1] += 1
                temp[0] += 2

            if (ls == 5):
                if (temp[0] == 0):
                    temp[1] += 3
                else:
                    temp[0] += 1

            if (ls == 6):
                if (temp[0] == 1):
                    temp[0] += 3
                else:
                    temp[0] += 1

        endflag = False
        count = 0
        while (not endflag):
            endflag = True

        abs_X += temp[0]
        abs_Y += temp[1]

        genome_list.append(temp[0])
        genome_list.append(temp[1])
        genome_list.append(abs_X)
        genome_list.append(abs_Y)
        genome_list.append(temp[2])

        #?R?[?X?A?E?g????
        if (genome_list[len(genome_list) - 2] >= HIGHT):  #yが上に外れているとき
            genome_list[len(genome_list) - 2] = HIGHT - 1
            genome_list[len(genome_list) - 3] += 1
            genome_list[len(genome_list) - 1] = 1
        elif (genome_list[len(genome_list) - 2] > 0):  #yが下に外れているとき:
            genome_list[len(genome_list) - 2] = 0
            genome_list[len(genome_list) - 3] += 1
        if (genome_list[len(genome_list) - 2] >= HIGHT - 2
                and genome_list[len(genome_list) - 1] >= 2):  #yが上に外れているとき
            genome_list[len(genome_list) - 1] = 1

    return ga.genom(genome_list, 0)
Esempio n. 14
0
File: BMO.py Progetto: framg/BMO
                #stdDistance = velocityModule.getDistanceStd()
                #print ("Real Velocity:", velocity)
                if velocity != None and velocity < 0.1:
                    crashed = True
            if crashed == True:
                crashed = False
                motorController.back()
                time.sleep(getBackTime())
                turnRandDirectionRandAngle()
                num_crashes += 1
                num_rotations += 1
            elif distance > 0 and distance < getDistanceToCrash():
                crashed = True
            elif distance > getDistanceToCrash() and distance < getDistanceToRotate():
                turnRandDirectionRandAngle()
                num_rotations += 1
            else:
                motorController.forward()

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)


old_settings = termios.tcgetattr(sys.stdin)
motorController = MotorController(Motor1A, Motor1B, Motor1E, Motor2A, Motor2B, Motor2E, GPIO.BOARD)
ultrasonicController = UltrasonicController(TRIG, ECHO, GPIO.BOARD)
velocityModule = Velocity()
GA = GeneticAlgorithm(10)
GA.start()
AI()
def optimal(hand, dealer):
    optimalGA = GeneticAlgorithm.Individual(GeneticAlgorithm.Chromosome())
    optimalGA.chromosome.hard_hands = {
        5: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        6: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        7: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        8: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        9: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        10: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        11: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        12: {
            2: 'h',
            3: 'h',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        13: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        14: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        15: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        16: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        17: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        },
        18: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        },
        19: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        },
        20: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        }
    }
    optimalGA.chromosome.soft_hands = {
        2: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        3: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        4: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        5: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        6: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        7: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 's',
            8: 's',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        8: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        },
        9: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        }
    }
    optimalGA.chromosome.pairs = {
        2: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        3: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        4: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        5: {
            2: 'h',
            3: 'h',
            4: 'h',
            5: 'h',
            6: 'h',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        6: {
            2: 'h',
            3: 'h',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        7: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        8: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 'h',
            8: 'h',
            9: 'h',
            10: 'h',
            1: 'h'
        },
        9: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        },
        10: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        },
        1: {
            2: 's',
            3: 's',
            4: 's',
            5: 's',
            6: 's',
            7: 's',
            8: 's',
            9: 's',
            10: 's',
            1: 's'
        }
    }
    return genetic_algorithm(hand, dealer, optimalGA)
Esempio n. 16
0
import GeneticAlgorithm as GA

whereTheHospitalLol = GA.GeneticAlgorithm()
whereTheHospitalLol.plotCostFunction()

whereTheHospitalLol.geneticAlgorithm()
Esempio n. 17
0
        exit(1)
    if not os.path.isdir(level_path):
        os.makedirs(level_path)

    # Generate the seed
    if random_seed:
        seed = random.randrange(100000000)
    print("Seed:", seed)
    rng = random.Random(seed)

    # Run the GA to generate rooms
    room_ga = GeneticAlgorithm(breeder=GeneticAlgorithm.uniform_crossover,
                               mutator=RoomChromosome.mutate,
                               initial=[
                                   RoomChromosome.generate_gene(
                                       rng, gene_length)
                                   for _ in range(population_size)
                               ],
                               fitness=Fitness.mixed_room_fitness,
                               _rng=rng)
    rooms_dominant = room_ga.compute(iterations)

    # Run the GA to generate room types
    room_type_ga = GeneticAlgorithm(breeder=GeneticAlgorithm.uniform_crossover,
                                    mutator=RoomTypeChromosome.mutate,
                                    initial=[
                                        RoomTypeChromosome.generate_gene(
                                            rng, rooms_dominant)
                                        for _ in range(population_size)
                                    ],
                                    fitness=Fitness.room_type_fitness,
#Creating the initial population.
initialPopulationWithWeightsInMatrixForm = []    
for network in numpy.arange(0, networksPerPopulation):
    currentNetworkWeights = []
    for layer in numpy.arange(0, len(neuronsPerLayer)):
        if (layer == 0):
            currentNetworkWeights.append(numpy.random.uniform(low=-0.1, high=0.1,
                                                              size=(data_inputs.shape[1],neuronsPerLayer[0])))
        else:
            currentNetworkWeights.append(numpy.random.uniform(low=-0.1, high=0.1,
                                                              size=(neuronsPerLayer[layer-1],neuronsPerLayer[layer])))
    initialPopulationWithWeightsInMatrixForm.append(numpy.array(currentNetworkWeights))

# Just converts to numpy array
populationWithWeightsInMatrixForm = numpy.array(initialPopulationWithWeightsInMatrixForm)
populationWithWeightsInVectorForm = ga.mat_to_vector(populationWithWeightsInMatrixForm)

best_outputs = []
accuracies = numpy.empty(shape=(maxGenerations))

print("Training NN with genetic algorithm:")
pbar = tqdm(total=maxGenerations)
nnPreLearningTime = time.time()

for generation in range(maxGenerations):
    # converting the solutions from being vectors to matrices.
    populationWithWeightsInMatrixForm = ga.vector_to_mat(populationWithWeightsInVectorForm, 
                                       populationWithWeightsInMatrixForm)

    # Measuring the fitness of each chromosome in the population.
    fitness = ANN.fitness(populationWithWeightsInMatrixForm, 
Esempio n. 19
0
        #val_y.append(val[1])
        val_x.append(p.genes[0])
        val_y.append(p.genes[1])

    pf1 = np.arange(0.0, 1.0, 0.01)
    pf2 = 1.0 - np.sqrt(pf1)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(pf1, pf2, 'r')
    ax.scatter(val_x, val_y)
    ax.plot(val_x[0], val_y[0], 'rs')
    plt.show()


if __name__ == '__main__':

    initRange = [0.0, 1.0]
    weight = [0.5, 0.5]

    ga = GeneticAlgorithm(500, initRange, 30, calcFitness, weight, 0.05, 0.05)

    showFit(ga)

    for i in range(1000):
        ga.next()
        print ga.population[0].fitness

    print zdt1(ga.population[0].genes)

    showFit(ga)
Esempio n. 20
0
    def initGeneticAlgorithm(self):
        # train and tune weights
        if Config.ga_mode == 0 or Config.ga_mode == 1:
            if Config.ga_mode == 0:
                # randomly initialize first populations/chromosomes
                prey_new_population = np.random.choice(
                    np.arange(-1, 1, step=0.01),
                    size=Config.population_matrix_size,
                    replace=True)
                hunter_new_population = np.random.choice(
                    np.arange(-1, 1, step=0.01),
                    size=Config.population_matrix_size,
                    replace=True)

            else:
                # load weights from input files
                prey_new_population = pd.read_csv(Config.input_file_prey,
                                                  header=None,
                                                  index_col=None).to_numpy()
                hunter_new_population = pd.read_csv(Config.input_file_hunter,
                                                    header=None,
                                                    index_col=None).to_numpy()

            #matrices and values to store fittest prey & hunter information
            fittest_prey_weights = []
            fittest_hunter_weights = []
            fittest_prey_score = 0
            fittest_hunter_score = 0
            max_prey_fitness = 0
            max_hunter_fitness = 0

            # iterate over each generation
            for generation in range(Config.num_of_generations):
                prey_fitness = []
                hunter_fitness = []

                # for each chromosome, run game and determine prey & hunter fitness values
                for chromosome in range(Config.chromosomes):
                    run_info = self.run(prey_new_population[chromosome],
                                        hunter_new_population[chromosome])
                    score = run_info[0]
                    hunter_near_fruit = run_info[1]
                    final_state_flag = run_info[2]
                    prey_score = ga.prey_score(score, final_state_flag)
                    hunter_score = ga.hunter_score(score, hunter_near_fruit,
                                                   final_state_flag)

                    # update fittest prey & hunter scores if prey & hunter surpass previous fittest
                    if prey_score > fittest_prey_score:
                        fittest_prey_weights = prey_new_population[chromosome]
                        fittest_prey_score = prey_score
                    if hunter_score > fittest_hunter_score:
                        fittest_hunter_weights = hunter_new_population[
                            chromosome]
                        fittest_hunter_score = hunter_score

                    # append scores to list
                    prey_fitness.append(prey_score)
                    hunter_fitness.append(hunter_score)

                #Create next generation of prey
                if Config.ga_training_mode == 0 or Config.ga_training_mode == 1:
                    # convert to array and determine max prey fitnesses
                    prey_fitness = np.array(prey_fitness)
                    max_prey_fitness = np.amax(prey_fitness)

                    # determine prey parents based on highest fitness values
                    prey_parents = ga.select_parents(prey_new_population,
                                                     prey_fitness,
                                                     Config.num_of_parents)

                    # determine prey offsprings using crossover method on selected parents
                    prey_offspring_crossover = ga.breed(
                        prey_parents,
                        offspring_size=(Config.population_matrix_size[0] -
                                        prey_parents.shape[0],
                                        Config.num_w_all))

                    # randomly mutate offspring chromosomes to build in gene diversity
                    prey_offspring_mutation = ga.mutate(
                        prey_offspring_crossover)

                    # create new prey populations based on selected parents and offspirngs
                    prey_new_population[
                        0:prey_parents.shape[0], :] = prey_parents
                    prey_new_population[
                        prey_parents.shape[0]:, :] = prey_offspring_mutation

                #Create next generation of hunters
                if Config.ga_training_mode == 0 or Config.ga_training_mode == 2:
                    # convert to array and determine max hunter fitnesses
                    hunter_fitness = np.array(hunter_fitness)
                    max_hunter_fitness = np.amax(hunter_fitness)

                    # determine hunter parents based on highest fitness values
                    hunter_parents = ga.select_parents(hunter_new_population,
                                                       hunter_fitness,
                                                       Config.num_of_parents)

                    # determine hunter offsprings using crossover method on selected parents
                    hunter_offspring_crossover = ga.breed(
                        hunter_parents,
                        offspring_size=(Config.population_matrix_size[0] -
                                        hunter_parents.shape[0],
                                        Config.num_w_all))

                    # randomly mutate offspring chromosomes to build in gene diversity
                    hunter_offspring_mutation = ga.mutate(
                        hunter_offspring_crossover)

                    # create new hunter populations based on selected parents and offspirngs
                    hunter_new_population[
                        0:hunter_parents.shape[0], :] = hunter_parents
                    hunter_new_population[
                        hunter_parents.
                        shape[0]:, :] = hunter_offspring_mutation

                # save prey & hunter populations for future use if at save interval
                if generation % Config.generation_save_interval == 0:
                    prey_output_file = 'prey_output_gen' + str(
                        generation) + '.csv'
                    hunter_output_file = 'hunter_output_gen' + str(
                        generation) + '.csv'
                    pd.DataFrame(prey_new_population, index=None,
                                 columns=None).to_csv(prey_output_file,
                                                      index=False,
                                                      header=False)
                    pd.DataFrame(hunter_new_population,
                                 index=None,
                                 columns=None).to_csv(hunter_output_file,
                                                      index=False,
                                                      header=False)

                # print results from generation
                print('for generation: ' + str(generation) +
                      ', max prey fitness = ' + str(max_prey_fitness) +
                      ', max hunter fitness = ' + str(max_hunter_fitness))

            pd.DataFrame(np.array(fittest_prey_weights),
                         index=None,
                         columns=None).to_csv('fittest_prey.csv',
                                              index=False,
                                              header=False)
            pd.DataFrame(np.array(fittest_hunter_weights),
                         index=None,
                         columns=None).to_csv('fittest_hunter.csv',
                                              index=False,
                                              header=False)

        # load weights and run game
        else:
            prey_weights = pd.read_csv(Config.input_file_prey,
                                       header=None,
                                       index_col=None).to_numpy()
            hunter_weights = pd.read_csv(Config.input_file_hunter,
                                         header=None,
                                         index_col=None).to_numpy()
            for i in range(15):
                self.run(prey_weights, hunter_weights)
Esempio n. 21
0
import GeneticAlgorithm
import PMSPMain as main
from PMSPRestrictions import PMSPRestrictions


if __name__ == '__main__':
    G = main.ler_instancia("20on4Rp50Rs50_1original.dat")
    restrictions = PMSPRestrictions(len(G[0][0]),len(G[0]), G)
    ga = GeneticAlgorithm.GeneticAlgorithm(restrictions,1000)
    
    pop = ga.run(1000)

Esempio n. 22
0
### Set Neural Evolution parameters
num_population = 100
mutation_factor = 0.5
crossover_rate = 0.8
input_number = 4  # distancia, altura, velocidade, bias
hidden_number = 6
output_number = 3  # pular, agachar, nada
max_weight_value = 100
min_weight_value = -100
weights_number = (input_number * hidden_number) + (hidden_number *
                                                   output_number)

### Initialize Neural Evolution
dino_evolution = GeneticAlgorithm.GeneticAlgorithm(
    num_population, mutation_factor, crossover_rate, max_weight_value,
    min_weight_value, weights_number)
dino_evolution.createPopulation()
generation = 1
best_fitness = 0
while generation <= 50:
    dinosaur_players = []
    population_over = [False] * num_population
    for x in range(num_population):
        dinosaur_players.append(Player.Player(createDino(), x, time.time()))
        dinosaur_players[x].createNeuralNetwork(input_number, hidden_number,
                                                output_number)
        dinosaur_players[x].setNeuralNetworkWeights(
            dino_evolution.getPopulation()[x][:-1])
        dinosaur_players[x].setBias(dino_evolution.getPopulation()[x][-1])
        dinosaur_players[x].setPlayerFitness(0)
Esempio n. 23
0
while run:
    #pygame.time.delay(100)
    
    clock.tick()
    fps = clock.get_fps()
    if(fps != 0):
        print("Frametime: " + str((1000/fps)))
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    
    win.fill((0, 0, 0))
    
    ga.calculateFitness()
    ga.normalizeFitness()    
    ga.nextGeneration()
    
    print("Beste Distanz: " + str(ga.distRecord))
    progress.append(ga.distRecord)

    #if ga.distRecord <= 7450 and not reached:
    #    print("NN Record Eingeholt! Generation: " + str(len(progress)))
    #   reached = True
        
    #if len(progress) >= 1000:
    #    pygame.time.delay(100000)

    plt.plot(progress)
    plt.pause(0.05)
Esempio n. 24
0
def evaluation(ga):


    #上部:評価関数の内部関数
    # getTime() : その遺伝子ごとの最終的な経過時間を計算して、返す。
    def getTime(stockShape):
        time = 0
        for x in stockShape:
            if(x==1):
                time += 1000
            elif(x==2):
                time += 2500
            elif(x==3):
                time += 3000
            elif(x==4):
                time += 6000
        return time

    # getDiversity() : 金型の種類が偏りを判定し、評価値を返す。
    def getDiversity(stockShape):
        MaxP = GENOM_LENGTH / Decimal(5) 
        evaluation = 0
        ShapeList = [0,0,0,0] #array6

        for x in stockShape:
            if(x==1):
                ShapeList[0] += 1
                evaluation += 100
            elif(x==2):
                ShapeList[1] += 1
                evaluation += 200
            elif(x==3):
                ShapeList[2] += 1
                evaluation += 600
            elif(x==4):
                ShapeList[3] += 1
                evaluation += 500
            
        if(ShapeList[0] > MaxP/Decimal(len(ShapeList))):
            evaluation -= 100*(ShapeList[0]-MaxP/Decimal(len(ShapeList)))
        if(ShapeList[1] > MaxP/Decimal(len(ShapeList))):
            evaluation -= 200*(ShapeList[1]-MaxP/Decimal(len(ShapeList)))
        if(ShapeList[2] > MaxP/Decimal(len(ShapeList))):
            evaluation -= 300*(ShapeList[2]-MaxP/Decimal(len(ShapeList)))
        if(ShapeList[3] > MaxP/Decimal(len(ShapeList))):
            evaluation -= 1200*(ShapeList[2]-MaxP/Decimal(len(ShapeList)))

        return evaluation

                

    """評価関数
    マーカーとマーカーの座標の差が少ないほどよい
    位置がかぶった場合はマイナス
    鉄板より外れたら大マイナス
    空白が少ない程、評価値が高い。
    経過時間が少ないほど評価値が高い(金型の種類の差より、移動にかかる時間の方が比重が大きい)
    金型の種類が偏っていいない程評価値が高い(一定割合を超えるとマイナス)  
    evalist: マーカーを置いたことのある座標を記録する
    :param ga: 評価を行うgenomClass
    :return: 評価処理をしたgenomClassを返す
    """

    eval = 0
    SumMoveTime = 0
    evalist = []
    count = 0
    checkX = 0
    checkY = 0
    checkRota = 0
    endX = 0
    checkShape = 0
    StockShape = []
    before = (0,0)

    add = True

    
    for x in ga.getGenom():

        if(count % 5 == 4):
            checkShape = x

            if(checkY < HIGHT and checkX < WIDTH and checkY >= 0):
                if(ga.getReservation(checkY,checkX)==1):
                    now = (checkX,checkY)
                    for x in range(len(evalist)):
                        if(evalist[x]==now):
                            add = False
                            break
                        
                    if(add):
                        Mult = 1
                        AddMoveTime = 0
                        evalist.append(now)
                        if(checkShape==2):
                            if(checkRota == 0 or checkRota == 2):
                                evalist.append((now[0]+1,now[1]))
                                evalist.append((now[0]+2,now[1]))
                            elif(checkRota == 1 or checkRota == 3):
                                evalist.append((now[0],now[1]+1))
                                evalist.append((now[0],now[1]+2))
                            Mult = 3
                        if(checkShape==3):
                            evalist.append((now[0]+1,now[1]))
                            evalist.append((now[0],now[1]+1))
                            evalist.append((now[0]+1,now[1]+1))
                            Mult = 4
                        if(checkShape==4):
                            if(checkRota == 0 or checkRota == 2):
                                evalist.append((now[0]+1,now[1]))
                                evalist.append((now[0]+2,now[1]))
                                evalist.append((now[0],now[1]+1))
                                evalist.append((now[0]+1,now[1]+1))
                                evalist.append((now[0]+2,now[1]+1))
                            if(checkRota == 1 or checkRota == 3):
                                evalist.append((now[0],now[1]+1))
                                evalist.append((now[0],now[1]+2))
                                evalist.append((now[0]+1,now[1]))
                                evalist.append((now[0]+1,now[1]+1))
                                evalist.append((now[0]+1,now[1]+2))
                            Mult = 6

                        eval += (5 *Mult)
                        SumMoveTime += AddMoveTime
                        now = before
                    else:
                        eval -= 200

            else:
                eval -= 300
            StockShape.append(checkShape)

        if(count % 5 == 3):
            
            checkY = x
            
        elif(count % 5 == 2):
            checkX = x
            if(x>endX):
                endX = x
        elif(count % 5 == 0):
            checkRota = x
        
        count += 1

    for y in range(HIGHT):
        for x in range(endX+1):
            if(ga.getReservation(y,x)==0):
                eval -= 7

    if(eval <= 0):
        eval = 0

    return eval
Esempio n. 25
0
import GeneticAlgorithm

####################################################################################
bounds = [[0, 67], [0, 3]]  #[[speed range], [actions]]
mutationProb = 0.4  # mutation rate
crossoverProb = 0.4  # crossover rate
popSize = 4
numOfNpc = 2
numOfTimeSlice = 5
maxGen = 100
####################################################################################

ge = GeneticAlgorithm.GeneticAlgorithm(bounds, mutationProb, crossoverProb,
                                       popSize, numOfNpc, numOfTimeSlice,
                                       maxGen)
#ge.set_checkpoint('GaCheckpoints/last_gen.obj')
ge.ga()
Esempio n. 26
0
import GeneticAlgorithm as GA
import Fitness
import Ordenation
import Graphic

time = 720
chromosomeSize = time/10
generations = 50
mutationPercentage = 40
populationSize = 20
numberOfSelectedIndividuals = 12
pltBestFitness = []
pltFitnessAverage = []

# Main
population = GA.initialize_population(populationSize,chromosomeSize)
for i in range(generations):
    print "Generation: "+ str(i)
    fitnessvalues = Fitness.fitness(population,time)
    fitnessvalues,population = Ordenation.selectionsort(fitnessvalues,population)
    print "     Best fitness: "+str(fitnessvalues[0])
    print "     Fitness average: "+str(sum(fitnessvalues)/len(fitnessvalues))
    pltBestFitness.append(fitnessvalues[0])
    pltFitnessAverage.append(sum(fitnessvalues)/len(fitnessvalues))
    population = GA.selection(population, numberOfSelectedIndividuals)
    population = GA.uniformCrossover(population, populationSize, chromosomeSize)
    population = GA.mutation(population, mutationPercentage)

Graphic.printGraphic(pltBestFitness,pltFitnessAverage,generations)
Esempio n. 27
0
    testing_pctg = 0.5

    #In-sample period
    dates = [dt.datetime(2017, 1, 1), dt.datetime(2018, 4, 4)]
    strategy = manstratt.ManualStrategyTicktoTick()

    # Get data
    df = util.get_all_data(symbol, dates)

    pos = int(len(df.index) * testing_pctg)
    split_date = df.index[pos]

    # Use GeneticAlgorithm to optimize signal weights
    params = False
    gen_alg = ga.GeneticAlgorithm(symbol=symbol,
                                  dates=[dates[0], split_date],
                                  start_val=start_val,
                                  verbose=True)
    params, sharpe_ratio = gen_alg.start_ga()

    #pdb.set_trace()

    ft = FakeTicker(symbol, df, testing_pctg)
    #print (ft.get_training_data().shape)
    prices_df = ft.get_training_data()['Adj Close']
    ohlc = ind.get_ohlc(ft.get_training_data())

    trades = []
    ctr = 0
    while not ft.is_end_ticker():
        start = time.time()
        # Get tick data
Esempio n. 28
0
# 5. Delete the previous set of cars and drive the new generation


def reset_schedule():
    for car in GA.pop:
        pyglet.clock.unschedule(car.update)
        pyglet.clock.schedule_interval(car.update, 1 / 60.0)


if __name__ == '__main__':
    width, height = 1000, 700
    game_window = pyglet.window.Window(width, height)
    walls, checkpoints = create_track(width, height)

    neuron_shape = (5, 3, 3, 1)
    GA = GA.GeneticAlgorithm(5, 0.03)
    GA.create_population(neuron_shape)

    @game_window.event
    def on_draw():
        game_window.clear()
        stopped_cars = 0
        for car in GA.pop:
            if car:
                car.draw()
                for wall in walls:
                    wall.show()
                    pt = car.check_collision(wall)
                    if pt: car.alive = False
                car.look(walls)
                for gate in checkpoints:
Esempio n. 29
0
#Calculating Fading (TBD)

#Minimum Output Power (ETSI TS 136 101 V14.3.0 (2017-04))
p_min = -40 #dBm

allocatingPilotSequence(K, 10)


# ------GA------
# setupGA = SetupGA(10,10,5, 60.02)
generationNumber = 30
rateMutation = 0.07

individual = Individual()

ga = GeneticAlgorithm()
ga.runGA(phi, generationNumber, rateMutation, beta, N0*Bmax)
# ga.inicializePopulation(phi)
# for i in range(len(ga.population)):
#     for j in range(len(ga.population[i])):
#         ga.population[i][j].fnFitness()

# ga.printPopulation()
# print("TSTES %s" % ga.population[0][1].chromosome)

finihed = time.time()
print("------------------------------")
print("Tempo de execucao: ", finihed-start)
print("------------------------------")
plt.show()
Esempio n. 30
0
from Algorithms import Searcher
from Utility import *
from GeneticAlgorithm import *

graph = generateGraph("Test_Problems/prob15.map")

searcher = Searcher(graph)
res = []
res.append(searcher.AStarSearch())

res.append(searcher.BreadthFirstSearch())

res.append(searcher.DepthFirstSearch())

res.append(searcher.UniformCostSearch())

ProbScore = ProblemScore(res)
ProbScore.printScores()
scores = ProbScore.GetScores()
resDict = ProbScore.GetResultDict()

GA = GeneticAlgorithm(50, scores, resDict)

gaRes = GA.PerformAlgorithm()

gaRes.printResult()
    variance = sum((counts[i] - freq[i]*len(ciphertext)) ** 2 for i in alphabet) / 2 / len(ciphertext) ** 2
    return 1-variance # since we want to minimize variance, but have to feed a maximizing problem into the genetic algorithm

def crossover(gene1, gene2, mutation_chance):
    new_gene = ""
    for i in range(len(gene1)):
        r = random.random()
        if r < 0.5 - mutation_chance / 2:
            new_gene += gene1[i]
        elif r < 1 - mutation_chance:
            new_gene += gene2[i]
        else: # mutate
            new_gene += alphabet[random.randrange(26)]
    return new_gene

def generate():
    return ''.join([chr(random.randint(65, 90)) for i in range(26)])

if __name__ == '__main__':
    ciphertext = "GUR ZBQHYRF QRFPEVORQ VA GUVF PUNCGRE CEBIVQR N JVQR ENATR BS FGEVAT ZNAVCHYNGVBA BCRENGVBAF NAQ BGURE GRKG CEBPRFFVAT FREIVPR"
    evaluate = lambda gene: eval_freq(gene, "GUR ZBQHYRF QRFPEVORQ VA GUVF PUNCGRE CEBIVQR N JVQR ENATR BS FGEVAT ZNAVCHYNGVBA BCRENGVBAF NAQ BGURE GRKG CEBPRFFVAT FREIVPR") # the ciphertext in rot13
    g = GeneticAlgorithm(generate, crossover, evaluate, 100, 1000)
    g.run()

    counts = {i:{chr(j):0 for j in range(65, 91)} for i in range(26)}
    for i in g.gene_pool:
        for index, letter in enumerate(i):
            counts[index][letter] += 1

    
Esempio n. 32
0
def create_genom(length):
    station_genom = []
    for count in range(length):
        station_genom.append([station_list[random.randint(0, 5133)], 0])
    return ga.genom(station_genom, 0)
def geneticAlgorithm(networkParameters, runs):
    accuracies = []
    for run in range(runs):
        maxGenerations = 30
        neuronsPerLayer = [150, 60, noOfClasses]
        initialPopulationWithWeightsInMatrixForm = []
        for network in numpy.arange(0, networkParameters["populationSize"]):
            currentNetworkWeights = []
            for layer in numpy.arange(0, len(neuronsPerLayer)):
                if (layer == 0):
                    currentNetworkWeights.append(
                        numpy.random.uniform(low=-0.1,
                                             high=0.1,
                                             size=(data_inputs.shape[1],
                                                   neuronsPerLayer[0])))
                else:
                    currentNetworkWeights.append(
                        numpy.random.uniform(low=-0.1,
                                             high=0.1,
                                             size=(neuronsPerLayer[layer - 1],
                                                   neuronsPerLayer[layer])))
            initialPopulationWithWeightsInMatrixForm.append(
                numpy.array(currentNetworkWeights))

        # Just converts to numpy array
        populationWithWeightsInMatrixForm = numpy.array(
            initialPopulationWithWeightsInMatrixForm)
        populationWithWeightsInVectorForm = ga.mat_to_vector(
            populationWithWeightsInMatrixForm)

        for generation in range(maxGenerations):
            # converting the solutions from being vectors to matrices.
            populationWithWeightsInMatrixForm = ga.vector_to_mat(
                populationWithWeightsInVectorForm,
                populationWithWeightsInMatrixForm)

            # Measuring the fitness of each chromosome in the population.
            fitness = ANN.fitness(populationWithWeightsInMatrixForm,
                                  data_inputs,
                                  data_outputs,
                                  activation="sigmoid")

            # Selecting the best parents in the population for mating.
            parents = ga.select_mating_pool(
                populationWithWeightsInVectorForm, fitness.copy(),
                int(networkParameters["crossoverRate"] *
                    networkParameters["populationSize"]))

            # Generating next generation using crossover.
            offspring_crossover = ga.crossover(
                parents,
                # offspring(populationSize-numParents,totalConnections)
                offspring_size=(populationWithWeightsInVectorForm.shape[0] -
                                parents.shape[0],
                                populationWithWeightsInVectorForm.shape[1]))

            # Adding some variations to the offsrping using mutation.
            offspring_mutation = ga.mutation(
                offspring_crossover,
                mutation_percent=int(networkParameters["mutationRate"] * 100))

            # Creating the new population based on the parents and offspring.
            populationWithWeightsInVectorForm[0:parents.shape[0], :] = parents
            populationWithWeightsInVectorForm[
                parents.shape[0]:, :] = offspring_mutation

        populationWithWeightsInMatrixForm = ga.vector_to_mat(
            populationWithWeightsInVectorForm,
            populationWithWeightsInMatrixForm)
        best_weights = populationWithWeightsInMatrixForm[0, :]
        acc, predictions = ANN.predict_outputs(best_weights,
                                               data_inputs,
                                               data_outputs,
                                               activation="sigmoid")
        accuracies.append(acc)
    return numpy.median(accuracies)
Esempio n. 34
0
class NeuralNetworkCalculator(object):
    def __init__(self, dimension, hiddenNum):
        self.dim = dimension
        self.dataSize = 0
        self.inputs = []
        for d in range(self.dim):
            self.inputs.append([])
        self.outputs = []

        self.mse = 0.0
        self.fitnessVal = []
        self.runCnt = 2000
        self.nn = NeuralNetwork([self.dim, hiddenNum, 1])

        self.ga = None
        self.pso = None

    def load(self, filename):
        with open(filename, 'rb') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                self.dataSize += 1
                for d in range(self.dim):
                    self.inputs[d].append(float(row[d]))
                self.outputs.append(float(row[self.dim]))

        self.X = np.array(self.inputs).T
        self.Y = np.array(self.outputs)

    def calcFitness(self, weight):

        nY = []
        for i in range(self.dataSize):
            x = self.X[i, :]
            nY.append(self.nn.calcFunc(weight, x)[0])
        delta = self.Y - np.array(nY)
        return np.dot(delta.T, delta) / self.dataSize

    def calcByGA(self, population_num, geneRange):
        chromoLen = self.nn.weight_num + self.nn.bias_num

        self.ga = GeneticAlgorithm(population_num, geneRange, chromoLen,
                                   self.calcFitness)

        self.fitnessVal = []
        for t in range(self.runCnt):
            self.ga.next()
            self.fitnessVal.append(self.ga.population[0].fitness)
            print str(t) + " : " + str(self.ga.population[0].fitness)

        self.betas = np.array(self.ga.population[0].genes)
        nY = []
        for i in range(self.dataSize):
            x = self.X[i, :]
            nY.append(self.nn.calcFunc(self.betas, x)[0])
        delta = self.Y - np.array(nY)
        self.mse = np.dot(delta.T, delta) / self.dataSize

    def calcByPSO(self, population_num, geneRange):

        particleDim = self.nn.weight_num + self.nn.bias_num

        self.pso = Swarm(population_num, particleDim, geneRange,
                         self.calcFitness, 0.4, 1.0, 1.0)

        self.fitnessVal = []
        for t in range(self.runCnt):
            self.pso.next()
            self.fitnessVal.append(self.pso.gbFitness)
            print str(t) + " : " + str(self.pso.gbFitness)

        self.betas = np.array(self.pso.gb)
        nY = []
        for i in range(self.dataSize):
            x = self.X[i, :]
            nY.append(self.nn.calcFunc(self.betas, x)[0])
        delta = self.Y - np.array(nY)
        self.mse = np.dot(delta.T, delta) / self.dataSize

    def log(self, filename):

        id = str(id=str(time.time()))
        with open(filename + "-" + id + ".txt", 'w') as file:
            paramStr = "PARAM: "
            paramStr += "I: " + str(self.nn.input_num) + " "
            paramStr += "H: " + str(self.nn.hidden_num) + " "
            paramStr += "O: " + str(self.nn.output_num) + " "
            paramStr += "\n"
            file.write(paramStr)

            if self.pso != None:
                psoStr = "PSO "
                psoStr += "Num: " + str(self.pso.particle_num) + " "
                psoStr += "Range: " + str(self.pso.posRange) + " "
                psoStr += "Chi: " + str(self.pso.chi) + " "
                psoStr += "Phi_G: " + str(self.pso.phi_g) + " "
                psoStr += "Phi_P: " + str(self.pso.phi_p) + "\n"
                file.write(psoStr)
            elif self.ga != None:
                gaStr = "GA "
                gaStr += "Num: " + str(self.ga.population_num) + " "
                gaStr += "Range: " + str(self.ga.geneRange) + "\n"
                file.write(gaStr)

            for fVal in self.fitnessVal:
                file.write(str(fVal) + "\n")
Esempio n. 35
0
def create_genom(length):
    """ランダムに遺伝子の作成"""
    genom_list = list()
    for i in range(length):
        genom_list.append(random.randint(0, 1))
    return ga.genom(genom_list, 0)
Esempio n. 36
0
def main_ga(df,
            trgt,
            n_boot=100,
            n_pop=50,
            ratio_retain=0.2,
            ratio_mut=0.3,
            min_metric='bic',
            min_gener=8,
            tol_gen=5,
            max_gener=20,
            mult_thrd=True,
            vif_value=5.0):
    '''
    Main function of algorithm
    Input: dataframe holiding all data, string of dependent variable,
    bootstrap iterations, number of individuals,
    retain fraction of rank selection, mutation probability, metric to be 
    used ('bic' or 'aic') in optimisation, minimum number of generations, minimum number of 
    generations with no improvement in best model, maximum number of generations,
    multithread enable boolean, VIF threshold
    Output: best model, final model, variables series  
    '''
    # Import tqdm module to handle progress indication
    import tqdm
    models_lst = []

    # Start algorithm with bootstrap iterations
    for iii in tqdm.tqdm(range(n_boot),
                         desc='Genetic Algorithm Model Selection'):
        # Take bootstrap sample
        file_nm_copy = df.copy()
        file_nm_boot = file_nm_copy.sample(frac=1, replace=True)
        # Reset dataframe index
        file_nm_boot = file_nm_boot.reset_index(drop=True)
        # Drop target (dependent) variable from X dataframe
        X_boot = file_nm_boot.drop([trgt], axis=1)
        # Y datafram holds all variables including the target
        # to be used in the ordinal regression fit in R
        Y = file_nm_boot
        # Remove collinearity
        X, col_lst_col = vif_functions.rmv_multicol(X_boot, vif_value)
        # Calculate number of individials, i.e. number of parameters remainig
        # after collinearity removal
        n_individual = len(X.columns)
        # Create initial population of genetic algorithm
        pop = [
            GeneticAlgorithm.create_individual(n_individual)
            for _ in range(n_pop)
        ]
        # Initial number of generations (n_gen) is zero
        n_gen = 0
        # List to hold best model of each iteration
        hof_lst = []
        # List to hold BIC or AIC values of best individual for each generation
        track_obj_vals = []
        # Start genetic algorithm with condition of exceeding maximum number
        # of generations (max_gener)
        while n_gen < max_gener:
            # The genetic algorithm returns the current population (pop_temp)
            # and the best model (hof)
            pop_temp, hof = start_evolve(ratio_retain, ratio_mut, pop, X, Y,
                                         min_metric, mult_thrd, trgt)
            # Append BIC or AIC value of best individual
            track_obj_vals.append(hof[0])
            # Append best individual
            hof_lst.append(hof)
            # Set next population to the current one returned from the genetic algorithm
            pop = pop_temp[:]
            # Increment the generation index
            n_gen += 1
            # Check if number of minimum generations is reached (n_gen>min_gener)
            # and if we have a minimum number of generations (tol_gen) without
            # a change in the best model
            if len(set(track_obj_vals[-tol_gen:])) == 1 and n_gen > min_gener:
                break
        # Sort best models according to their BIC (or AIC)
        hof_sort = sorted(hof_lst, key=getKey, reverse=False)
        # Select binary vector of model to be used to select the final
        # model parameters
        gen_arr = np.array(hof_sort[0][1])
        # Apply binary vector on the total model parameters in dataframe X
        # to get the final parameters by column name
        vars_lst = list(X.columns)
        gen_ind_0 = np.where(gen_arr == 0)
        gen_ind_0 = gen_ind_0[0]
        vars_lst2 = vars_lst[:]
        for i in sorted(gen_ind_0, reverse=True):
            del vars_lst2[i]
        final_vars_ga = vars_lst2[:]
        # Append parameters in list
        models_lst.append(final_vars_ga)
    # Count unique models
    aa = Counter(map(frozenset, models_lst))
    df = pd.DataFrame.from_dict(aa, orient='index')
    count_series = df.ix[:, 0]
    count_series = count_series.copy()
    count_series.sort_values(inplace=True, ascending=False)
    # Select best model of all the models
    best_model = list(list(count_series.index)[0])
    # Get the final model and variables by selection frequency as
    # Pandas series objects
    series_models, series_vars = func_output(count_series, n_boot)
    # Return best model, final models and variables series
    return best_model, series_models, series_vars
Esempio n. 37
0
def evaluation(ga):
    """評価"""
    genom_total = sum(ga.getGenom())
    return Decimal(genom_total) / Decimal(GENOM_LENGTH)
Esempio n. 38
0
         (25937.5000, 51313.3333), (25944.7222, 51456.3889),
         (25950.0000, 51066.6667), (25951.6667, 51349.7222),
         (25957.7778, 51075.2778), (25958.3333, 51099.4444),
         (25966.6667, 51283.3333), (25983.3333, 51400.0000),
         (25983.6111, 51328.0556), (26000.2778, 51294.4444),
         (26008.6111, 51083.6111), (26016.6667, 51333.3333),
         (26021.6667, 51366.9444), (26033.3333, 51116.6667),
         (26033.3333, 51166.6667), (26033.6111, 51163.8889),
         (26033.6111, 51200.2778), (26048.8889, 51056.9444),
         (26050.0000, 51250.0000), (26050.2778, 51297.5000),
         (26050.5556, 51135.8333), (26055.0000, 51316.1111),
         (26067.2222, 51258.6111), (26074.7222, 51083.6111),
         (26076.6667, 51166.9444), (26077.2222, 51222.2222),
         (26078.0556, 51361.6667), (26083.6111, 51147.2222),
         (26099.7222, 51161.1111), (26108.0556, 51244.7222),
         (26116.6667, 51216.6667), (26123.6111, 51169.1667),
         (26123.6111, 51222.7778), (26133.3333, 51216.6667),
         (26133.3333, 51300.0000), (26150.2778, 51108.0556)]

for i in range(len(nodes)):
    nodes[i] = nodes[i][1], nodes[i][0]

G = FullyConnectedGraph(nodes)

ga = GeneticAlgorithm(G,
                      num_chromosomes=500,
                      depth=100000,
                      mutation_rate=.3,
                      crossover_rate=.9)
winner = ga.run()
Esempio n. 39
0
from GeneticAlgorithm import *
from SnakeGame import *

size = 20
snake_size = 3

pop_size = 30
num_gen = 500
window_size = 7
hidden_size = 8
max_iter = 100

genetic_algorithm = GeneticAlgorithm(
    size,
    pop_size,
    num_gen,
    window_size,
    hidden_size,
    max_iter=max_iter,
    mutation_chance=0.5,
    mutation_size=0.2,
    display=False,
)

# genetic_algorithm.run(eating=False) # test for a survival SnakeGame

genetic_algorithm.run(eating=True)
Esempio n. 40
0
for line in reader:
    data = dict(zip(header, line))
    data['received_pizza'] = json.loads(data['received_pizza'].lower())
    kaggleRequests.append(data)

fh.close()

fh = open(logfile, 'r')
reader = csv.reader(fh)
header = reader.__next__()
for field in ['ID', 'Gen', 'Score']:
    header.remove(field)

bestScore = 0.0
bestAgent = None
for i, agent in enumerate(reader):
    if i >= numAgents:
        break
    
    agentObj = Agent.deserializeAgent(header, agent)
    score = GeneticAlgorithm.runAgentAgainstTest(agentObj, kaggleRequests, True)
    if score > bestScore:
        bestScore = score
        bestAgent = agentObj
    
    if bestScore > goal:
        GeneticAlgorithm.runAgentAgainstTest(agentObj, kaggleRequests, False)
        break

fh.close()
Esempio n. 41
0
    file1 = open(pathname + filename, openmode)
    return file1


# main
# initialising population
s = time.time()
subprocess.call([delete])
print("Running for.......\nMAX_ITERATION:", iter_max)
print("POPULATION SIZE:", MAX_POPULATION_SIZE)
print(
    "GENERATION#0-----------------------------------------------------------------------------------"
)
population = Population(MAX_POPULATION_SIZE, 0, "initialise")
#dplot1=plotter.DynamicUpdate()#plotting maximum fitness dynamically
GeneticAlgorithm.sort(population)
print_pop._print_population(population, 0)
iter = 1
sigma = [GeneticAlgorithm.std_deviation(0, iter_max, sigma_ini1, sigma_fin1)]
while iter < iter_max:
    print(
        "**************************************EVOLUTION STARTED*********************************************************"
    )
    sigma.append(
        GeneticAlgorithm.std_deviation(iter, iter_max, sigma_ini1, sigma_fin1))
    print(
        "GENERATION#", iter,
        "-----------------------------------------------------------------------------------"
    )
    print(
        "sigma shape:",