Beispiel #1
0
def m_ga1(func,nvar,varmin,varmax,maxit,npop,optimization,thread_it,selection_type,x_type,gamma=0.1,mu=0.1,sigma=0.1,beta=1,pc=1):
    if(len(res)>0):
        res.clear()
    in_it=datetime.now()
    global q
    problem = structure()
    #here in the elifs you can add the make the func what you added above
    if "x^" in func:
        p,q=func.split("^")
        problem.costfunc=sphere
    elif func=='@rastrigin':#it's your choice what you add here like i enter func name as @rastrigin and the function called is rastrigin
        problem.costfunc=rastrigin
    elif func =="@ackley":
        problem.costfunc=ackley_path
    elif func=="@schwefel":
        problem.costfunc=schwefel
    elif func=="@griewangk":
        problem.costfunc=griewangk
    else:
        problem.costfunc=func_eval
    problem.func_expr=func
    problem.nvar = nvar
    varmin=varmin.split(',')
    varmax=varmax.split(',')
    problem.varmin = []
    problem.varmax=[]
    for item in varmin:
        problem.varmin.append(float(item))
    for item in varmax:
        problem.varmax.append(float(item))


    params = structure()
    params.maxit = maxit#the max iterations required
    params.npop = npop#the initial population 
    params.pc = pc
    params.gamma = gamma
    params.mu = mu#mutation rate
    params.sigma = sigma
    params.beta=beta
    params.optimization=optimization
    params.selection_type=selection_type
    params.x_type=x_type
    # run ga    
    if(thread_it=="Yes"):
        t=threading.Thread(target=wrapper,args=(ga.run_ga,(problem,params),res))
        t.start()
        while(len(res)==0):
            pass
        t.join()
        print(res)
        result = res[0]
    else:
        result=ga.run_ga(problem,params)
    std=np.std([x['cost'] for x in result.pop])
    fin_time=datetime.now()
    print(f"execution time is {fin_time-in_it}")
    print(f"following are the last offsprings {result.bestsol['position']}")
    print(f"the cost is {result.bestsol['cost']}")
    return result,std,result.bestsol['position']
Beispiel #2
0
def singlePointCrossover(parentOne, parentTwo, nVar):
    singlePoint = nVar // 2
    childOne = structure(
        list(parentOne.items())[:singlePoint] +
        list(parentTwo.items())[singlePoint:nVar])
    childTwo = structure(
        list(parentOne.items())[singlePoint:nVar] +
        list(parentTwo.items())[:singlePoint])
    return childOne, childTwo
