Skip to content

Commit

Permalink
feat: Multiprocessing feature added
Browse files Browse the repository at this point in the history
- Fixed multiprocessing feature.
- Added positional arguments to run()
- Added default args to d,f,seed for multiproc runs
- Added max_time parameter to __init__ of base_algorithm.FlightAlgorithm and all overrriding ABCs
  • Loading branch information
Agrover112 committed Aug 29, 2021
1 parent 40df096 commit 8cc840e
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 96 deletions.
8 changes: 3 additions & 5 deletions flight_algorithms/algorithms/base_algorithm.py
Expand Up @@ -5,12 +5,13 @@
import sys

class FlightAlgorithm(metaclass=ABCMeta):
def __init__(self, domain, fitness_function,seed=random.randint(10, 100),seed_init=True,init=[])-> None:
def __init__(self, domain, fitness_function,seed=random.randint(10, 100),seed_init=True,init=[],max_time=1000)-> None:
self.domain = domain
self.fitness_function = fitness_function
self.seed = seed
self.seed_init = seed_init
self.init = init
self.max_time=1000
if self.seed_init:
# Set the seed for initial population only
self.r_init = random.Random(seed)
Expand All @@ -29,8 +30,5 @@ def get_name(self) -> str:
pass

@abstractmethod
def run(self, **kwargs) -> tuple:
pass
@abstractmethod
def run(self,**kwargs) -> tuple:
def run(self,domain,fitness_function,seed) -> tuple:
pass
50 changes: 23 additions & 27 deletions flight_algorithms/algorithms/ga.py
Expand Up @@ -2,7 +2,6 @@
import os
import time
sys.path.append(os.getcwd())
#sys.path.append("/mnt/d/MINOR PROJECT/final/")
from utils.utils import plot_scores, print_schedule, read_file
from flight_algorithms.algorithms.base_algorithm import FlightAlgorithm
from flight_algorithms.algorithms.rs import RandomSearch
Expand All @@ -16,10 +15,10 @@

class BaseGA(FlightAlgorithm, metaclass=ABCMeta):

def __init__(self, domain, fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],max_time=100,
population_size=100, step=1, probability_mutation=0.2, probability_crossover=0.2, elitism=0.2,
number_generations=500, search=False) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init)
super().__init__(domain, fitness_function, seed, seed_init, init,max_time)
self.population_size = population_size
self.step = step
self.probability_mutation = probability_mutation
Expand All @@ -36,28 +35,27 @@ def get_name(self) -> str:
pass

@abstractmethod
def run(self,**kwargs) -> tuple:
def run(self,domain,fitness_function,seed) -> tuple:
pass




class GA(BaseGA):
def __init__(self, domain, fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],max_time=100,
population_size=100, step=1, probability_mutation=0.2, elitism=0.2,
number_generations=500, search=False) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init, population_size, step, probability_mutation,
super().__init__(domain, fitness_function, seed, seed_init, init,max_time, population_size, step, probability_mutation,
0, elitism, number_generations, search)

def run(self,**kwargs) -> tuple:
max_time=kwargs.get('max_time',1000)
def run(self,domain,fitness_function,seed) -> tuple:
population = []
scores = []
nfe = 0
for i in range(self.population_size):
if self.search == True:
solution, b_c, sc, r_nfe, s = RandomSearch(
self.domain, self.fitness_function, self.seed).run()
).run(self.domain, self.fitness_function, self.seed)
nfe += r_nfe
if len(self.init) > 0:
solution = self.init
Expand Down Expand Up @@ -98,28 +96,27 @@ def run(self,**kwargs) -> tuple:
population.append(
crossover(domain, ordered_individuals[i1], ordered_individuals[i2]))

if time.time()-self.start_time>max_time:
if time.time()-self.start_time>self.max_time:
return costs[0][1], costs[0][0], scores, nfe, self.seed

return costs[0][1], costs[0][0], scores, nfe, self.seed


