-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_co_viz.py
More file actions
187 lines (149 loc) · 7 KB
/
simple_co_viz.py
File metadata and controls
187 lines (149 loc) · 7 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import json
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
def load_co_results():
"""Load both ACO and BCO results."""
results = {}
# Load BCO results
bco_file = Path("results_CO/bco_results/comprehensive_results.json")
if bco_file.exists():
with open(bco_file, 'r') as f:
results["BCO"] = json.load(f)
print("BCO results loaded successfully")
# Load ACO results
aco_file = Path("results_CO/aco_results/comprehensive_results.json")
if aco_file.exists():
with open(aco_file, 'r') as f:
results["ACO"] = json.load(f)
print("ACO results loaded successfully")
return results
def create_comparison_table(results):
"""Create a comparison table for research."""
table_data = []
for algo, data in results.items():
hard = data["results"]["hard_constraints"]
soft = data["results"]["soft_constraints"]
table_row = {
"Algorithm": algo,
"Hard Violations": hard["total_violations"],
"Primary Violation Types": f"{hard['total_violations']} ({hard['lecturer_conflicts']}), ({hard['room_capacity_violations']}), ({hard['student_group_conflicts']})",
"Soft Constraint Score": f"{soft['overall_score']:.3f}",
"Convergence Speed": data["results"]["convergence_speed"],
"Final Fitness": f"{data['results']['final_fitness']:.2f}",
"Unassigned Activities": hard["unassigned_activities"]
}
table_data.append(table_row)
df = pd.DataFrame(table_data)
# Save to CSV
df.to_csv("results_CO/research_tables/co_comparison.csv", index=False)
# Print formatted table
print("\n" + "="*80)
print("CO ALGORITHMS RESEARCH COMPARISON TABLE")
print("="*80)
print(df.to_string(index=False))
print("="*80)
return df
def create_convergence_plot(results):
"""Create convergence comparison plot."""
plt.figure(figsize=(12, 8))
# Plot 1: Best fitness convergence
plt.subplot(2, 2, 1)
colors = {"ACO": "blue", "BCO": "green"}
for algo, data in results.items():
if "best_fitness_history" in data["results"]:
history = data["results"]["best_fitness_history"]
plt.plot(range(1, len(history) + 1), history,
color=colors[algo], linewidth=2, label=f"{algo}")
plt.xlabel("Iteration")
plt.ylabel("Best Fitness")
plt.title("Convergence Comparison")
plt.legend()
plt.grid(True, alpha=0.3)
# Plot 2: Constraint violations comparison
plt.subplot(2, 2, 2)
algorithms = list(results.keys())
hard_violations = [results[algo]["results"]["hard_constraints"]["total_violations"] for algo in algorithms]
bars = plt.bar(algorithms, hard_violations, color=[colors[algo] for algo in algorithms], alpha=0.7)
for i, bar in enumerate(bars):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.5,
f'{int(height)}', ha='center', va='bottom')
plt.ylabel("Hard Constraint Violations")
plt.title("Hard Constraint Violations")
plt.grid(True, alpha=0.3)
# Plot 3: Soft constraint scores
plt.subplot(2, 2, 3)
soft_scores = [results[algo]["results"]["soft_constraints"]["overall_score"] for algo in algorithms]
bars = plt.bar(algorithms, soft_scores, color=[colors[algo] for algo in algorithms], alpha=0.7)
for i, bar in enumerate(bars):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{height:.3f}', ha='center', va='bottom')
plt.ylabel("Soft Constraint Score")
plt.title("Soft Constraint Performance")
plt.ylim(0, 1)
plt.grid(True, alpha=0.3)
# Plot 4: Convergence speed
plt.subplot(2, 2, 4)
convergence_speeds = [results[algo]["results"]["convergence_speed"] for algo in algorithms]
bars = plt.bar(algorithms, convergence_speeds, color=[colors[algo] for algo in algorithms], alpha=0.7)
for i, bar in enumerate(bars):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.5,
f'{int(height)}', ha='center', va='bottom')
plt.ylabel("Convergence Speed (Iterations)")
plt.title("Convergence Speed Comparison")
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("results_CO/comparison_charts/co_comprehensive_comparison.png", dpi=300, bbox_inches='tight')
plt.close()
print("Comprehensive comparison chart saved")
def create_detailed_breakdown(results):
"""Create detailed performance breakdown."""
for algo, data in results.items():
print(f"\n{algo} DETAILED RESULTS:")
print("-" * 30)
hard = data["results"]["hard_constraints"]
soft = data["results"]["soft_constraints"]
print(f"Hard Constraints:")
print(f" • Total Violations: {hard['total_violations']}")
print(f" • Vacant Rooms: {hard['vacant_rooms']}")
print(f" • Lecturer Conflicts: {hard['lecturer_conflicts']}")
print(f" • Room Capacity Violations: {hard['room_capacity_violations']}")
print(f" • Student Group Conflicts: {hard['student_group_conflicts']}")
print(f" • Unassigned Activities: {hard['unassigned_activities']}")
print(f"\nSoft Constraints:")
components = soft["components"]
print(f" • Student Fatigue: {components['student_fatigue']:.3f}")
print(f" • Student Idle Time: {components['student_idle']:.3f}")
print(f" • Student Lecture Spread: {components['student_spread']:.3f}")
print(f" • Lecturer Fatigue: {components['lecturer_fatigue']:.3f}")
print(f" • Lecturer Idle Time: {components['lecturer_idle']:.3f}")
print(f" • Lecturer Lecture Spread: {components['lecturer_spread']:.3f}")
print(f" • Lecturer Workload Balance: {components['lecturer_balance']:.3f}")
print(f" • Overall Score: {soft['overall_score']:.3f}")
print(f"\nPerformance:")
print(f" • Final Fitness: {data['results']['final_fitness']:.2f}")
print(f" • Convergence Speed: {data['results']['convergence_speed']} iterations")
params = data["parameters"]
print(f"\nParameters:")
for key, value in params.items():
print(f" • {key}: {value}")
def main():
print("Starting CO algorithms analysis...")
# Ensure directories exist
Path("results_CO/research_tables").mkdir(parents=True, exist_ok=True)
Path("results_CO/comparison_charts").mkdir(parents=True, exist_ok=True)
# Load results
results = load_co_results()
if not results:
print("No results found!")
return
# Generate outputs
create_comparison_table(results)
create_convergence_plot(results)
create_detailed_breakdown(results)
print("\nCO algorithms analysis completed!")
if __name__ == "__main__":
main()