Beispiel #3
0
def run(problem, params):
    # Problem information
    costfun = problem.costfun
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parameters
    maxit = params.maxit
    npop = params.npop
    pc = params.pc
    nc = np.round(pc * npop / 2) * 2
    gama = params.gama

    # Empty Individual Template
    empty_individual = structure()
    empty_individual.position = None
    empty_individual.cost = None

    bestol = empty_individual.deepcopy()
    bestol.cost = np.inf

    # Initialise population
    pop = empty_individual.repeat(npop)
    for i in range(0, npop):
        pop[i].position = np.random.uniform(varmin, varmax, nvar)
        pop[i].cost = costfun(pop[i].position)
        if pop[i].cost < bestol.cost:
            bestol = pop[i].deepcopy()

    # Best cost of interations
    bestcost = np.empty(maxit)

    # Main loop
    for it in range(maxit):
        popc = []
        for k in range(int(nc) // 2):
            # Select parents
            q = np.random.permutation(npop)
            p1 = pop[q[0]]
            p2 = pop[q[1]]

            # Perform crosssover
            c1, c2 = crosssover(p1, p2, gama)
    # Output
    out = structure()
    out.pop = pop

    return out
Beispiel #4
0
    def load(self, path: str = "./kriging_model.npy"):

        if path[-4:] != ".npy":
            path += ".npy"

        model = np.load(path, allow_pickle=True)[()]
        optim_dict = model["optim"]

        optim = structure(
            var_min=optim_dict["var_min"],
            var_max=optim_dict["var_max"],
            num_iter=optim_dict["num_iter"],
            num_pop=optim_dict["num_pop"],
            mu=optim_dict["mu"],
            sigma=optim_dict["sigma"],
            child_factor=optim_dict["child_factor"],
            gamma=optim_dict["gamma"],
        )

        self.parameters = model["parameters"]
        self.X = model["X"]
        self.n_feat = model["n_feat"]
        self.Psi = model["Psi"]
        self.y = model["y"]
        self.optim = optim

        print("Loaded parameters from saved model :\n {}".format(path))
Beispiel #5
0
Datei: ga.py Projekt: zfortes/AG
def create_initial_population(cities, config):
    initial_population = structure()
    initial_population.cost = 0
    initial_population.chromosome = list(range(0, 9))
    initial_population = initial_population.repeat(config.population_size)
    min_cost = structure()
    min_cost.cost = float('inf')
    for i in range(config.population_size):
        random.shuffle(initial_population[i].chromosome)
        initial_population[i].chromosome.insert(0, 9)
        initial_population[i].chromosome.insert(10, 9)
        initial_population[i].cost = calc_fitness(
            cities, initial_population[i].chromosome)
        if initial_population[i].cost < min_cost.cost:
            min_cost = initial_population[i]

    return initial_population, min_cost
Beispiel #6
0
def main_run(generations):
    #problem defination
    problem = structure()
    problem.cost_func = cost_func
    problem.varmin = [-12, -6]
    problem.varmax = [12, 6]
    problem.var = 2

    #GA paramters
    param = structure()
    param.npop = 1000
    param.niter = generations  #generations

    #Run GA
    #empty induvidual
    empty_induvidual = structure()
    empty_induvidual.cost = None
    empty_induvidual.value = None
    #best value
    best_value = structure()
    best_value.cost = 0
    best_value.value = None

    pop_gen = empty_induvidual.repeat(param.npop)
    pop_gen1 = empty_induvidual.repeat(param.npop)
    pop_gen2 = empty_induvidual.repeat(param.npop)

    for i in range(param.npop):
        pop_gen[i].value = np.random.uniform(problem.varmin, problem.varmax, 2)
        pop_gen[i].cost = cost_func(pop_gen[i].value[0], pop_gen[i].value[1])
        pop_gen1[i] = pop_gen[i].deepcopy()
        pop_gen2[i] = pop_gen[i].deepcopy()
        if pop_gen[i].cost > best_value.cost:
            best_value = pop_gen[i].deepcopy()

    print('first GA algorithm running----------')
    best_sol1, avg_list1, best_value1 = ga_first(pop_gen, best_value, problem,
                                                 param)
    print('secound GA algorithm running----------')
    best_sol2, avg_list2, best_value2 = ga_sec(pop_gen1, best_value, problem,
                                               param)
    print('third GA algorithm running----------')
    best_sol3, avg_list3, best_value3 = ga_third(pop_gen2, best_value, problem,
                                                 param)
    #best_value1=ga_sec(problem,params)
    return best_sol1, best_sol2, best_sol3, avg_list1, avg_list2, avg_list3, best_value1, best_value2, best_value3
Beispiel #7
0
def ga(ofun, optim: object, verbose: bool = True):

    optim = set_optim_defaults(optim)

    object_template = structure()
    object_template.variables = None
    object_template.cost = None

    best_individual = object_template.deepcopy()
    best_individual.cost = np.inf

    population = object_template.repeat(optim.num_pop)

    for individual in population:
        individual.variables = generate_random_variables(optim.var_min, optim.var_max)
        individual.cost = ofun(individual.variables)[0]

        if individual.cost < best_individual.cost:
            best_individual = individual.deepcopy()

    for iter in range(optim.num_iter):

        child_pop = []

        for _ in range(int(np.round(optim.child_factor * optim.num_pop / 2) * 2)):

            perm = np.random.permutation(optim.num_pop)
            child_1, child_2 = crossover(
                population[perm[0]], population[perm[1]], optim.gamma
            )

            child_1 = mutate(child_1, optim.mu, optim.sigma)
            child_2 = mutate(child_2, optim.mu, optim.sigma)

            child_1 = check_bounds(child_1, optim.var_min, optim.var_max)
            child_2 = check_bounds(child_2, optim.var_min, optim.var_max)

            child_1.cost = ofun(child_1.variables)[0]
            child_2.cost = ofun(child_2.variables)[0]

            if child_1.cost < best_individual.cost:
                best_individual = child_1.deepcopy()

            if child_2.cost < best_individual.cost:
                best_individual = child_2.deepcopy()

            child_pop += [child_1, child_2]

        population += child_pop
        population = sorted(population, key=lambda x: x.cost)
        population = population[: optim.num_pop]

        print(" >> Iter {} : cost = {} ".format(iter, best_individual.cost))
        print(" >> Params : {} \n".format(best_individual.variables))

    return best_individual.variables
Beispiel #8
0
 def init_children(self, gene_list, params):
     num_turtles = params.npop
     turt_params = structure()
     turt_params.tilesize = self.tilesize
     turt_params.start = self.start
     for gene in gene_list:
         turt_params.gene = gene
         turt_params.path = gu.card_to_coords(self.start, gene)
         t_obj = turtle(turt_params)
         self.turtle_list.append(t_obj)
Beispiel #9
0
 def init_turtles(self, params):
     num_turtles = params.npop
     turt_params = structure()
     turt_params.tilesize = self.tilesize
     turt_params.start = self.start
     for n in range(num_turtles):
         turt_params.path = self.create_random_path()
         turt_params.gene = gu.coords_to_cardinal(turt_params.path)
         t_obj = turtle(turt_params)
         self.turtle_list.append(t_obj)
Beispiel #10
0
def genChromosome(Ngen):
    """
    generate a chromosome with N number of genes:
    --------------------------------------------
    Ngen: int, number of genes in a chromosome
    --------------------------------------------
    return: structure
    """
    chromosome = structure()
    for i in range(Ngen):
        for y in range(Ngen):
            chromosome[f'{i},{y}'] = np.random.uniform(-1, 1)
    return chromosome
Beispiel #11
0
Datei: ga.py Projekt: zfortes/AG
def crossover(cities, parent1, parent2, config):
    probability = np.random.randint(0, 100)
    offspring = structure()

    if probability < 50:
        chromosome = crossover_one_cut(parent1, parent2)
    else:
        chromosome = crossover_two_cut(parent1, parent2)

    chromosome = mutation(chromosome, config.mutation_probability)
    offspring.cost = calc_fitness(cities, chromosome)
    offspring.chromosome = chromosome

    return offspring
Beispiel #12
0
 def filter_out_turtles(self):
     res_list = []
     for turtle in self.turtle_list:
         pos = (turtle.rect.centerx, turtle.rect.centery)
         if turtle.stopped:
             # Get a red X
             redx = structure()
             redx.surf = self.REDX
             redx.rect = redx.surf.get_rect(center=pos)
             self.redx_list.append(redx)
             # Calculate the cost of the turtle
             turtle.cost = self.calc_cost(turtle)
             # Add to retired turtles list
             self.retired_turtles.append(turtle)
         elif turtle.safe:
             check = structure()
             check.surf = self.CHECK
             check.rect = check.surf.get_rect(center=pos)
             self.check_list.append(check)
             turtle.cost = self.calc_cost(turtle)
             self.retired_turtles.append(turtle)
         else:
             res_list.append(turtle)
     self.turtle_list = res_list
Beispiel #13
0
def initialize():
    cities = structure()
    cities.name = [
        "SP", "BA", "RJ", "Lima", "Bog.", "Sant.", "Carac.", "BH", "PoA", "BsB"
    ]
    cities.distances = [[0, 17, 3, 35, 43, 26, 44, 5, 8, 9],
                        [17, 0, 20, 31, 47, 11, 51, 22, 8, 23],
                        [3, 20, 0, 38, 45, 29, 45, 3, 11, 9],
                        [35, 31, 38, 0, 19, 25, 27, 36, 33, 32],
                        [43, 47, 45, 19, 0, 43, 10, 43, 46, 37],
                        [26, 11, 29, 25, 43, 0, 49, 30, 19, 30],
                        [44, 51, 45, 27, 10, 49, 0, 42, 48, 35],
                        [5, 22, 3, 36, 43, 30, 42, 0, 13, 6],
                        [8, 8, 11, 33, 46, 19, 48, 13, 0, 16],
                        [9, 23, 9, 32, 37, 30, 35, 6, 16, 0]]
    return cities
Beispiel #14
0
def sort_select(pop, popc):
    npop = len(pop)
    pop += popc
    pop = sorted(pop, key=lambda x: x.cost)
    pop = pop[0:npop]
    costs = []
    for turtle in pop:
        costs.append(turtle.cost)

    best_cost = min(costs)
    avg_cost = np.mean(costs)

    out = structure()
    out.pop = pop
    out.avg_cost = avg_cost
    out.best_cost = best_cost
    return out
Beispiel #15
0
    def spawn_car(self):
        top = random.randrange(
            2)  # Random chance that car starts at bottom or top
        spawnpoint = (None, None)
        car = structure()
        car.surf = gu.load_tilesz(self.car_picture, self.tilesize)
        if top == 1:
            spawnpoint = (self.car_spawn_top, 0)
            car.direction = 1
            car.surf = pygame.transform.rotozoom(car.surf, 90, 1)
        else:
            spawnpoint = (self.car_spawn_bot, self.height * self.tilesize)
            car.direction = -1
            car.surf = pygame.transform.rotozoom(car.surf, -90, 1)

        car.rect = car.surf.get_rect(center=spawnpoint)
        self.car_list.append(car)
Beispiel #16
0
def run(problem, params):

    #Problem definition
    costfunc = problem.costfunc
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parameters
    maxit = params.maxit
    accep = params.accep
    npop = params.npop
    pc = params.pc
    nc = int(np.round(pc * npop / 2) * 2)
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma
    beta = params.beta

    # Empty Individual Template
    empty_individual = structure()
    empty_individual.position = None
    empty_individual.cost = None

    # BestSolution Ever Found
    bestsol = empty_individual.deepcopy()
    bestsol.cost = np.inf

    # Initialize Population
    pop = empty_individual.repeat(npop)
    for i in range(0, npop):
        pop[i].position = np.random.uniform(varmin, varmax, nvar)
        pop[i].cost = costfunc(pop[i].position)
        if pop[i].cost < bestsol.cost:
            bestsol = pop[i].deepcopy()

    # Best Cost of Interactions
    bestcost = []

    it = 0

    # Main Loop
    while bestsol.cost > accep and maxit > it:
        #for it in range(maxit):

        costs = np.array([x.cost for x in pop])
        avg_cost = np.mean(costs)
        if avg_cost != 0:
            costs = costs / avg_cost

        probs = np.exp(-beta * costs)

        popc = []
        for _ in range(nc // 2):  # nc = number of children

            # select parents RANDOM SELECTION
            #q = np.random.permutation(npop)
            #p1 = pop[q[0]]
            #p2 = pop[q[1]]

            # Perform Roulette Wheel Selection
            p1 = pop[roulette_wheel_selection(probs)]
            p2 = pop[roulette_wheel_selection(probs)]

            # Perform Crossover
            c1, c2 = crossover(p1, p2, gamma)

            # Perform Mutation
            c1 = mutate(c1, mu, sigma)
            c2 = mutate(c2, mu, sigma)

            # Check limits
            apply_bound(c1, varmin, varmax)
            apply_bound(c2, varmin, varmax)

            # Evaluate First Offspring
            c1.cost = costfunc(c1.position)
            if c1.cost < bestsol.cost:
                bestsol = c1.deepcopy()

            # Evaluate Second Offspring
            c2.cost = costfunc(c2.position)
            if c2.cost < bestsol.cost:
                bestsol = c2.deepcopy()

            # Add Offsprings to population
            popc.append(c1)
            popc.append(c2)

        # Merge, sort and select
        pop = pop + popc
        pop = sorted(pop, key=lambda x: x.cost)
        pop = pop[0:npop]

        # Store best cost
        bestcost.append(bestsol.cost)

        # Show info each int
        print("Interation {}: best output/cost = {}".format(it, bestcost[it]))

        it = it + 1

    # Output
    output = structure()
    output.pop = pop
    output.bestsol = bestsol
    output.bestcost = bestcost
    output.it = it
    return output
Beispiel #17
0
# xs = np.array([[1.5, 1.7, 2, 3, 3.5, 5]]).T
xs = np.linspace(1.5, 5, 15)[:, None]
ys = ofun(xs)

# Scale xs :
xs = (xs - x.min()) / (x.max() - x.min())
x = (x - x.min()) / (x.max() - x.min())

varmin = np.array([1, 1])
varmax = np.array([3, 2])
n_feat = 1
numiter = 10
numpop = 10
mu = 0.1
sigma = 0.1
child_factor = 10
gamma = 0.1

optim = structure(n_feat=n_feat,
                  var_min=varmin,
                  var_max=varmax,
                  num_iter=numiter,
                  num_pop=numpop,
                  mu=mu,
                  sigma=sigma,
                  child_factor=2,
                  gamma=gamma)

krigger = surmod.rbf.Kriging(optim=optim, verbose=True)

krigger.fit(xs, ys.ravel())
Beispiel #18
0
                        [3, 20, 0, 38, 45, 29, 45, 3, 11, 9],
                        [35, 31, 38, 0, 19, 25, 27, 36, 33, 32],
                        [43, 47, 45, 19, 0, 43, 10, 43, 46, 37],
                        [26, 11, 29, 25, 43, 0, 49, 30, 19, 30],
                        [44, 51, 45, 27, 10, 49, 0, 42, 48, 35],
                        [5, 22, 3, 36, 43, 30, 42, 0, 13, 6],
                        [8, 8, 11, 33, 46, 19, 48, 13, 0, 16],
                        [9, 23, 9, 32, 37, 30, 35, 6, 16, 0]]
    return cities


# Iniicializa a estrutura das cidades
cities = initialize()

# Parametros do algoritmo
config = structure()
#Tamanho da populacao
config.population_size = 20
# Numero de iteracoes que iram ser repetidas
config.number_iterations = 1000
# Probabilidade de ocorrer uma mutacao em um dado gene dos cromossomos filhos
# (0 a 100)
config.mutation_probability = 3
# Numero que representa o total de ocorrencias aleatorias que ocorreram durante
# a selecao de quem ira ou nao continuar na populacao
# Quanto maior for o valor, mais eventos aleatorios acontecerao  e em decorrencia
# disso mais aleatorio sera o resultado
# Quanto menor ele for definido maior sera as chances das novas populacoes serem
# escolhidas na selecao dos mais fortes e propensos a continuar a reproducao
config.cut_randomness = 30
Beispiel #19
0
def run(problem, params, verbose=False):
    # Problem Information
    func = problem.func
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parameters
    maxit = params.maxit
    npop = params.npop
    beta = params.beta
    pc = params.pc
    # Given the Population Count Increase Ratio, Calculate How Many Crossovers Will be Done In Each Iteration.
    # Let's also make sure it will always be an even Integer (so it will allign elegantly with the integer division
    # done in the crossover loop)
    nc = int(np.round(pc * npop / 2) * 2)
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma

    # Empty Individual Template
    empty_individual = structure()
    empty_individual.assignment = None
    empty_individual.reward = None

    # Best Solution Ever Found
    bestsol = empty_individual.deepcopy()
    bestsol.reward = -np.inf

    # Initialize Population
    pop = empty_individual.repeat(npop)
    for i in range(npop):
        pop[i].assignment = np.random.uniform(varmin, varmax, nvar)
        pop[i].reward = func(pop[i].assignment)
        #  bestsol Needs to be Replaced.
        if pop[i].reward > bestsol.reward:
            bestsol = pop[i].deepcopy()

    # Best Costs of Iterations
    bestreward = np.empty(maxit)

    # Main Loop
    for it in range(maxit):
        rewards = np.array([x.reward for x in pop])
        avg_reward = np.mean(rewards)
        if avg_reward != 0:
            rewards = rewards / avg_reward
        probs = np.exp(-beta * rewards)

        popc = []
        for _ in range(nc // 2):
            # Perform Roulette Wheel Selection
            p1 = pop[__roulette_wheel_selection(probs)]
            p2 = pop[__roulette_wheel_selection(probs)]

            # Perform Crossover
            c1, c2 = __crossover(p1, p2, gamma)

            # Perform Mutation
            c1 = __mutate(c1, mu, sigma)
            c2 = __mutate(c2, mu, sigma)

            # Apply Bounds
            __apply_bound(c1, varmin, varmax)
            __apply_bound(c2, varmin, varmax)

            # Evaluate First Offspring
            c1.reward = func(c1.assignment)
            if c1.reward > bestsol.reward:
                bestsol = c1.deepcopy()

            # Evaluate Second Offspring
            c2.reward = func(c2.assignment)
            if c2.reward > bestsol.reward:
                bestsol = c2.deepcopy()

            # Add Offsprings to popc
            popc.append(c1)
            popc.append(c2)

        # Merge
        pop += popc
        # Sort
        pop = sorted(pop, key=lambda x: x.reward, reverse=True)
        # Select
        pop = pop[0:npop]

        # Store Best Reward
        bestreward[it] = bestsol.reward

        if verbose:
            # Show Iteration Information
            print("Iteration {}: Best Reward in Iteration = {}".format(
                it, bestreward[it]))

    # Output
    out = structure()
    out.pop = pop
    out.bestsol = bestsol
    out.bestreward = bestreward
    return out
Beispiel #20
0
import numpy as np
import matplotlib.pyplot as plt
from ypstruct import structure
import growingneuralgas as gng

# Load Data
data = np.loadtxt('data.jain.txt')

# Neural Gas Parameters
params = structure()
params.N = 40
params.maxit = 50
params.L = 40
params.epsilon_b = 0.2
params.epsilon_n = 0.01
params.alpha = 0.5
params.delta = 0.995
params.T = 50

# Fit Neural Gas to Data
print("Fitting Growing Neural Gas Network ...")
net = gng.fit(data, params)

plt.figure()
plt.grid()
plt.scatter(data[:,0], data[:,1], s=2)
for i in range(0, params.N):
    for j in range(i+1, params.N):
        if net.C[i,j] == 1:
            plt.plot([net.w[i,0], net.w[j,0]], [net.w[i,1], net.w[j,1]], c='r')
Beispiel #21
0
def run(problem,params):
    temp = 0
    # Problem Bilgisinin alınması
    costfunc = problem.costfunc
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parametreler
    maxit = params.maxit
    npop = params.npop
    pc = params.pc
    nc = np.round(pc*npop/2)*2                                          # Üretilecek olan çocuk sayısı
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma


    # Boş birey şablonu
    empty_individual = structure()
    empty_individual.hedef = None
    empty_individual.yenidenSiparis = None
    empty_individual.cost = None


    # En iyi birey şablonu
    bestsol = empty_individual.deepcopy()                               # Eğer deepcopy() kullanılmazsa bestsol değiştiğinde empty_ind değeri de değişir
    bestsol.cost = np.inf                                               # Önceden en iyi çözümün maliyetini sonsuz bir değere eşitliyoruz


    # Popülasyonun (Boş bireylerden oluşan bir array) oluşturulması, bu kısım ilk iterasyon için hazırlandı, sonrasında 2,3,4.... n iterasyona kadar alttaki döngü çalışacak
    pop = empty_individual.repeat(npop)                                         # önceden belirlenmiş büyüklükte bir popülasyon oluşturulması
    for i in range(0,npop):
        pop[i].yenidenSiparis = np.random.uniform(varmin, varmax, nvar)         # önceden belirlenmiş sınırlar içerisinde, önceden belirlenmiş büyüklüğe göre
        pop[i].hedef = np.random.uniform(pop[i].yenidenSiparis[0], varmax, nvar)
        pop[i].cost = costfunc(pop[i].yenidenSiparis[0], pop[i].hedef[0])       #rastgele pozisyonların oluşturulması
        if pop[i].cost < bestsol.cost:                                          # eğer popülasyondaki i. bireyin (kromozomun) maliyet değeri
            bestsol = pop[i].deepcopy()                                         #en iyi bireyin maliyetinden küçükse en iyi değer değiştirilir


    # En iyi yineleme maliyeti
    bestcost = np.empty(maxit)                                          # Her iterasyonun sonunda en iyi maliyeti tutan içi boş array


    # Ana döngü
    for it in range(maxit):                                             # Bu döngü içerisinde her iterasyon için mutasyon, crossover, vb. gibi işlemler uygulanacak

        popc = []                                                       # Üretilecek çocukların listesi (ilk başta boş)
        for k in range (int(nc//2)):                                    # Yeni çocukların üretilmesi için for döngüsü

            # Ebeveynlerin seçimi
            q = np.random.permutation(npop)                             # 0'dan npop değerine kadar bütün sayıları rastgele bir sırayla içeren (her birinden 1 tane) array
            p1 = pop[q[0]]
            p2 = pop[q[1]]

            # Çocukların seçimi
            c1, c2 = crossover(p1,p2, gamma)                            # Rastgele oluşuturulan 2 ebeveynden crossover ile 2 çocuk üretiliyor

            # Mutasyon
            c1 = mutate(c1, mu, sigma)
            c2 = mutate(c2, mu, sigma)

            # Sınırların eklenmesi
            # apply_bound(c1, varmin, varmax)
            # apply_bound(c2, varmin, varmax)

            # Sonuçların değerlendirilmesi

            # Birinci çocuğun değerlendirilmesi
            c1.yenidenSiparis.sort()
            c1.hedef.sort()
            c1.cost = costfunc(c1.yenidenSiparis[0], c1.hedef[0])
            if c1.cost < bestsol.cost:
                bestsol = c1.deepcopy()

            # İkinci çocuğun değerlendirilmesi
            c2.yenidenSiparis.sort()
            c2.hedef.sort()
            c2.cost = costfunc(c2.yenidenSiparis[0], c2.hedef[0])
            if c2.cost < bestsol.cost:
                bestsol = c2.deepcopy()

            # Üretilen çocukların popülasyona dahil edilmesi
            popc.append(c1)
            popc.append(c2)

        # yeni popülasyonun eski popülasyona eklenmesi
        pop += popc
        # en iyi sonuçların bulunması için sıralama
        sorted(pop, key = lambda  x: x.cost)
        # popülasyon büyüklüğüne kadar olan (öreneğin ilk 50) kromozomun seçilip yeni iterasyon için popülasyon haline getirilmesi
        pop = pop[0:npop]


        # En iyi maliyetin hafızaya aktarılması

        bestcost[it] = bestsol.cost

        # Iterasyon bilgisinin print edilmesi, sadece iyileştirme olduğunda ve son iterasyonun sonucunu print eder
        if bestsol.yenidenSiparis[0] != temp:
            print("{}. İterasyondaki yeniden sipariş noktası = {}, hedef = {},en iyi maliyet = {}".format(it + 1,bestsol.yenidenSiparis[0],bestsol.hedef[0],bestcost[it]))
            temp = bestsol.yenidenSiparis[0]
        if it == (maxit-1):
            print("\n---------------------------------------------------\n\n{} dönem uygulanan optimizasyon sonucunda bulunan minimum maliyet = {}\nYeniden Sipariş Noktası = {}\nHedef = {}".format(maxit,bestcost[it],bestsol.yenidenSiparis[0],bestsol.hedef[0]))
Beispiel #22
0
        # Bir sonraki döneme geçiş yapılıyor
        kacinciDonem += 1
        baslangic_stok = kalan_stok

        # elde_bulundurma_ortalamasi = hesapArrayi[0]
        # yoksatma_maliyeti_ortalamasi = hesapArrayi[1]
        hesapArrayi = np.sum(maliyetler, axis=0)

    Toplam = np.sum(hesapArrayi)
    # Ortalama maliyeti döndürüyoruz
    return Toplam / donem


# Problem Tanımı
problem = structure(
)  # Problem değişkeni içerisinde 1den fazla veri gönderebilmek için
problem.costfunc = simulasyon  # Maliyet fonksiyonunun tanımlanması
problem.nvar = 1  # Değişken sayısı (popülasyonun her elemanı 5 değişkene sahip bir array olacak)
problem.varmin = 0  # Değişkeşerin alt sınırı
problem.varmax = 150  # Değişkenin üst sınırı

# GA parametreleri
params = structure()
params.maxit = 100  # Maksimum iterasyon sayısı
params.npop = 50  # Popülasyon büyüklüğü (kromozom sayısı)
params.pc = 1  # Üretilecek olan çocuk sayısının popülasyona oranı
params.gamma = 0.1
params.mu = 0.1
params.sigma = 0.1

# GA çalıştır
Beispiel #23
0
def run(problem, params):
    
    # Problem Information
    costfunc = problem.costfunc
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parameters
    maxit = params.maxit
    npop = params.npop
    beta = params.beta
    pc = params.pc
    nc = int(np.round(pc*npop/2)*2)
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma

    # Empty Individual Template
    empty_individual = structure()
    empty_individual.position = None
    empty_individual.cost = None

    # Best Solution Ever Found
    bestsol = empty_individual.deepcopy()
    bestsol.cost = np.inf

    # Initialize Population
    pop = empty_individual.repeat(npop)
    for i in range(npop):
        pop[i].position = np.random.uniform(varmin, varmax, nvar)
        pop[i].cost = costfunc(pop[i].position)
        if pop[i].cost < bestsol.cost:
            bestsol = pop[i].deepcopy()

    # Best Cost of Iterations
    bestcost = np.empty(maxit)
    
    # Main Loop
    for it in range(maxit):

        costs = np.array([x.cost for x in pop])
        avg_cost = np.mean(costs)
        if avg_cost != 0:
            costs = costs/avg_cost
        probs = np.exp(-beta*costs)

        popc = []
        for _ in range(nc//2):

            # Select Parents
            #q = np.random.permutation(npop)
            #p1 = pop[q[0]]
            #p2 = pop[q[1]]

            # Perform Roulette Wheel Selection
            p1 = pop[roulette_wheel_selection(probs)]
            p2 = pop[roulette_wheel_selection(probs)]
            
            # Perform Crossover
            c1, c2 = crossover(p1, p2, gamma)

            # Perform Mutation
            c1 = mutate(c1, mu, sigma)
            c2 = mutate(c2, mu, sigma)

            # Apply Bounds
            apply_bound(c1, varmin, varmax)
            apply_bound(c2, varmin, varmax)

            # Evaluate First Offspring
            c1.cost = costfunc(c1.position)
            if c1.cost < bestsol.cost:
                bestsol = c1.deepcopy()

            # Evaluate Second Offspring
            c2.cost = costfunc(c2.position)
            if c2.cost < bestsol.cost:
                bestsol = c2.deepcopy()

            # Add Offsprings to popc
            popc.append(c1)
            popc.append(c2)
        

        # Merge, Sort and Select
        pop += popc
        pop = sorted(pop, key=lambda x: x.cost)
        pop = pop[0:npop]

        # Store Best Cost
        bestcost[it] = bestsol.cost

        # Show Iteration Information
        print("Iteration {}: Best Cost = {}".format(it, bestcost[it]))

    # Output
    out = structure()
    out.pop = pop
    out.bestsol = bestsol
    out.bestcost = bestcost
    return out
Beispiel #24
0
def run(problem, params):
    # informações do problama
    costfunc = problem.costfunc
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax
    # parâmetros
    maxit = params.maxit
    npop = params.npop
    beta = params.beta
    pc = params.pc
    nc = int(np.round(pc * npop / 2) * 2)
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma
    # modelo individual vazio
    empty_individual = structure()
    empty_individual.position = None
    empty_individual.cost = None
    # melhor solução já encontrada
    bestsol = empty_individual.deepcopy()
    bestsol.cost = np.inf
    # população inicial
    pop = empty_individual.repeat(npop)
    for i in range(npop):
        pop[i].position = np.random.uniform(varmin, varmax, nvar)
        pop[i].cost = costfunc(pop[i].position)
        if pop[i].cost < bestsol.cost:
            bestsol = pop[i].deepcopy()
# melhor custo de iterações
    bestcost = np.empty(maxit)
    # loop principal
    for it in range(maxit):
        costs = np.array([x.cost for x in pop])
        avg_cost = np.mean(costs)
        if avg_cost != 0:
            costs = costs / avg_cost
        probs = np.exp(-beta * costs)
        popc = []
        for _ in range(nc // 2):
            # seleção proporcional de aptidão
            p1 = pop[roulette_wheel_selection(probs)]
            p2 = pop[roulette_wheel_selection(probs)]
            # executar cruzamento
            c1, c2 = crossover(p1, p2, gamma)
            # executar mutação
            c1 = mutate(c1, mu, sigma)
            c2 = mutate(c2, mu, sigma)
# aplicar limites
        apply_bound(c1, varmin, varmax)
        apply_bound(c2, varmin, varmax)
        # avaliação do primeiro descendente
        c1.cost = costfunc(c1.position)
        if c1.cost < bestsol.cost:
            bestsol = c1.deepcopy()
# valiação do segundo descendente
        c2.cost = costfunc(c2.position)
        if c2.cost < bestsol.cost:
            bestsol = c2.deepcopy()
# adicionar descendente ao popc
        popc.append(c1)
        popc.append(c2)
        # combinar, classificar e selecionar
        pop += popc
        pop = sorted(pop, key=lambda x: x.cost)
        pop = pop[0:npop]
        # melhor custo armazenado
        bestcost[it] = bestsol.cost
        # mostar as informações de iterações
        print("Iter {}: fun = {}".format(it, bestcost[it]))


# output
    out = structure()
    out.pop = pop
    out.bestsol = bestsol
    out.bestcost = bestcost
    return out
Beispiel #25
0
def breed_turtles(problem, params):
    # Extracting Problem information
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax
    turtle_list = problem.turtle_list

    # Extracting Parameters
    maxit = params.maxit
    npop = params.npop
    beta = params.beta
    pc = params.pc
    nc = int(np.round(pc * npop / 2) * 2)  # a ratio times total pop, rounded to make sure it is an integer value
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma
    it = params.it
    nelites = params.nelites

    # Best Solution found
    best_solution = structure()
    best_solution.gene = []
    best_solution.cost = np.inf  # This is the default value, which should be the worst case scenario

    pop = turtle_list
    # Sorting by best cost. the more positive the better
    pop.sort(key=lambda x: x.cost, reverse=False)

    elite_genes = []
    for turtle in pop:
        if turtle.cost < best_solution.cost:
            best_solution.gene = turtle.gene.copy()
            best_solution.cost = turtle.cost
            elite_genes.append(turtle.gene)

    elite_genes = elite_genes[len(elite_genes)-nelites:]

    # Best cost of Iterations
    best_cost_over_iterations = np.empty(maxit)  # array of maxit empty spots

    costs = np.array([turtle.cost for turtle in pop])  # List of costs for every member in population
    avg_cost = np.mean(costs)
    if avg_cost != 0:
        costs = costs / avg_cost

    children_gene_pool = []

    for k in range(nc // 2):  # nc is the number of children, a control variable, divided by 2
        # Selecting Parents here
        p1_gene = pop[k].gene.copy()
        p2_gene = pop[k+1].gene.copy()

        # Perform Crossover
        c1, c2 = crossover(p1_gene, p2_gene, mu)

        # Add children to population of children
        children_gene_pool.append(c1)
        children_gene_pool.append(c2)

    children_gene_pool.extend(elite_genes)
    return children_gene_pool
Beispiel #26
0
def run_ga(problem, params):
    # problem
    func_expr = problem.func_expr
    costfunc = problem.costfunc
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax
    # params
    maxit = params.maxit
    npop = params.npop
    gamma = params.gamma
    mu = params.mu
    sigma = params.sigma
    beta = params.beta
    flag = params.optimization
    selection_type = params.selection_type
    xtype = params.x_type
    # empty individual template
    empty_ind = structure()
    empty_ind.position = None
    empty_ind.cost = None

    # bestsolution
    best_sol = empty_ind.deepcopy()
    if (flag == "min"):
        best_sol.cost = np.inf
    else:
        best_sol.cost = -np.inf
    pc = float(params.pc)
    nc = int(np.round(pc * maxit / 2) * 2)
    # population init
    pop = empty_ind.repeat(npop)
    for i in range(0, npop):
        pop[i].position = np.random.uniform(varmin, varmax, nvar)
        pop[i].cost = costfunc(func_expr, pop[i].position)
        try:
            if (flag == "min"):
                if (pop[i].cost < best_sol.cost):
                    best_sol = pop[i].deepcopy()
            else:
                if (pop[i].cost > best_sol.cost):
                    best_sol = pop[i].deepcopy()
        except Exception as e:
            raise (e)
    # best cost
    bestcost = np.empty(maxit)
    if selection_type == "Tournament" or selection_type == "Elitism":
        if flag == "min":
            pop = sorted(pop, key=lambda x: x.cost)
        else:
            pop = sorted(pop, key=lambda x: x.cost, reverse=True)

    # main loop
    for it in range(maxit):
        popc = []
        costs = np.array([x.cost for x in pop])
        avg_cost = np.mean(costs)
        if avg_cost != 0:
            costs = costs / avg_cost
        probs = np.exp(-beta * costs)
        for _ in range(nc // 2):  # number of childrens we want
            if (selection_type == "Random"):
                q = np.random.permutation(npop)
                p1 = pop[q[0]]
                p2 = pop[q[1]]
                p3 = pop[q[1]]
            elif (selection_type == "Tournament"):
                q_all = np.random.randint(0, npop)
                p1 = pop[0]
                p2 = pop[q_all]
                p2 = pop[np.random.randint(0, npop)]
            elif selection_type == "Elitism":
                p1 = pop[np.random.randint(0, int(npop * 0.1))]
                p2 = pop[np.random.randint(0, int(npop * 0.1))]
                p2 = pop[np.random.randint(0, int(npop * 0.1))]
            else:
                p1 = pop[roullete(probs)]
                p2 = pop[roullete(probs)]
                p3 = pop[roullete(probs)]
            #crossover
            c1, c2 = crossover(p1, p2, p3, xtype, gamma)
            # mutation
            c1 = mutate(c1, mu, sigma)
            c2 = mutate(c2, mu, sigma)

            # bounds to the positions
            apply_bound(c1, varmin, varmax)
            apply_bound(c2, varmin, varmax)
            c1.cost = costfunc(func_expr, c1.position)
            c2.cost = costfunc(func_expr, c2.position)
            if flag == "min":
                if c1.cost < best_sol.cost:
                    best_sol = c1.deepcopy()
                if c2.cost < best_sol.cost:
                    best_sol = c2.deepcopy()
            else:
                if c1.cost > best_sol.cost:
                    best_sol = c1.deepcopy()
                if c2.cost > best_sol.cost:
                    best_sol = c2.deepcopy()
            popc.append(c1)
            popc.append(c2)

        pop += popc
        if flag == "min":
            pop = sorted(pop, key=lambda x: x.cost)
        else:
            pop = sorted(pop, key=lambda x: x.cost, reverse=True)
        pop = pop[0:maxit]
        bestcost[it] = best_sol.cost

    out = structure()
    out.pop = pop
    out.bestsol = best_sol
    out.bestcost = bestcost
    out_file = open("Results/math/res.txt", "wt")
    out_file.write(f"best soln {best_sol} ,best cost = {bestcost}")
    out_file.close()
    return out
Beispiel #27
0
def run(problem, params):
    """
    :param problem: estructura con datos del proble a optimizar
    :param params: parametros para la optimizacion
    :return: optimizacion por algoritmo genetico en formato diciconario y guarda en formato pkl
    
    codigo basado en el siguiente recurso:
    https://yarpiz.com/632/ypga191215-practical-genetic-algorithms-in-python-and-matlab

    Debugging
    --------
    problem = problem
    params = params
    """

    # informar que se inicia la optimización
    print('------------------------')
    print('Optimizacion del ratio de sharpe')
    print('------------------------')

    # Problem Information
    costfunc = problem.costfunc
    hist = problem.data
    investment = problem.init_invest
    backtest = problem.backtest
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parameters
    maxit = params.maxit  # Iterations
    npop = params.npop  # Population size
    beta = params.beta  #
    pc = params.pc  # proportion of children
    nc = int(np.round(pc * npop / 2) * 2)  # Number of children as even number
    gamma = params.gamma  # Exploration space
    mu = params.mu  # Mutarion chance
    sigma = params.sigma  # Step size

    # Empty Individual Template
    empty_individual = structure()
    empty_individual.position = None
    empty_individual.cost = None

    # Best Solution Ever Found
    bestsol = empty_individual.deepcopy()
    bestsol.cost = np.NINF

    # Initialize Population
    pop = empty_individual.repeat(npop)
    for i in range(npop):
        pop[i].position = np.random.randint(varmin, varmax, nvar)
        df_backtest = backtest(pop[i].position, hist, investment)
        pop[i].cost = costfunc(df_backtest)
        if pop[i].cost > bestsol.cost:
            bestsol = pop[i].deepcopy()

    # Best Cost of Iterations
    bestcost = np.empty(maxit)

    # Main Loop
    for it in range(maxit):
        ini = time.time()
        costs = np.array([x.cost for x in pop])
        avg_cost = np.mean(costs)
        if avg_cost != 0:
            costs = costs / avg_cost
        probs = np.exp(-beta * costs)

        popc = []
        for _ in range(nc // 2):

            # Select Parents
            # q = np.random.permutation(npop)
            # p1 = pop[q[0]]
            # p2 = pop[q[1]]

            # Perform Roulette Wheel Selection
            p1 = pop[roulette_wheel_selection(probs)]
            p2 = pop[roulette_wheel_selection(probs)]

            # Perform Crossover
            c1, c2 = crossover(p1, p2, gamma)

            # Perform Mutation
            c1 = mutate(c1, mu, sigma)
            c2 = mutate(c2, mu, sigma)

            # Apply Bounds
            apply_bound(c1, varmin, varmax)
            apply_bound(c2, varmin, varmax)

            # Evaluate First Offspring
            c1.cost = costfunc(backtest(c1.position, hist, investment))
            if c1.cost > bestsol.cost:
                bestsol = c1.deepcopy()

            # Evaluate Second Offspring
            c2.cost = costfunc(backtest(c2.position, hist, investment))
            if c2.cost > bestsol.cost:
                bestsol = c2.deepcopy()

            # Add Offsprings to popc
            popc.append(c1)
            popc.append(c2)

        # Merge, Sort and Select
        pop += popc
        pop = sorted(pop, key=lambda x: x.cost, reverse=True)
        pop = pop[0:npop]

        # Store Best Cost
        bestcost[it] = bestsol.cost

        # Show Iteration Information
        fin = time.time()
        print("Iteration {}: Best Sharpe = {}\n"
              " -Time: {:.2f} minutos".format(it, bestcost[it],
                                              (fin - ini) / 60))

        if it % 100 == 0 and it != 0:
            out = structure()
            out.pop = pop
            out.bestsol = bestsol
            out.bestcost = bestcost
            f_struct2dict(out, True)

    # Output
    out = structure()
    out.pop = pop
    out.bestsol = bestsol
    out.bestcost = bestcost
    modelo = f_struct2dict(out, True)
    return modelo
Beispiel #28
0
class game:
    pygame.init()
    """ DEFINE TILES """
    tilesize = 60
    W = 0  # WATER
    G = 1  # GRASS
    R = 2  # ROAD
    F = 3  # FOREST
    M = 4  # MUD
    X = 5  # CLIFF/FENCE - IMPASSABLE AREA

    # Defining tiles that should autopopulate in the map
    Tiles = (G, F, M)
    """DEFINE TILE COLORS/TEXTURES"""
    img_path = "assets/"
    WATER = gu.image_to_tile(img_path + "water.png", tilesize)
    GRASS = gu.image_to_tile(img_path + "grass.png", tilesize)
    ROAD = gu.image_to_tile(img_path + "road.png", tilesize)
    FOREST = gu.image_to_tile(img_path + "forest.png", tilesize)
    MUD = gu.image_to_tile(img_path + "mud.png", tilesize)
    IMPASSE = gu.image_to_tile(img_path + "cliff.png", tilesize)
    """ OTHER TEXTURES AND THINGS """
    REDX = None
    """LINK TILES AND TEXTURES/COLORS"""
    TileTexture = {W: WATER, G: GRASS, R: ROAD, F: FOREST, M: MUD, X: IMPASSE}
    """DEFINE MAP"""
    # map1 = np.array([[F, G, F, G, G, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, G, G, G, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, F, G, G, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, F, M, M, G, G, G, R, R, G, G, X, G, G, G, W],
    #                [G, G, F, M, M, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, F, M, M, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, M, F, G, G, X, G, G, R, R, G, G, X, G, G, G, W],
    #                [G, G, F, G, G, X, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, F, M, G, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, F, M, G, G, G, G, R, R, G, G, F, F, G, G, W],
    #                [G, G, G, G, G, G, G, G, R, R, G, G, G, G, G, G, W],
    #                [G, G, G, G, G, G, G, G, R, R, G, G, G, G, G, G, W]])

    map1 = np.array([
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17),
        random.choices(Tiles, k=17)
    ])

    # Creating the road and left water edge in the randomized map
    for i in range(12):
        map1[i, 8] = R
        map1[i, 9] = R
        map1[i, 16] = W
    """ DEFINE TILE SPEEDS """
    # Will multiply the movement by these numbers
    TileSpeed = {W: 4, G: 3, R: 3, F: 1, M: 2, X: 1}
    """ GAME VARIABLES """
    # Map
    width = len(map1[0])
    height = len(map1)
    # print("MAP1 is {} long and {} high".format(width, height))
    start = (tilesize // 2, (height * tilesize) // 2 - tilesize // 2)
    end = (width * tilesize, (height * tilesize) // 2)
    game_active = True
    wall_list = []
    redx_list = []
    check_list = []
    water_list = []

    # Car
    road_edge_left = 8
    road_edge_right = 10
    car_spawn_top = road_edge_left * tilesize + (tilesize // 2)
    car_spawn_bot = road_edge_right * tilesize - (tilesize // 2)
    car_speed = 5
    car_picture = img_path + "car3.png"
    # print("THESE", road_edge_left, road_edge_right)

    # Bridge
    bridge_params = structure()
    bridge_params.top = height - 1
    bridge_params.bot = 0
    bridge_params.left = 8
    bridge_params.tilesize = tilesize
    brg = bridge(bridge_params)
    """ GAME OBJECTS """
    turtle_list = []
    retired_turtles = []  # Put turtles here once they are dead or stuck
    car_list = []
    clock = pygame.time.Clock()
    """ EVENTS """
    SPAWNCAR = pygame.USEREVENT
    pygame.time.set_timer(
        SPAWNCAR,
        2000)  # Will probably make this a lot slower in the actual game
    """ HELPER FUNCTIONS """
    def init_turtles(self, params):
        num_turtles = params.npop
        turt_params = structure()
        turt_params.tilesize = self.tilesize
        turt_params.start = self.start
        for n in range(num_turtles):
            turt_params.path = self.create_random_path()
            turt_params.gene = gu.coords_to_cardinal(turt_params.path)
            t_obj = turtle(turt_params)
            self.turtle_list.append(t_obj)

    def init_children(self, gene_list, params):
        num_turtles = params.npop
        turt_params = structure()
        turt_params.tilesize = self.tilesize
        turt_params.start = self.start
        for gene in gene_list:
            turt_params.gene = gene
            turt_params.path = gu.card_to_coords(self.start, gene)
            t_obj = turtle(turt_params)
            self.turtle_list.append(t_obj)

    def calc_cost(self, turtle):
        cost = 1000

        # for coord in positioning:
        #     if coord[0] > x_pos_old:
        #         reward += 10
        #     elif coord[0] == x_pos_old:
        #         reward += 2
        #     elif coord[0] < x_pos_old:
        #         reward -= 5

        #     x_pos_old = coord[0]

        # Simpler to do it this way? With pixels instead of tiles
        cost -= 0.5 * turtle.rect.centerx
        cost += 0.3 * turtle.effort

        if turtle.bridge:
            cost -= 300
        if turtle.dead:
            cost += 600
        if turtle.stopped:
            cost += 200
        if turtle.safe:
            cost -= 1000
        return cost

    # Assumes a road of width 2 that vertically bisects the map in a straight line
    def spawn_car(self):
        top = random.randrange(
            2)  # Random chance that car starts at bottom or top
        spawnpoint = (None, None)
        car = structure()
        car.surf = gu.load_tilesz(self.car_picture, self.tilesize)
        if top == 1:
            spawnpoint = (self.car_spawn_top, 0)
            car.direction = 1
            car.surf = pygame.transform.rotozoom(car.surf, 90, 1)
        else:
            spawnpoint = (self.car_spawn_bot, self.height * self.tilesize)
            car.direction = -1
            car.surf = pygame.transform.rotozoom(car.surf, -90, 1)

        car.rect = car.surf.get_rect(center=spawnpoint)
        self.car_list.append(car)

    def move_cars(self):
        for car in self.car_list:
            # Check if car is out of map
            if car.direction == -1 and car.rect.centery < 0:
                self.car_list.remove(car)
                continue
            elif car.direction == 1 and car.rect.centery > (self.height *
                                                            self.tilesize):
                self.car_list.remove(car)
                continue
            car.rect.centery += self.car_speed * car.direction
            self.screen.blit(car.surf, car.rect)

    def get_tile_speed(self, turtle):
        pos = (turtle.rect.centerx, turtle.rect.centery)
        x, y = self.which_tile(pos)
        y = self.height - y
        if x > self.width or y > self.height:
            turtle.stop()
            return 0
        tile_type = self.map1[y - 1, x - 1]
        # print("On tile {} {} which is a tile of type {}".format(x,y,tile_type))
        return self.TileSpeed[tile_type]

    def create_random_path(self):
        tile_size = self.tilesize
        lower_bound = 0 - 1  # Remember this is the top of the screen in pygame
        high_bound = self.height + 1  # And this is the bottom
        left_bound = 0 - 1
        right_bound = self.width + 1
        game_map = self.map1
        start = self.which_tile(self.start)
        end = self.which_tile(self.end)
        tile_wise_path = []

        def is_end_path(pos):
            return pos[0] < left_bound or pos[0] > right_bound \
                   or pos[1] < lower_bound or pos[1] > high_bound \
                   or pos == end

        def remove_tile(tile, choices):
            for i in range(len(choices)):
                if tile[0] == choices[i][0] and tile[1] == choices[i][1]:
                    return np.delete(choices, i, 0)
            return choices

        # Create a tile-by-tile path
        current_tile = start
        prev_tile = current_tile
        while True:
            x, y = current_tile
            choices = np.array([[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1],
                                [x + 1, y + 1], [x + 1, y - 1], [x - 1, y + 1],
                                [x - 1, y - 1]])

            # Make sure to not travel back to previous tile
            choices = remove_tile(prev_tile, choices)

            # Randomly choose the next tile
            next_ind = random.randrange(len(choices))
            prev_tile = current_tile
            tile_wise_path.append(prev_tile)
            if is_end_path(prev_tile):
                break
            current_tile = (choices[next_ind][0], choices[next_ind][1])

        #print("\nCHOSE THIS PATH: ", tile_wise_path)
        return tile_wise_path

    def which_tile(self, pos):
        x = pos[0]
        y = pos[1]
        x_ind = x // self.tilesize
        y_ind = (self.height - 1) - (y // self.tilesize)
        return (x_ind, y_ind)

    def move_turtles(self):
        for turtle in self.turtle_list:
            path_ind = turtle.iteration
            tilesize = self.tilesize
            posx = turtle.rect.centerx  # Pixel
            posy = turtle.rect.centery
            current_tile = self.which_tile((posx, posy))

            # Check if turtle has reached goal
            if path_ind >= len(turtle.path) - 1:
                self.screen.blit(turtle.surf, turtle.rect)
                continue
            if turtle.path[path_ind] == current_tile:
                path_ind += 1
                turtle.iteration = path_ind
            elif turtle.path[path_ind] == current_tile and path_ind >= len(
                    turtle.path):
                turtle.stop()
                continue
            # print("\nGoing to ", turtle.path[path_ind])
            diffx = turtle.path[path_ind][0] - current_tile[0]
            diffy = turtle.path[path_ind][1] - current_tile[1]
            movex = 1
            movey = 1
            if not diffy:
                movey = 0
            if diffy > 0:
                movey *= -1
            if not diffx:
                movex = 0
            elif diffx < 0:
                movex *= -1
            speed = self.get_tile_speed(turtle)
            turtle.rect.centerx += speed * movex
            turtle.rect.centery += speed * movey
            turtle.animate(movex, movey)
            # print("\nMoved to ", which_tile((turtle.rect.centerx,turtle.rect.centery),game))
            turtle.effort += 1
            self.screen.blit(turtle.surf, turtle.rect)

    def pop_special_tiles_lists(self):
        for row in range(self.height):
            for col in range(self.width):
                if self.map1[row][col] == self.X:
                    surface = self.TileTexture[self.map1[row][col]]
                    rect = surface.get_rect(topleft=(col * self.tilesize,
                                                     row * self.tilesize))
                    self.wall_list.append(rect)
                elif self.map1[row][col] == self.W:
                    surface = self.TileTexture[self.map1[row][col]]
                    rect = surface.get_rect(topleft=(col * self.tilesize,
                                                     row * self.tilesize))
                    self.water_list.append(rect)

    # Call this function when a turtle dies or is stopped.
    # This does several things
    # Puts the stopped turtles in a retired list
    # Adds a red x to represent each turtle.
    def filter_out_turtles(self):
        res_list = []
        for turtle in self.turtle_list:
            pos = (turtle.rect.centerx, turtle.rect.centery)
            if turtle.stopped:
                # Get a red X
                redx = structure()
                redx.surf = self.REDX
                redx.rect = redx.surf.get_rect(center=pos)
                self.redx_list.append(redx)
                # Calculate the cost of the turtle
                turtle.cost = self.calc_cost(turtle)
                # Add to retired turtles list
                self.retired_turtles.append(turtle)
            elif turtle.safe:
                check = structure()
                check.surf = self.CHECK
                check.rect = check.surf.get_rect(center=pos)
                self.check_list.append(check)
                turtle.cost = self.calc_cost(turtle)
                self.retired_turtles.append(turtle)
            else:
                res_list.append(turtle)
        self.turtle_list = res_list

    def display_markers(self):
        for x in self.redx_list:
            self.screen.blit(x.surf, x.rect)
        for x in self.check_list:
            self.screen.blit(x.surf, x.rect)

    def in_map(self, turtle):
        high = self.height * self.tilesize
        right = self.width * self.tilesize
        low = 0
        left = 0
        posx = turtle.rect.centerx
        posy = turtle.rect.centery
        if posx > right or posx < left:
            return False
        elif posy > high or posy < low:
            return False
        else:
            return True

    def check_collision(self):
        # Check for wall and car collisions
        for turtle in self.turtle_list:
            if not self.in_map(turtle):
                turtle.stop()
            for wall in self.wall_list:
                if turtle.rect.colliderect(wall):
                    # print("HIT WALL")
                    turtle.stop()
            for water in self.water_list:
                if turtle.rect.colliderect(water):
                    turtle.save()
            for car in self.car_list:
                if turtle.rect.colliderect(car):
                    if turtle.rect.colliderect(self.brg.rect):
                        turtle.bridge = True
                        continue
                    # print("HIT CAR")
                    turtle.kill()

    def display_bridge(self):
        self.screen.blit(self.brg.surf, self.brg.rect)

    """MAIN GAME FUNCTIONS"""

    def init_game(self):
        pygame.init()
        self.screen = pygame.display.set_mode(
            (self.width * self.tilesize, self.height * self.tilesize))
        self.REDX = gu.load_half_tilesz(self.img_path + "redx.png",
                                        self.tilesize)
        self.CHECK = gu.load_half_tilesz(self.img_path + "check.png",
                                         self.tilesize)
        self.pop_special_tiles_lists()
        self.brg.load_pic(self.img_path + "bridge.jpeg", self.tilesize)

    def set_turtle_list(self, turtles):
        self.turtle_list = turtles

    def reset_turtles(self):
        for turtle in self.turtle_list:
            turtle.reset()
            turtle.rect.center = self.start

    def run_game(self):
        def display_map():
            """ DRAW MAP TO SCREEN """
            for row in range(self.height):
                for col in range(self.width):
                    surface = self.TileTexture[self.map1[row][col]]
                    rect = surface.get_rect(topleft=(col * self.tilesize,
                                                     row * self.tilesize))
                    self.screen.blit(surface, rect)

        """ MAIN LOOP """
        while True:
            if not self.turtle_list:  # This ends the round
                return
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == self.SPAWNCAR:
                    self.spawn_car()
            display_map()
            if self.turtle_list:
                self.move_turtles()
            if self.car_list:
                self.move_cars()
            self.check_collision()
            self.filter_out_turtles()
            if self.redx_list:
                self.display_markers()
            self.display_bridge()
            pygame.display.update()
            self.clock.tick(120)

    def reset(self):
        self.redx_list.clear()
        self.car_list.clear()
        self.check_list.clear()
        for turtle in self.turtle_list:
            turtle.reset()
            turtle.rect.center = self.start
random_permutation = np.random.permutation(letters)
#print(random_permutation)
open_text = 'helloworld'
cipher = encode_open_text(open_text, random_permutation)
print("Endcoded text: {}".format(cipher))
decoded_text = decode_chiper(cipher, random_permutation)
print("Decoded text: {}".format(decoded_text))

prob_open_text = costfunction(decoded_text, letters)
# print(prob_open_text)
# prob_cipher = costfunction(cipher, random_permutation)
# print(prob_cipher)
# print('over')

#Problem
problem = structure()
problem.costfunction = costfunction
problem.key = letters
problem.encoded_text = cipher

#Parameters
params = structure()
params.max_iterations = 10
params.npop = 100
#Precentage of population in the offspring
params.pc = 1
#Probability of mutation
params.pm = 0.1
#Number of positions in a crossover
params.crossover_positions = 8
#Probability of selecting the individual with better fitness in tournament selection
Beispiel #30
0
def fit(data, params):

    # Data Size and Dimension
    ndata = data.shape[0]
    ndim = data.shape[1]

    # Shuffle Data Points
    np.random.shuffle(data)

    # Find Min. and Max. of Data Points
    xmin = np.amin(data, axis=0)
    xmax = np.amax(data, axis=0)

    # Parameters
    N = params.N
    maxit = params.maxit
    L = params.L
    epsilon_b = params.epsilon_b
    epsilon_n = params.epsilon_n
    alpha = params.alpha
    delta = params.delta
    T = params.T
    
    # Initialization
    w = np.zeros((N,ndim))
    E = np.zeros(N)
    C = np.zeros((N,N))
    t = np.zeros((N,N))
    tt = 0

    K = 2
    for i in range(K):
        w[i] = np.random.uniform(xmin, xmax, (1,ndim))

    # Main Loop
    nx = 0
    for it in range(maxit):
        for l in range(ndata):
            
            # Get Input Vector
            nx += 1
            x = data[l]
            
            # Calculate Distance and Sort Neurons
            d = np.sum((x-w[0:K])**2, axis=1)    # Squared Distance
            sortorder = np.argsort(d)
            
            # Find 2 Best Neurons
            i = sortorder[0]
            j = sortorder[1]

            # Aging
            t[i,0:K] += 1
            t[0:K,i] += 1

            # Update Error
            E[i] += d[i]
            
            # Adaptation
            for k in range(K):
                if k == i:
                    eps = epsilon_b
                else:
                    if C[i,k] == 0:
                        continue
                        
                    eps = epsilon_n

                w[k] += eps*(x-w[k])

            # Create Link between 1st and 2nd Neurons
            C[i,j] = 1
            C[j,i] = 1
            t[i,j] = 0
            t[j,i] = 0

            # Remove Old Links
            old_links = t > T
            C[old_links] = 0
            nNeighbor = np.sum(C,axis=0)
            keeporder = np.argsort(-nNeighbor).tolist()
            C = C[keeporder,:][:,keeporder]
            t = t[keeporder,:][:,keeporder]
            w = w[keeporder,:]
            E = E[keeporder]
            K = np.where(nNeighbor>0)[0].size

            # Add New Nodes
            if K < N and nx % L == 0:
                q = np.argmax(E)
                f = np.argmax(C[q,:]*E)

                w[K] = (w[q]+w[f])/2
                C[K,:] = 0
                C[:,K] = 0
                t[K,:] = 0
                t[:,K] = 0

                C[q,f] = 0
                C[f,q] = 0
                C[q,K] = 1
                C[K,q] = 1
                C[f,K] = 1
                C[K,f] = 1
                
                E[q] *= alpha
                E[f] *= alpha
                E[K] = E[q]

            # Decrease Errors
            E *= delta

        # Display Iteration Info
        print("Iteration {0}".format(it))

    net = structure()
    net.w = w
    net.C = C
    net.t = t
    net.E = E

    return net