You are on page 1of 8

GENETIC ALIGORITHM IN PYTHON:

Step - 1: Create an initial population of P chromosomes.


step - 2 : Evaluate the ftness of chromosomes.
step - 3 : Choose P/2 parents from the current population via proportional selection.
step - 4 : Randomly select two parents to create offspring using crossover operator.
step - 5 : Apply mutation operators for minor changes in the results.
step - 6 : Repeat steps 4 & 5 until all parents are selected & mated.
step - 7 : Replace old population of chromosomes with new one.
step - 8 : Evaluate the fitness of each chromosome in the new population.
step - 9 : Terminate if the number of generations meets some upper bound; otherwise so to
step - 3.
By using the principles of Genetic Aligorithm we can sole this & the principles are:
1) FITNESS FUNCTION: Which represents the main requriments of the desired solution of a
problem.
2) ENCODING: It givess the possible solutions of a problem are considered as individuals in
a population.
3) SELECTION: It defines the way individuals in the current population.
4) CROSS OVER: It defines how chromosomes of parents are mixed in order to obtain
genetic codes of their offspring.
5) MUTATION: It creates random changes in genetic codes of the offspring.
 
Therefore the TWO point cross over on X1 & X2 are
X1 =  57 | 81469 | 23
X2 = 16 | 87543 | 92
CROSS OVER:
O1 = 578754323
O2 = 168146992

Question1. Write a python program to implement TSP (Travelling Salesman


problem) using genetic algorithm.
import requests import json from bs4 import BeautifulSoup def
get_distance(start, stop): api = "getYourOwnKeyDude" url =
"https://maps.googleapis.com/maps/api/distancematrix/json?
units=imperial&origins=" + start + "&destinations=" + stop + "&key=" +
api link = requests.get(url) json_loc = link.json()
distance = json_loc['rows'][0]['elements'][0]['distance']['text']
distance = int(''.join([d for d in distance if d.isdigit()==True]))
return distance cities = """ New York Los Angeles Chicago Houston
Phoenix Philadelphia San Antonio San Diego Dallas San Jose Austin
Jacksonville Fort Worth Columbus Charlotte San Francisco Indianapolis
Seattle Denver Washington DC Boston El Paso Nashville Detroit Oklahoma
City """ cities = [c for c in cities.split('\n') if c != ''] edges =
[] dist_dict = {c:{} for c in cities} for idx_1 in range(0,len(cities)-
1): for idx_2 in range(idx_1+1,len(cities)): city_a =
cities[idx_1] city_b = cities[idx_2] dist =
get_distance(city_a,city_b) dist_dict[city_a][city_b] = dist
edges.append((city_a,city_b,dist)) import random import operator from
numpy import vectorize class GeneticAlgo(): def
__init__(self,hash_map,start,steps=2,crossover_prob=0.15,mutation_prob=
0.15,population_size=5,iterations=100):
self.crossover_prob=crossover_prob
self.mutation_prob=mutation_prob
self.population_size=population_size self.hash_map = hash_map
self.steps = steps self.iterations = iterations
self.start = start self.cities = [k for k in
self.hash_map.keys()] self.cities.remove(start)
self.genes = [] self.epsilon = 1 - 1/self.iterations
self.generate_genes = vectorize(self.generate_genes)
self.evaluate_fitness = vectorize(self.evaluate_fitness)
self.evolve = vectorize(self.evolve) self.prune_genes =
vectorize(self.prune_genes) self.converge =
vectorize(self.converge) self.generate_genes()
def generate_genes(self): for i in range(self.population_size):
gene = [self.start] options = [k for k in self.cities]
while len(gene) < len(self.cities)+1: city =
random.choice(options) loc = options.index(city)
gene.append(city) del options[loc]
gene.append(self.start) self.genes.append(gene)
return self.genes def evaluate_fitness(self):
fitness_scores = [] for gene in self.genes:
total_distance = 0 for idx in range(1,len(gene)):
city_b = gene[idx] city_a = gene[idx-1]
try: dist = self.hash_map[city_a][city_b]
except: dist = self.hash_map[city_b][city_a]
total_distance += dist fitness = 1/total_distance
fitness_scores.append(fitness) return fitness_scores
def evolve(self): index_map = {i:'' for i in
range(1,len(self.cities)-1)} indices = [i for i in
range(1,len(self.cities)-1)] to_visit = [c for c in
self.cities] cross = (1 - self.epsilon) * self.crossover_prob
mutate = self.epsilon * self.mutation_prob crossed_count =
int(cross * len(self.cities)-1) mutated_count = int((mutate *
len(self.cities)-1)/2) for idx in range(len(self.genes)-1):
gene = self.genes[idx] for i in range(crossed_count):
try: gene_index = random.choice(indices)
sample = gene[gene_index] if sample in to_visit:
index_map[gene_index] = sample loc =
indices.index(gene_index) del indices[loc]
loc = to_visit.index(sample) del to_visit[loc]
else: continue except:
pass last_gene = self.genes[-1] remaining_cities = [c
for c in last_gene if c in to_visit] for k,v in
index_map.items(): if v != '': continue
else: city = remaining_cities.pop(0)
index_map[k] = city new_gene = [index_map[i] for i in
range(1,len(self.cities)-1)] new_gene.insert(0,self.start)
new_gene.append(self.start) for i in range(mutated_count):
choices = [c for c in new_gene if c != self.start] city_a =
random.choice(choices) city_b = random.choice(choices)
index_a = new_gene.index(city_a) index_b =
new_gene.index(city_b) new_gene[index_a] = city_b
new_gene[index_b] = city_a self.genes.append(new_gene)
def prune_genes(self): for i in range(self.steps):
self.evolve() fitness_scores = self.evaluate_fitness()
for i in range(self.steps): worst_gene_index =
fitness_scores.index(min(fitness_scores)) del
self.genes[worst_gene_index] del
fitness_scores[worst_gene_index] return
max(fitness_scores),self.genes[fitness_scores.index(max(fitness_scores)
)] def converge(self): for i in
range(self.iterations): values = self.prune_genes()
current_score = values[0] current_best_gene = values[1]
self.epsilon -= 1/self.iterations if i % 100 == 0:
print(f"{int(1/current_score)} miles") return
current_best_gene g =
GeneticAlgo(hash_map=dist_dict,start='Chicago',mutation_prob=0.25,cross
over_prob=0.25,
population_size=30,steps=15,iterations=2000) g.converge()
As An Example Of Something That
Seems Easy To Compute, But It Is
Actually Quite Difficult. In The Problem, A
Salesperson Starts At One City And Must
Visit Every Other City Exactly Once
Before Returning Home. Obviously, Some
Cities Are Further Apart Than Others, So
The Cost To Move Between Them Varies.
in JAva
Answer
// So as you mentioned I am writing code in which you can have a sequence of cities visited
instead of minimum distance for which I have used stack data structure I am also giving a
code which divided into two files TSP.java and TSPMain.java which are as follows. drop a
comment if any other assistance is needed.
 