class ReverseGA(BaseGA):
def __init__(self, domain, fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],max_time=100,
population_size=100, step=1, probability_crossover=0.2, elitism=0.2,
number_generations=500, search=False) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init, population_size, step, 0.0,
super().__init__(domain, fitness_function, seed, seed_init, init,max_time, population_size, step, 0.0,
probability_crossover, elitism, number_generations, search)

def run(self,**kwargs) -> tuple:
max_time=kwargs.get('max_time',1000)
def run(self,domain,fitness_function,seed) -> tuple:
population = []
scores = []
nfe = 0
for i in range(self.population_size):
if self.search == True:
solution, b_c, sc, r_nfe, s = RandomSearch(
self.domain, self.fitness_function, self.seed).run()
).run(self.domain, self.fitness_function, self.seed)
nfe += r_nfe
if len(self.init) > 0:
solution = self.init
Expand Down Expand Up @@ -160,32 +157,31 @@ def run(self,**kwargs) -> tuple:
population.append(
mutation(self.domain, self.step, ordered_individuals[m]))

if time.time()-self.start_time>max_time:
if time.time()-self.start_time>self.max_time:
return costs[0][1], costs[0][0], scores, nfe, self.seed

return costs[0][1], costs[0][0], scores, nfe, self.seed



class GAReversals(BaseGA):
def __init__(self, domain, fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100), seed_init=True, init=[],max_time=100,
population_size=100, step=1, probability_mutation=0.2, elitism=0.2,
number_generations=500, search=False,n_k=250, step_length=100,) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init, population_size, step, probability_mutation,
super().__init__(domain, fitness_function, seed, seed_init, init,max_time, population_size, step, probability_mutation,
0.0, elitism, number_generations, search)
self.n_k = n_k
self.step_length = step_length

def run(self,**kwargs) -> tuple:
max_time=kwargs.get('max_time',1000000)
def run(self,domain,fitness_function,seed) -> tuple:
population = []
scores = []
nfe = 0
rev = 0
for i in range(self.population_size):
if self.search == True:
solution, b_c, sc, r_nfe, s = RandomSearch(
self.domain, self.fitness_function, self.seed).run()
).run(self.domain, self.fitness_function,self.seed)
nfe += r_nfe
if len(self.init) > 0:
solution = self.init
Expand Down Expand Up @@ -219,7 +215,7 @@ def run(self,**kwargs) -> tuple:
if not self.fitness_function.__name__ == 'fitness_function':
scores.append(self.fitness_function(population[0]))
else:
scores.append(fitness_function(population[0], 'FCO'))
scores.append(self.fitness_function(population[0], 'FCO'))
nfe += 1
while len(population) < self.population_size:
if random.random() < self.probability_mutation:
Expand Down Expand Up @@ -252,17 +248,17 @@ def run(self,**kwargs) -> tuple:
population.append(
mutation(self.domain, self.step, ordered_individuals[m]))

if time.time()-self.start_time>max_time:
if time.time()-self.start_time>self.max_time:
return costs[0][1], costs[0][0], scores, nfe, self.seed

return costs[0][1], costs[0][0], scores, nfe, self.seed


if __name__ == '__main__':
read_file('flights.txt')
sga = GAReversals(domain=domain['domain'], fitness_function=fitness_function,
seed=5, seed_init=False, search=True,n_k=125)
sga = ReverseGA(seed_init=False,search=True)

soln, cost, scores, nfe, seed = sga.run()
plot_scores(scores, sga.get_base(), save_fig=False)
soln, cost, scores, nfe, seed = sga.run(domain=domain['domain'], fitness_function=fitness_function,
seed=5)
plot_scores(scores, sga.get_base(),fname='flight_scheduling', save_fig=True)
print_schedule(soln, 'FCO')
20 changes: 10 additions & 10 deletions flight_algorithms/algorithms/hc.py
Expand Up @@ -2,7 +2,6 @@
import os
sys.path.append(os.getcwd())
import time
#sys.path.append("/mnt/d/MINOR PROJECT/final/")
from abc import ABCMeta
from utils.utils import plot_scores, print_schedule, read_file
from flight_algorithms.algorithms.base_algorithm import FlightAlgorithm
Expand All @@ -11,9 +10,9 @@
from fitness import *

