Hi I am trying to apply NSGA-II and my logic is pretty simple I randomly choose two number within the range and applying crossover but the code is giving index out of range error

Here is my code :

def make_child_pop(parent_set, child_set):
    for i in range(popul):
        r1 = random.randint(0, req-1)
        r2 = random.randint(0, req-2)
        c1=[]
        c2=[]
        if r2 >= r1:
            r2 += 1
        # r1, r2 crossover
        r3 = random.randint(0, req-1)
    try:
        c1 = parent_set[r1][:r3] + parent_set[r2][r3:]
        c2 = parent_set[r2][:r3] + parent_set[r1][r3:]
        except IndexError:
            print(parent_set, r3, r1, r2)

        # r4 : mutation
        r4 = random.randint(0, 99)
        r5 = random.randint(0, 99)
        if r4 < 100 * mutation_rate:
            r6 = random.randint(0, req-1)
            c1[r6] = not c1[r6]
        if r5 < 100 * mutation_rate:
            r6 = random.randint(0,req-1)
            c2[r6] = not c2[r6]
        child_set.append(c1)
        child_set.append(c2)
    child_set = child_set + copy.copy(parent_set)

I personally think the problem lies in this part

try:
    c1 = parent_set[r1][:r3] + parent_set[r2][r3:]
    c2 = parent_set[r2][:r3] + parent_set[r1][r3:]
except IndexError:
    print(parent_set, r3, r1, r2)

Any help will be greatly appreciated.

0 Answers