TSP.java
import java.util.Stack;
public class TSP {
    private int no_of_vertices;
    private Stack<Integer> visited_cities;
    public TSP() {
        visited_cities = new Stack<Integer>();
    }
    public void tsp(int cities[][])
  {
        no_of_vertices = cities[1].length - 1;
        int[] visited = new int[no_of_vertices + 1];
        visited[1] = 1;
        visited_cities.push(1);
        int element, dst = 0, i;
        int min = Integer.MAX_VALUE;
        boolean minFlag = false;
        System.out.print(1 + "\t");
        while (!visited_cities.isEmpty())
    {
            element = visited_cities.peek();
            i = 1;
            min = Integer.MAX_VALUE;
            while (i <= no_of_vertices)
      {
                if (cities[element][i] > 1 && visited[i] == 0)
        {
                    if (min > cities[element][i])
          {
                        min = cities[element][i];
                        dst = i;
                        minFlag = true;
          }
        }
                i++;
      }
            if (minFlag)
      {
                visited[dst] = 1;
                visited_cities.push(dst);
                System.out.print(dst + "\t");
                minFlag = false;
                continue;
      }
            visited_cities.pop();
    }
  }
}
 
TSPMain.java
 
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TSPMain {
    public static void main(String[] args) {
        File file=new File("<path of file>");
        Scanner sc;
        int i=0,j=0;
        int a[][];
        try {
            sc=new Scanner(file);
            String S=sc.nextLine();
            String s[]=S.split(",");
            a=new int[s.length][s.length];
            while(S!=null) {
                for(j=0;j<s.length;j++)
                    a[i][j]=Integer.parseInt(s[j]);
                S=sc.nextLine();
                s=S.split(",");
                i++;
            }
            TSP tsp=new TSP();
            tsp.tsp(a);
            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(InputMismatchException e) {
            e.printStackTrace();
        }
        
    }
}

You might also like