Esempio n. 1
0
def new_crossover(CA, DA, cr, mr, dim):
    ratio = GLOB.CA_DA_RATIO
    new_pop = []

    if len(CA + DA) < 2:
        new_pop += GA.initial_genes(dim, GLOB.POP)
        return new_pop
    elif len(CA) < 2 or len(DA) < 2:
        new_pop += GA.crossover(CA + DA, mr=mr)
        return new_pop

    for i in range(GLOB.POP):
        child = None

        # consider crossover rate
        if random.random() < cr:
            p1, p2 = None, None

            # randomly choose parents between CA and DA
            rand_num = random.random()
            if rand_num < ratio * ratio:
                p1, p2 = random.sample(CA, 2)
            elif rand_num < 2 * ratio - ratio * ratio:
                if random.random() < 0.5:
                    p1 = random.sample(CA, 1)[0]
                    p2 = random.sample(DA, 1)[0]
                else:
                    p1 = random.sample(DA, 1)[0]
                    p2 = random.sample(CA, 1)[0]
            else:
                p1, p2 = random.sample(DA, 2)

            child = GA.PMX(p1, p2)
        else:
            seq = random.sample(CA + DA, 1)[0].get_seq().copy()
            child = GA.Gene_Info(seq)

        # mutation
        if random.random() < mr:
            seq = child.get_seq()
            idx1, idx2 = random.sample(list(seq), 2)
            seq[idx2], seq[idx1] = seq[idx1], seq[idx2]

        #check overlap
        overlapped = False
        for parent in CA + DA:
            if (child.get_seq() == parent.get_seq()).all():
                overlapped = True
                break
        if overlapped:  # if overlap, do not add child at new_pop
            continue

        new_pop.append(child)

    return new_pop


#run_TAEA('sed',1,360)
Esempio n. 2
0
def new_crossover(CA,DA):
    ratio = GLOB.CA_DA_RATIO
    new_pop = []

    for i in range(GLOB.POP):
        p1,p2 = None,None
        if len(DA) != 0:
            rand_num = random.random()
            if rand_num < ratio*ratio:
                p1,p2 = random.sample(CA,2)
            elif rand_num < 2*ratio-ratio*ratio:
                p1 = random.sample(CA,1)[0]
                p2 = random.sample(DA,1)[0]
            else:
                p1,p2 = random.sample(DA,2)
        else:
            p1,p2 = random.sample(CA,2)

        child = GA.PMX(p1,p2)
        new_pop.append(child)

    return new_pop