示例#1
0
文件: sa.py 项目: ai-se/16sway
def sa(m,_, logDecs,logObjs):  
  sb = s = m.decide()
  eb = e = the.SA.energy(m,s,logObjs.space) 
  logDecs += s
  logObjs += s
  frontier = []
  for t,era in saControl():  
    era.e += [e] 
    sn  = mutate(s, get   = decisions, 
                 lower    = logDecs.space.lower, 
                 upper    = logDecs.space.upper, 
                 ok       = m.ok,
                 evaluate = m.eval) 
    
    
    logDecs += sn
    logObjs += sn
    en  = the.SA.energy(m,sn,logObjs.space)   
    if en < eb:
      eb = en
      era.better += 1
      era.sb, era.eb = sn,en
      frontier = [sb]
    elif m.bothAsGood(sn,sb, how=the.SA.how, space=logObjs):
      frontier += [sn]
    if en < e:
      s,e = sn,en
      era.lt += 1 
    elif exp((e - en)/t) < r():
      s,e = sn,en
      era.stagger += 1 
  return  frontier 
示例#2
0
文件: sa.py 项目: ai-se/16sway
def sa(m, _, logDecs, logObjs):
    sb = s = m.decide()
    eb = e = the.SA.energy(m, s, logObjs.space)
    logDecs += s
    logObjs += s
    frontier = []
    for t, era in saControl():
        era.e += [e]
        sn = mutate(s,
                    get=decisions,
                    lower=logDecs.space.lower,
                    upper=logDecs.space.upper,
                    ok=m.ok,
                    evaluate=m.eval)

        logDecs += sn
        logObjs += sn
        en = the.SA.energy(m, sn, logObjs.space)
        if en < eb:
            eb = en
            era.better += 1
            era.sb, era.eb = sn, en
            frontier = [sb]
        elif m.bothAsGood(sn, sb, how=the.SA.how, space=logObjs):
            frontier += [sn]
        if en < e:
            s, e = sn, en
            era.lt += 1
        elif exp((e - en) / t) < r():
            s, e = sn, en
            era.stagger += 1
    return frontier
示例#3
0
    def generate_random_phrase(klass):
        i = random.randint(0, len(base_rhythms) - 1)
        # print "rhythm", i
        rhythm = base_rhythms[i]
        for i in xrange(num_base_mutations):
            rhythm = mutate(rhythm)

        i = random.randint(0, len(base_hats) - 1)

        # print "hats",
        hats = base_hats[i]
        for i in xrange(num_base_mutations):
            hats = mutate(hats)

        return Phrase(
            90 + random.randint(0, 70),
            {0: None, 1: "samples/BT3AADA.WAV", 2: "samples/HANDCLP1.WAV", 3: "samples/CLOP1.WAV"},
            [rhythm, hats],
        )
示例#4
0
def MODE(nIter, nChr, nPop, F, Cr, func, lb, rb):
    """多目标差分进化算法主程序 
    Params:
        nIter: 迭代次数
        nPop: 种群规模 
        F: 缩放因子 
        Cr: 交叉概率 
        func:优化函数 
        lb: 自变量下界 
        rb:自变量上界 
    Return:
        paretoPops: 帕累托解集 
        paretoFits: 对应的适应度 
    """
    # 生成初始种群
    parPops = initPop(nChr, nPop, lb, rb)
    parFits = fitness(parPops, func)

    # 开始迭代
    iter = 1
    while iter <= nIter:
        # 进度条
        print("【进度】【{0:20s}】【正在进行{1}代...】【共{2}代】".\
            format('▋'*int(iter/nIter*20), iter, nIter), end='\r')

        mutantPops = mutate(parPops, F, lb, rb)  # 产生变异向量
        trialPops = crossover(parPops, mutantPops, Cr)  # 产生实验向量
        trialFits = fitness(trialPops, func)  # 重新计算适应度

        pops = np.concatenate((parPops, trialPops), axis=0)  # 合并成新的种群
        fits = np.concatenate((parFits, trialFits), axis=0)
        ranks = nonDominationSort(pops, fits)  # 非支配排序
        distances = crowdingDistanceSort(pops, fits, ranks)  # 计算拥挤度

        parPops, parFits = select1(nPop, pops, fits, ranks, distances)

        iter += 1
    print("\n")
    # 获取等级为0,即实际求解得到的帕累托前沿
    paretoPops = pops[ranks == 0]
    paretoFits = fits[ranks == 0]

    return paretoPops, paretoFits
