text_plain_output_1.png
import pygad

import random

target_url = 'https://filebox.ece.vt.edu/~mhsiao/ISCAS89/s27.bench'
import urllib.request
outputs = []
inputs = []
for line in urllib.request.urlopen(target_url):
    l = line.decode('utf-8')
    if '=' in l:
        parse = l.split(' = ')
        outputs.append(parse[0])
        inputs.append(parse[1].split('(')[1].split(')')[0].split(', '))

n = len(outputs)
edges = []
for i in range(n):
    out = outputs[i]
    for j in range(n):
        if out in inputs[j]:
            edges.append([i + 1, j + 1])

nodesLen = n
edgesLen = len(edges)

def IC(chromosome):
    zeros = 0
    ones = 0
    for i in chromosome:
        if i == '0':
            zeros += 1
        else:
            ones += 1
    return abs(zeros - ones)
IC('0000000111111111111')

def PC(chromosome, edges):
    partition0 = []
    partition1 = []
    for i in range(len(chromosome)):
        if chromosome[i] == '0':
            partition0.append(i + 1)
        else:
            partition1.append(i + 1)
    pc = 0
    for i in edges:
        x, y = (i[0], i[1])
        if x in partition0 and y in partition1 or (x in partition1 and y in partition0):
            pc += 1
    return pc

a = 100
b = 10
edgesTemp = [[1, 2], [1, 3], [2, 4], [3, 6], [4, 5], [5, 6]]
def fitness(ga_instance, chromosome, chromosomeIdx):
    ic = IC(chromosome)
    pc = PC(chromosome, edges)
    cost = a * pc + b * ic * ic
    return 1.0 / cost

def on_generation(ga_instance):
    pass

import random
def getInitialPopulation(chromosomeLen, chromosomesReq):
    population = []
    for i in range(chromosomesReq):
        chromosome = []
        for j in range(chromosomeLen):
            chromosome.append(random.randint(0, 1))
        population.append(chromosome)
    return population

num_generations = 50
num_parents_mating = 2
init_range_low = 0
init_range_high = 2
initial_pop = getInitialPopulation(nodesLen, 20)

ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness, sol_per_pop=10, num_genes=nodesLen, gene_type=int, init_range_low=init_range_low, init_range_high=init_range_high, gene_space=[0, 1], initial_population=initial_pop, parent_selection_type='sss', K_tournament=3, crossover_type='scattered', crossover_probability=0.6, mutation_type='random', mutation_probability=0.1, save_best_solutions=True, on_generation=on_generation)

ga_instance.run()