class HillClimb(FlightAlgorithm,metaclass=ABCMeta):
def __init__(self, domain, fitness_function, seed=random.randint(10, 100),
seed_init=True, init=[], epochs=100) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init)
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100),
seed_init=True, init=[], max_time=1000,epochs=100) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init)
self.epochs = epochs
self.best_solution=0.0

Expand All @@ -22,8 +21,7 @@ def get_base(self) -> str:
def get_name(self) -> str:
return self.__class__.__name__

def run(self,**kwargs) -> tuple:
max_time=kwargs.get('max_time',1000)
def run(self,domain,fitness_function,seed) -> tuple:
count = 0
scores = []
nfe = 0
Expand Down Expand Up @@ -71,14 +69,16 @@ def run(self,**kwargs) -> tuple:
# print('NFE: ',nfe)
break

if time.time()-self.start_time>max_time:
if time.time()-self.start_time>self.max_time:
return solution, best_cost, scores, nfe, self.seed

return solution, best_cost, scores, nfe, self.seed



if __name__ == '__main__':
read_file('flights.txt')
hc=HillClimb(domain=domain['griewank']*5,fitness_function=griewank,seed=5,seed_init=False)
soln, cost, scores, nfe, seed=hc.run(max_time=0.0000001)
#plot_scores(scores,hc.get_name(),save_fig=False)
hc=HillClimb(seed_init=False,max_time=0.0000001)
soln, cost, scores, nfe, seed=hc.run(domain=domain['griewank']*5,fitness_function=griewank,seed=5)
plot_scores(scores,hc.get_name(),fname='griewank',save_fig=True)
#print_schedule(soln,'FCO')
74 changes: 33 additions & 41 deletions flight_algorithms/algorithms/rs.py
Expand Up @@ -2,7 +2,6 @@
import os
sys.path.append(os.getcwd())
import time
#sys.path.append("/mnt/d/MINOR PROJECT/final/")
from abc import ABCMeta
from utils.utils import plot_scores, print_schedule, read_file
from flight_algorithms.algorithms.base_algorithm import FlightAlgorithm
Expand All @@ -12,9 +11,9 @@


class RandomSearch(FlightAlgorithm, metaclass=ABCMeta):
def __init__(self, domain, fitness_function, seed=random.randint(10, 100),
seed_init=True, init=[], epochs=100) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init)
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100),
seed_init=True, init=[],max_time=1000,epochs=100) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init,max_time)
self.epochs = epochs
self.best_cost=sys.maxsize
self.best_solution=0.0
Expand All @@ -25,49 +24,42 @@ def get_base(self) -> str:
def get_name(self) -> str:
return self.__class__.__name__

def run(self,**kwargs) -> tuple:
max_time=kwargs.get('max_time',1000)
scores = []
nfe = 0
if len(self.init) > 0:
solution = self.init
else:
solution = [self.r_init.randint(self.domain[i][0], self.domain[i][1])
for i in range(len(self.domain))]

self.start_time=time.time()
for i in range(self.epochs):
if i != 0:
solution = [random.randint(self.domain[i][0], self.domain[i][1])
for i in range(len(self.domain))]
if not self.fitness_function.__name__ == 'fitness_function':
cost = self.fitness_function(solution)
else:
cost = self.fitness_function(solution, 'FCO')
nfe += 1
if cost < self.best_cost:
self.best_cost = cost
self.best_solution = solution
scores.append(self.best_cost)

if time.time()-self.start_time>max_time:
return self.best_solution, self.best_cost, scores, nfe, self.seed
return self.best_solution, self.best_cost, scores, nfe, self.seed


def run(self,domain,fitness_function,seed):
scores = []
nfe = 0
if len(self.init) > 0:
solution = self.init
else:
solution = [self.r_init.randint(self.domain[i][0], self.domain[i][1])
for i in range(len(self.domain))]

