def costFunction(funcName, dim, x): """""" try: if dim > 1000: dim = 1000 if funcName == "Shifted Sphere": return Shifted_Sphere(dim, x) elif funcName == "Shifted Schwefel": return Schwefel_Problem(dim, x) elif funcName == "Shifted Rosenbrock": return Shifted_Rosenbrock(dim, x) elif funcName == "Shifted Rastrigin": return Shifted_Rastrigin(dim, x) elif funcName == "Shifted Griewank": return Shifted_Griewank(dim, x) elif funcName == "Shifted Ackley": return Shifted_Ackley(dim, x) else: print("Error : Function number out of range\n") exit() except: EH()
def plotPSO(Evaluation, funcName, fitness): try: #print(len(iterations)) plt.figure(figsize=(10, 5)) plt.grid('on') plt.rc('axes', axisbelow=True) plt.plot(Evaluation, "r-", label=funcName, lw=2) plt.xlabel("Iterations") plt.ylabel("Cost") plt.title('PSO - ' + funcName) #plt.annotate('local max', xy=(index, fitness_gbp_Position),arrowprops=dict(facecolor='black', shrink=0.05)) best = [i for i, ev in enumerate(Evaluation) if ev == fitness] for i in best: plt.scatter(i, fitness, 50, marker='o', facecolors='c', edgecolors='k', linewidths=1) plt.legend() plt.show() except: EH()
def install_required_Packages(): """ Install the required PACKAGES :return: Nothing """ try: # List all the required packages required_packages = [ 'matplotlib', 'numpy', ] # Check and retrieve the installed packages info installed = subprocess.check_output( [sys.executable, '-m', 'pip', 'freeze']) # Split and strip the returned info to get the # installed packages names list installed_packages = [ r.decode().split('==')[0] for r in installed.split() ] # Loop over the required packages for package in required_packages: # If the package is not in the installed packages if package not in installed_packages: # print informative message print(marks) print("Installing {}! Please wait ...") print(marks) # Send a check call and install the package subprocess.check_call( [sys.executable, "-m", "pip", "install", package]) except: EH()
def evaluations(funcName, bounds, Dimension): """ Evaluation Function :param funcName: string :param bounds: list :param Dimension: int :return: None """ try: # number of particles - Swarm Size particles = 100 # Max number of iterations - Stopping Tolerance iterations = 500 # for minimization problem # _initialFitness = float("inf") """ w (Inertia Weight): is used to control the velocity: The acceleration coefficients: c1 (cognitive) and c2 (social) c1 (cognitive): expresses how much confidence a particle has in itself: c2 (social): expresses how much confidence a particle has in its neighbors """ options = {'w': 0.85, 'c1': 1.0, 'c2': 1.5} print("\n Starting SPO ...") totalExecutionTime = 0 solutions = [] for i in range(1, 26): start = dt.datetime.now() pso = runPSO(funcName, bounds, Dimension, particles, iterations, options) pso.run() solutions.append(pso) end = dt.datetime.now() totalExecutionTime += (end - start).seconds # Sort the resulted array: sortedList = sorted(solutions, key=lambda PSO: PSO.fitness) # Rotate through the results and choose the best one: print("\n-- Resulted Fitness:") for i, s in enumerate(sortedList): print(f"PSO {i + 1}, best fitness is {s.fitness}") print() bestPSO = sortedList[0] print("Best Solution: \n", bestPSO) print( f'Total Execution Time in seconds (repetitions: 25): {totalExecutionTime}' ) # Plot evaluation plotPSO(bestPSO.Evaluation, funcName, bestPSO.fitness) except: EH()
def Shifted_Rastrigin(dim, x): """""" try: F = 0 for i in range(dim): z = x[i] - rastrigin[i] F = F + (math.pow(z, 2) - 10 * np.cos(2 * np.pi * z) + 10) return F + f_bias[3] except: EH()
def Shifted_Sphere(dim, x): """""" try: F = 0 # objective function #print(len(sphere)) for i in range(dim): F += math.pow(x[i] - sphere[i], 2) #print(F + f_bias[0]) return F + f_bias[0] except: EH()
def Schwefel_Problem(dim, x): """""" try: F = np.abs(x[0]) for i in range(1, dim): z = x[i] - schwefel[i] F = max(F, np.abs(z)) return F + f_bias[1] except: EH()
def repeatSA(repetition, Nodes): """""" try: print("Starting Annealing ...") _results = [] _totalExecutionTime = 0 # repeat Annealing few times and store the result: for i in range(1, repetition): start = dt.datetime.now() s = runAnnealing(Nodes) s.run() _results.append(s) end = dt.datetime.now() _totalExecutionTime += (end - start).seconds print( f'Total Execution Time in seconds (repetitions: 25): {_totalExecutionTime}' ) # Sort the resulted array: sortedList = sorted(_results, key=lambda sa: sa.bestFitness) # Rotate through the results and choose the best one: print("\n-- Resulted Fitness:") for i, s in enumerate(sortedList): print( f"Simulated Annealing {i+1}, best fitness is {s.bestFitness}") # Print the best fitness details print() bestAnnealing = sortedList[0] print("Best Solution: \n", bestAnnealing) # List of City Coordinates: _points = bestAnnealing.coordinates #print(f"City Coordinates :\n {_points}") # List of Best Solution Path: _solution = bestAnnealing.solutions #print(f"Best Solution:\n {_solution}") # List of Best Fitted Distances: _fitness = bestAnnealing.fitnessList #print(f"Best Fitness:\n {_fitness}") initFit, bestFit = bestAnnealing.greedyFitness, bestAnnealing.bestFitness return _solution, _points, _fitness, initFit, bestFit except: EH()
def runAnnealing(Nodes): try: # Run Annealing: s = sa(Nodes, initialTemperature=1e2, stoppingTemperature=1e-3, alpha=0.99999, stoppingIteration=500000) #s.run() return s except: EH()
def Shifted_Griewank(dim, x): """""" try: F1 = 0 F2 = 1 for i in range(dim): z = x[i] - griewank[i] F1 += (math.pow(z, 2) / 4000) F2 *= (np.cos(z / np.sqrt(i + 1))) F = F1 - F2 + 1 + f_bias[4] return F except: EH()
def Shifted_Rosenbrock(dim, x): """""" try: z = [] F = 0 for i in range(dim): z.append(x[i] - rosenbrock[i] + 1) for i in range(dim - 1): F = F + 100 *(math.pow( (math.pow(z[i], 2) - z[i + 1]), 2)) \ + math.pow((z[i] - 1), 2) return F + f_bias[2] except: EH()
def Shifted_Ackley(dim, x): """""" try: Sum1 = 0 Sum2 = 0 for i in range(dim): z = x[i] - ackley[i] Sum1 += math.pow(z, 2) Sum2 += np.cos(2 * np.pi * z) F = -20 * np.exp(-0.2 * np.sqrt(Sum1 / dim)) \ - np.exp(Sum2 / dim) + 20 + np.e + f_bias[5] return F except: EH()
def runPSO(funcName, bounds, Dimension, particles, iterations, options): """ Run PSO Function :param funcName: string :param bounds: list :param Dimension: int :param particles: int :param iterations: int :param options: dict :return: obj """ try: # Total execution time s = PSO(funcName, bounds, particles, iterations, Dimension, options) return s except: EH()
def values(fileName): """ Values :param fileName: string :return: list[float] """ try: _value = [] with open(fileName, "r") as f: for line in f: stripped_line = line.split(",") for it in stripped_line: if it != '\n': _value.append(float(it)) #print(len(_value)) return _value except: EH()
def coordinates(fileName): """ Coordinates :param fileName: string :return: list[int, float, float] """ try: city, latitude, longitude = [], [], [] with open(fileName, "r") as f: for line in f.readlines(): line = [float(x.strip()) for x in line.split(" ")] city.append(int(line[0])) latitude.append(float(line[1])) longitude.append(float(line[2])) cities = np.column_stack((city, latitude, longitude)) return cities except: EH()
def main(): """ """ try: print() print("1. Djibouti - 38 Cities.") print("2. Qatar - 194 Cities.\n") choice = int(input("Your choice? ")) """ Traveling salesman problem: is, given a set of cities, to find the shortest path to visit all of the cities exactly once. """ parser = argparse.ArgumentParser(description="Metaheuristics") fileList = ["data/dj38_tsp.txt", "data/qa194_tsp.txt"] regList = ["SA", "GA"] parser.add_argument("--filename", choices=fileList, default=fileList[choice - 1], help='A string represents a dataset') args = parser.parse_args() # load and read data ---------------------------------------------------- print("..." * 15) _Nodes = coordinates(args.filename) solutionObj, coordinatesObj, _fitnessObj, initFit, bestFit = repeatSA( 6, _Nodes) # Visualize if choice == 1: animateTSP("Djibouti", solutionObj, coordinatesObj) plotLearning(_fitnessObj, initFit, bestFit) else: animateTSP("Qatar", solutionObj, coordinatesObj) plotLearning(_fitnessObj, initFit, bestFit) except: EH()
def plotLearning(fitnessList, initFit, bestFit): """ :param fitnessList: list[float] :param initFit: float :param bestFit: float :return: None """ try: plt.figure(figsize=(10, 5)) plt.grid('on') plt.rc('axes', axisbelow=True) plt.plot([i for i in range(len(fitnessList))], fitnessList) line_init = plt.axhline(y=initFit, color='r', linestyle='--') line_min = plt.axhline(y=bestFit, color='g', linestyle='--') plt.legend([line_init, line_min], ['Greedy Initial Fitness', 'Optimized Annealing Fitness']) plt.ylabel('Distance') plt.xlabel('Iteration') plt.show() except: EH()
def main(): """ Main Function :return: None """ try: while True: func_name, bounds = None, None flag = None D_range = [2, 50, 500] print( "\n Choose a dimension from the following list: [2, 50, 500]") print("\t or press any other KEY to EXIT .....") Dimension = int(input("\n Enter a dimension --> ")) if Dimension in D_range: flag = True if flag: print(f"\n 1: Shifted Sphere" f"\n 2: Shifted Schwefel" f"\n 3: Shifted Rosenbrock" f"\n 4: Shifted Rastrigin" f"\n 5: Shifted Griewank" f"\n 6: Shifted Ackley" f"\n ... Press any key to EXIT") choice = int(input("\n Enter a choice? ")) if choice == 1: func_name = "Shifted Sphere" bounds = [(-100, 100) for i in range(Dimension)] elif choice == 2: func_name = "Shifted Schwefel" bounds = [(-100, 100) for i in range(Dimension)] elif choice == 3: func_name = "Shifted Rosenbrock" bounds = [(-100, 100) for i in range(Dimension)] elif choice == 4: func_name = "Shifted Rastrigin" bounds = [(-5, 5) for i in range(Dimension)] elif choice == 5: func_name = "Shifted Griewank" bounds = [(-600, 600) for i in range(Dimension)] elif choice == 6: func_name = "Shifted Ackley" bounds = [(-32, 32) for i in range(Dimension)] else: print("\n--------------------") print( "The program interrupted ... function not found!") print("--------------------\n") flag = False break if flag: evaluations(func_name, bounds, Dimension) else: print( "\n----------------------------------------------------------" ) print( "Required dimension is not in the list [2, 50, 100, 500]!") print( "----------------------------------------------------------\n" ) break except: EH()
def animateTSP(country, history, points): """ :param country: string :param history: list[int, float, float] :param points: list[int, float, float] :return: """ try: # Prepare the coordinates for plotting the trip cityName = [] latitude = [] longitude = [] for city in points: cityName.append(city[0]) latitude.append(city[1] / 1000.) longitude.append(city[2] / 1000.) cityName.append(cityName[0]) latitude.append(latitude[0]) longitude.append(longitude[0]) plt.figure(figsize=(7, 7)) # Specify tripMap width and height if country == "Djibouti": tripMap = Basemap(width=350000, height=270000, resolution='i', projection='tmerc', lat_0=11.572076, lon_0=43.145645) else: tripMap = Basemap(width=250000, height=250000, resolution='i', projection='tmerc', lat_0=25.286106, lon_0=51.534817) tripMap.drawmapboundary(fill_color='aqua') tripMap.fillcontinents(color='#FFE4B5', lake_color='aqua') tripMap.drawcoastlines() tripMap.drawcountries() # Range the frames _frames = len(history) // 1500 _frameRange = range(0, len(history), _frames) # Path is represented as line line = tripMap.plot([], [], 'D-', markersize=3, linewidth=1, color='r')[0] # initial function def init_func(): # Draw node dots on graph x = [longitude[i] for i in history[0]] y = [latitude[i] for i in history[0]] x, y = tripMap(x, y) tripMap.plot(x, y, 'bo', markersize=3) # Empty initialization line.set_data([], []) return line, # animate function def gen_function(frame): # Update the graph for each frame x = [longitude[i] for i in history[frame] + [history[frame][0]]] y = [latitude[i] for i in history[frame] + [history[frame][0]]] x, y = tripMap(x, y) line.set_data(x, y) return line # Animate the graph _animation = FuncAnimation(plt.gcf(), func=gen_function, frames=_frameRange, init_func=init_func, interval=10, repeat=False) plt.show() except: EH()
print("..." * 15) _Nodes = coordinates(args.filename) solutionObj, coordinatesObj, _fitnessObj, initFit, bestFit = repeatSA( 6, _Nodes) # Visualize if choice == 1: animateTSP("Djibouti", solutionObj, coordinatesObj) plotLearning(_fitnessObj, initFit, bestFit) else: animateTSP("Qatar", solutionObj, coordinatesObj) plotLearning(_fitnessObj, initFit, bestFit) except: EH() if __name__ == "__main__": try: # Install Required packages install_required_Packages() # load Packages import argparse import datetime as dt import numpy as np main() except: EH()