I am new to genetic algorithms and made one the other day that recreated a target string. So I tried to make one that could make a Magic Square. It was ok until I got to the crossover part, realising I couldn't just do a single point crossover. So I attempted to perform a Partially Mapped Crossover, and I could not and still can't get it to work. I understand how the Partially Mapped Crossover works I just can't implement it into python. Since my code isn't complete yet I isolated the crossover function in a different program and changed it so the parents were a fixed list.
Can someone please correct my code or if it is completely wrong show me how to perform a Partial Mapped Crossover on 2 lists with integers 1 to 9? Also, I am sorry and understand that my naming of variables isn't that good but I was just trying to get the program to work making constant edits.
import random
parent1 = [1,2,3,4,5,6,7,8,9]
parent2 = [5,4,6,7,2,1,3,9,8]
firstCrossPoint = random.randint(0,len(parent1)-1) #Creating parameters for random sublist
secondCrossPoint = random.randint(firstCrossPoint+1,len(parent1))
parent1MiddleCross = parent1[firstCrossPoint:secondCrossPoint]
parent2MiddleCross = parent2[firstCrossPoint:secondCrossPoint]
child1 = (parent1[:firstCrossPoint] + parent2MiddleCross + parent1[secondCrossPoint:])
child2 = (parent2[:firstCrossPoint] + parent1MiddleCross + parent2[secondCrossPoint:])
relationsWithDupes = []
for i in range(len(parent1MiddleCross)):
relationsWithDupes.append([parent2MiddleCross[i], parent1MiddleCross[i]])
relations = []
for pair in relationsWithDupes:
for i in range(len(relationsWithDupes)):
if pair[0] in relationsWithDupes[i] or pair[1] in relationsWithDupes[i]:
if pair != relationsWithDupes[i]:
if pair[0] == relationsWithDupes[i][1]:
pair[0] = relationsWithDupes[i][0]
else:
pair[1] = relationsWithDupes[i][1]
if pair not in relations and pair[::-1] not in relations:
relations.append(pair)
for i in child1[:firstCrossPoint]:
for x in relations:
if i == x[0]:
i = x[1]
for i in child1[secondCrossPoint:]:
for x in relations:
if i == x[0]:
i = x[1]
for i in child2[:firstCrossPoint]:
for x in relations:
if i == x[1]:
i = x[0]
for i in child2[secondCrossPoint:]:
for x in relations:
if i == x[1]:
i = x[0]
print(child1)
print(child2)
I just stumbled across this when looking for an implementation of PMX and it seems unnecessarily complicated? I've included below an alternative I've just coded if anyone comes across the same issue.