self.start_time=time.time()
for i in range(self.epochs):
if i != 0:
solution = [random.randint(self.domain[i][0], self.domain[i][1])
for i in range(len(self.domain))]
if not self.fitness_function.__name__ == 'fitness_function':
cost = self.fitness_function(solution)
else:
cost = self.fitness_function(solution, 'FCO')
nfe += 1
if cost < self.best_cost:
self.best_cost = cost
self.best_solution = solution
scores.append(self.best_cost)
if time.time()-self.start_time>self.max_time:
return self.best_solution, self.best_cost, scores, nfe, self.seed
return self.best_solution, self.best_cost, scores, nfe, self.seed

if __name__ == '__main__':
read_file('flights.txt')
rs=RandomSearch(domain=domain['domain'],fitness_function=fitness_function,seed=5,seed_init=False)
soln, cost, scores, nfe, seed=rs.run(max_time=0.008)
#plot_scores(scores,rs.get_name(),save_fig=False)
#print_schedule(soln,'FCO')
rs=RandomSearch(max_time=0.00001) #def run():
soln, cost, scores, nfe, seed=rs.run(domain=domain['domain'],fitness_function=fitness_function,seed=5)
plot_scores(scores,rs.get_name(),fname='flight_scheduling',save_fig=False)
#print_schedule(soln,'FCO')
""""
Add max time parameter in the function
2. Docstrings
3. Type hinting
4. Unit tests
5. Change all single_runs
6. Change all multiple runs
"""
20 changes: 9 additions & 11 deletions flight_algorithms/algorithms/sa.py
Expand Up @@ -2,7 +2,6 @@
import os
import time
sys.path.append(os.getcwd())
#sys.path.append("/mnt/d/MINOR PROJECT/final/")
from abc import ABCMeta
from utils.utils import plot_scores, print_schedule, read_file
from flight_algorithms.algorithms.base_algorithm import FlightAlgorithm
Expand All @@ -13,9 +12,9 @@
from fitness import *

class SimulatedAnnealing(FlightAlgorithm,metaclass=ABCMeta):
def __init__(self, domain, fitness_function, seed=random.randint(10, 100),
seed_init=True, init=[],temperature=50000.0, cooling=0.95, step=1) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init)
def __init__(self, domain=domain['domain'], fitness_function=fitness_function, seed=random.randint(10, 100),
seed_init=True,init=[],max_time=1000,temperature=50000.0, cooling=0.95, step=1) -> None:
super().__init__(domain, fitness_function, seed, seed_init, init,max_time)
self.best_solution=0.0
self.temperature=temperature
self.cooling=cooling
Expand All @@ -28,8 +27,7 @@ def get_base(self) -> str:
def get_name(self) -> str:
return self.__class__.__name__

def run(self,**kwargs) -> tuple:
max_time=kwargs.get('max_time',1000)
def run(self,domain,fitness_function,seed) -> tuple:
count = 0
nfe = 0
scores = []
Expand Down Expand Up @@ -76,7 +74,7 @@ def run(self,**kwargs) -> tuple:
self.temp.append(self.temperature)
self.temperature = self.temperature * self.cooling

if time.time()-self.start_time>max_time:
if time.time()-self.start_time>self.max_time:
return solution, best_cost, scores, nfe, self.seed

print('Count: ', count)
Expand All @@ -86,7 +84,7 @@ def run(self,**kwargs) -> tuple:

if __name__ == '__main__':
read_file('flights.txt')
sa=SimulatedAnnealing(domain=domain['griewank']*5,fitness_function=griewank,seed=5,seed_init=False)
soln, cost, scores, nfe, seed=sa.run(max_time=0.0003)
plot_scores(scores,sa.get_name(),save_fig=False,temp=sa.temp)
#print_schedule(soln,'FCO')
sa=SimulatedAnnealing(max_time=0.0003,temperature=50000.0,seed_init=False)
soln, cost, scores, nfe, seed=sa.run(domain=domain['griewank']*5,fitness_function=griewank,seed=5)
plot_scores(scores,sa.get_name(),fname='griewank',save_fig=False,temp=sa.temp)
print_schedule(soln,'FCO')

0 comments on commit 8cc840e

Please sign in to comment.