示例#5
0
def NSGA2(nIter, nChr, nPop, pc, pm, etaC, etaM, func, lb, rb):
    """非支配遗传算法主程序 
    Params:
        nIter: 迭代次数 
        nPop: 种群大小 
        pc: 交叉概率 
        pm: 变异概率 
        func: 优化的函数 
        lb: 自变量下界
        rb: 自变量上界 
    """
    # 生成初始种群
    pops = initPops(nPop, nChr, lb, rb)
    fits = fitness(pops, func)

    # 开始第1次迭代
    iter = 1
    while iter <= nIter:
        # 进度条
        print("【进度】【{0:20s}】【正在进行{1}代...】【共{2}代】".\
            format('▋'*int(iter/nIter*20), iter, nIter), end='\r')
        ranks = nonDominationSort(pops, fits)  # 非支配排序
        distances = crowdingDistanceSort(pops, fits, ranks)  # 拥挤度
        pops, fits = select1(nPop, pops, fits, ranks, distances)
        chrpops = crossover(pops, pc, etaC, lb, rb)  # 交叉产生子种群
        chrpops = mutate(chrpops, pm, etaM, lb, rb)  # 变异产生子种群
        chrfits = fitness(chrpops, func)
        # 从原始种群和子种群中筛选
        pops, fits = optSelect(pops, fits, chrpops, chrfits)
        iter += 1
    # 对最后一代进行非支配排序
    ranks = nonDominationSort(pops, fits)  # 非支配排序
    distances = crowdingDistanceSort(pops, fits, ranks)  # 拥挤度
    paretoPops = pops[ranks == 0]
    paretoFits = fits[ranks == 0]
    return paretoPops, paretoFits
示例#6
0
bin_count_gen0, bin_IDs_gen0 = bin3d('gen0', bins)    # bin library

p_list_gen0 = pick_parents('gen0',                    # select parents
                           bin_count_gen0,
                           bin_IDs_gen0,
                           n_child)

dummy_screen(HTSOHM_dir, 'gen0')                      # dummy test, screen

# WAIT FOR JOBS

dummy_test(HTSOHM_dir, 'gen0')                        # dummy test, check output

firstS('gen0', mutation_strength, bins)               # set mutation strength(s)
mutate('gen0', number_of_atom_types, 'gen1')          # mutate gen0, create gen1

screen(HTSOHM_dir, 'gen1', 1 * number_of_materials,   # screen gen1
       number_of_materials)

# WAIT FOR JOBS

prep4mut(HTSOHM_dir, 'gen1', 1 * number_of_materials, # collect output
         number_of_materials, 'gen0', 'tgen1')

find_missing('tgen1')                                 # find missing data points




####
示例#7
0
def main():

    plotting = False  # Set to True if you want 2d plotting. The plotting is to be improved.

    population_size = 200
    n_genes = 60  # Right now, this must be a number divisible by n_dimensions
    crossover_probability = 0.8
    mutation_probability = 1/n_genes
    tournament_selection_parameter = 0.75
    tournament_size = 2
    n_generations = 100
    n_dimensions = 2
    variable_range = 5.0  # plus-minus 5.0
    n_elites = 2

    decoded_population = np.zeros((population_size, n_dimensions))  # Chromosomes along rows.
    fitness = np.zeros((1, population_size))

    population = initialise_population(population_size, n_genes)

    for i_generation in range(n_generations):

        maximum_fitness = 0.0
        x_best = np.zeros(n_dimensions)
        i_best_individual = -1

        # Decoding and assigning fitness values.
        for i in range(population_size):
            chromosome = population[i, :]
            x = decode_chromosome(chromosome, n_dimensions, variable_range)
            decoded_population[i, :] = x
            fitness[0, i] = evaluate_individual(x)

            if fitness[0, i] > maximum_fitness:
                maximum_fitness = fitness[0, i]
                i_best_individual = i
                x_best = copy.copy(x)

        temp_population = copy.copy(population)

        # Tournament and crossover.
        for i in range(0, population_size, 2):
            i1 = tournament_select(fitness, tournament_selection_parameter, tournament_size)
            i2 = tournament_select(fitness, tournament_selection_parameter, tournament_size)

            chromosome1 = population[i1, :]
            chromosome2 = population[i2, :]

            if i + 1 < population_size:
                r = random.random()
                if r < crossover_probability:
                    new_chromosome_pair = cross(chromosome1, chromosome2)
                    temp_population[i, :] = new_chromosome_pair[0, :]
                    temp_population[i + 1, :] = new_chromosome_pair[1, :]
                else:
                    temp_population[i, :] = copy.copy(chromosome1)
                    temp_population[i + 1, :] = copy.copy(chromosome2)
            else:
                temp_population[i, :] = copy.copy(chromosome1)

        # Mutation
        for i in range(population_size):
            original_chromosome = temp_population[i,:]
            mutated_chromosome = mutate(original_chromosome, mutation_probability)
            temp_population[i, :] = mutated_chromosome

        population = copy.copy(temp_population)

        # Elitism
        population = insert_best_individual(n_elites, population, i_best_individual)

        if plotting:
            plt.clf()
            plt.plot(decoded_population[:,0], decoded_population[:, 1], marker='*', linestyle = '')
            plt.draw()
            plt.show(block=False)

    print(x_best)