-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_KSP.py
More file actions
68 lines (59 loc) · 1.96 KB
/
main_KSP.py
File metadata and controls
68 lines (59 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from Problems.knapsack import KSP
from Encode.binaryCodeGraph import BinaryCodeG
from Metaheuristics.local_search import LocalSearch
from Metaheuristics.simulated_anneling import SimmulatedAnneling
from Metaheuristics.genetic_algorithm import GeneticAlgorithm
from Metaheuristics.PBIL import PopulationBaseIncrementalLearning
from Metaheuristics.tabu_search import TabuSearch
from Metaheuristics.iterated_local_search import IteratedLocalSearch
import matplotlib.pyplot as plt
import numpy as np
size = 2000
problem = KSP(size)
#solver = LocalSearch(problem)
#solver = SimmulatedAnneling(problem)
#solver = IteratedLocalSearch(problem, criterion='LSMC')
#solver = TabuSearch(problem)
solver = GeneticAlgorithm(problem, encode=BinaryCodeG(size))
#solver = PopulationBaseIncrementalLearning(problem, encode=BinaryCodeG(size))
x, w, v, t = problem.get_incremental()
solution, iterations = solver(max_iter=200)
iterations = [problem(i, real=True) for i in iterations]
iter = np.arange(len(iterations))
plt.figure(figsize=(12,9))
plt.subplot(2,2,1)
plt.plot(v, label='value')
plt.plot(w, label='weight')
plt.plot(np.ones(len(w)) * t, label='max')
plt.ylabel("Value/weight")
plt.title('KSP problem')
plt.legend()
plt.subplot(2,2,2)
plt.title('Fitness')
plt.plot(iter, iterations, '-o', label='Solutions')
plt.ylabel('Fitness')
plt.xlabel('Iteration')
plt.subplot(2,2,3)
plt.title('Solution vs Max')
plt.bar(["Value", "Weight"],
[problem(problem.x, real=True),
problem.total],
label='Max')
plt.bar(["Value", "Weight"],
[0, t],
label='Max capability')
plt.bar(["Value", "Weight"],
[problem(solution, real=True),
np.sum(problem.w[solution])],
label='Solution')
plt.legend()
plt.subplot(2,2,4)
plt.scatter(problem.v, problem.w, label='all')
v = [problem.v[i] for i in solution]
w = [problem.w[i] for i in solution]
plt.scatter(v, w, label='solution')
plt.title('Problem space')
plt.xlabel('Value')
plt.ylabel('Weight')
plt.legend()
plt.show()