Repository navigation
Expand file tree
/
Copy pathtrain_rl.py
More file actions
1875 lines (1617 loc) · 81.6 KB
/
Copy pathtrain_rl.py
File metadata and controls
1875 lines (1617 loc) · 81.6 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# train_rl.py - Simplified to focus on phased training
import os
import logging
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from tqdm import tqdm
from typing import Dict, List, Tuple
from training.core.episode import run_test_episode
import json
import shutil
from environment.environment import RestaurantMealDeliveryEnv
from training.config.solver_config import SOLVERS
from training.config.env_config import get_env_config
from scipy import stats
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
def train_rl_aca(
phases: List[Dict],
save_interval: int = 100,
stability_window: int = 10, # Window for stability assessment
stability_threshold: float = 3.0, # Max percent change considered stable
seed: int = 1,
visualize: bool = False,
reposition_idle_vehicles: bool = False,
model_dir: str = "data/models",
resume_from_model: str = None, # Support resuming
start_phase: int = 0, # Phase to start from when resuming
start_episode: int = 0, # Episode to start from when resuming
exploration_start: float = 0.9, # Initial exploration rate
exploration_end: float = 0.25, # Final exploration rate
decay_method: str = "exponential", # "linear" or "exponential"
decay_rate: float = 0.999, # For exponential decay
# RL hyperparameters
rl_learning_rate: float = 0.0005,
rl_discount_factor: float = 0.95,
rl_batch_size: int = 64,
rl_target_update_frequency: int = 50,
rl_replay_buffer_capacity: int = 10000,
rl_bundling_reward: float = 0.05,
rl_postponement_penalty: float = 0.00,
rl_on_time_reward: float = 0.2,
):
"""
Train the RL-based ACA solver through multiple progressive phases.
"""
# Create model directory if it doesn't exist
os.makedirs(model_dir, exist_ok=True)
# Generate timestamp for this training run
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Create directory for phase-specific data
phase_dir = os.path.join(model_dir, f"phased_training_{timestamp}")
os.makedirs(phase_dir, exist_ok=True)
# Use a single latest model path that will be updated throughout training
latest_model_path = os.path.join(phase_dir, "rl_aca_latest.pt")
# Set initial model path if resuming
current_model_path = resume_from_model if resume_from_model else latest_model_path
# Save phase configurations for reference
with open(os.path.join(phase_dir, "phase_configs.json"), "w") as f:
json.dump(phases, f, indent=4)
# Initialize overall metrics
all_metrics = {
"phase_transitions": [],
"rewards": [],
"delays": [],
"on_time_rates": [],
"postponement_rates": [],
"losses": [], # Add a list to track average loss per episode
"exploration_rates": [], # Track exploration rate for each episode
}
# Initialize exploration rate at the start
current_exploration_rate = exploration_start
# Calculate total episodes across all phases
max_total_episodes = sum(phase.get("max_episodes", 100) for phase in phases)
# If resuming, attempt to load metrics from previous runs
if resume_from_model:
resume_dir = os.path.dirname(resume_from_model)
metrics_file = os.path.join(resume_dir, f"phased_metrics_{os.path.basename(resume_dir).split('_')[-1]}.npz")
if os.path.exists(metrics_file):
saved_metrics = np.load(metrics_file, allow_pickle=True)
all_metrics = {
"phase_transitions": saved_metrics["phase_transitions"].tolist(),
"rewards": saved_metrics["rewards"].tolist(),
"delays": saved_metrics["delays"].tolist(),
"on_time_rates": saved_metrics["on_time_rates"].tolist(),
"postponement_rates": saved_metrics["postponement_rates"].tolist(),
"losses": saved_metrics.get("losses", []).tolist(),
}
logger.info(f"Resuming training from phase {start_phase}, episode {start_episode}")
# Create the solver once before the episode loop to persist the replay buffer
speed = 8 # 8 km/h for 30-second intervals (was 16 km/h for 1-minute intervals)
street_network_factor = 1.0
movement_per_step = (speed / 60) / street_network_factor
# Create a temporary environment to get the location_manager
env_params = get_env_config(movement_per_step)
env_params.update({"seed": seed, "reposition_idle_vehicles": reposition_idle_vehicles, "visualize": visualize})
temp_env = RestaurantMealDeliveryEnv(**env_params)
solver = SOLVERS["rl_aca"](movement_per_step, temp_env.location_manager)
# Load the RL model if resuming
if current_model_path and os.path.exists(current_model_path):
solver.postponement.load_model(current_model_path)
logger.info(f"Loaded model from {current_model_path} for solver")
# Training loop through phases
current_phase_idx = start_phase
total_completed_episodes = 0 # For exploration rate
while current_phase_idx < len(phases):
current_phase = phases[current_phase_idx]
phase_name = current_phase.get("name", f"Phase {current_phase_idx + 1}")
logger.info(f"\n{'=' * 80}\nStarting phase {current_phase_idx + 1}/{len(phases)}: {phase_name}")
logger.info(f"Environment: {current_phase['env_config']}")
logger.info(f"Performance criteria: {current_phase['performance_criteria']}\n{'=' * 80}")
# Initialize phase-specific metrics
phase_metrics = {"rewards": [], "delays": [], "on_time_rates": [], "postponement_rates": []}
# Process episodes for the current phase
episode_in_phase = start_episode if current_phase_idx == start_phase else 0
phase_complete = False
min_episodes = current_phase.get("min_episodes", 20)
max_episodes = current_phase.get("max_episodes", 100)
# Create progress bar for this phase
total_possible = max_episodes - episode_in_phase
with tqdm(total=total_possible, desc=f"Phase {current_phase_idx + 1}/{len(phases)}: {phase_name}") as pbar:
while not phase_complete:
# Pass phase-specific environment parameters
env_config = current_phase["env_config"]
# Log current model status
if episode_in_phase == 0:
logger.info(f"Starting phase with model: {current_model_path}")
else:
logger.info(f"Using model: {latest_model_path}")
# Phase-specific exploration rate management for curriculum learning
# Reset exploration rate at the start of each new phase
if episode_in_phase == 0:
current_exploration_rate = exploration_start # Reset to initial rate (0.9)
logger.info(
f"Phase {current_phase_idx + 1} started - Reset exploration rate to {current_exploration_rate:.3f}"
)
else:
# Phase-specific decay rates: slower for simple phases, faster for complex phases
phase_decay_rates = {
0: 0.999, # Phase 1: Simple (1 vehicle, 2 restaurants) - very slow decay
1: 0.999, # Phase 2: Intermediate (10 vehicles, 20 restaurants) - slow decay
2: 0.95, # Phase 3: Bridge (40 vehicles, 80 restaurants) - fast decay
3: 0.95, # Phase 4: Full (160 vehicles, 320 restaurants) - fast decay
}
current_decay_rate = phase_decay_rates.get(current_phase_idx, decay_rate)
# Update exploration rate based on selected decay method (within each phase)
if decay_method == "linear":
phase_progress = episode_in_phase / max_episodes
current_exploration_rate = max(
exploration_end, exploration_start - (exploration_start - exploration_end) * phase_progress
)
elif decay_method == "exponential":
current_exploration_rate = max(exploration_end, current_exploration_rate * current_decay_rate)
# Run test episode - always save to the same latest model path, using the same solver
stats = run_test_episode(
solver_name="rl_aca",
solver=solver, # Pass the same solver instance to persist the replay buffer
seed=seed + episode_in_phase, # Increment seed by episode only
reposition_idle_vehicles=reposition_idle_vehicles,
visualize=visualize and episode_in_phase % 20 == 0,
save_rl_model=True,
rl_model_path=latest_model_path, # Always use the latest model path
save_results_to_disk=False,
env_config=env_config,
exploration_rate=current_exploration_rate,
training_mode=True, # Explicitly set to True for training
# Pass RL hyperparameters
rl_learning_rate=rl_learning_rate,
rl_discount_factor=rl_discount_factor,
rl_exploration_rate=exploration_start, # Use the same exploration rate
rl_min_exploration_rate=exploration_end, # Use the same end rate
rl_batch_size=rl_batch_size,
rl_target_update_frequency=rl_target_update_frequency,
rl_replay_buffer_capacity=rl_replay_buffer_capacity,
rl_bundling_reward=rl_bundling_reward,
rl_postponement_penalty=rl_postponement_penalty,
rl_on_time_reward=rl_on_time_reward,
)
print(f"Seed: {seed + episode_in_phase}")
# Update metrics
reward = stats["total_reward"]
delay = sum(stats["delay_values"]) if stats["delay_values"] else 0
total_orders = max(1, stats["orders_delivered"])
late_orders = len(stats["late_orders"])
on_time_rate = ((total_orders - late_orders) / total_orders) * 100
postponement_rate = len(stats["postponed_orders"]) / max(1, stats["total_orders"]) * 100
# Update phase metrics
phase_metrics["rewards"].append(reward)
phase_metrics["delays"].append(delay)
phase_metrics["on_time_rates"].append(on_time_rate)
phase_metrics["postponement_rates"].append(postponement_rate)
# Update overall metrics
all_metrics["rewards"].append(reward)
all_metrics["delays"].append(delay)
all_metrics["on_time_rates"].append(on_time_rate)
all_metrics["postponement_rates"].append(postponement_rate)
all_metrics["exploration_rates"].append(current_exploration_rate)
# Extract the average loss for this episode and append to all_metrics["losses"]
try:
# Use the existing solver instance instead of creating a new one
episode_losses = solver.postponement.batch_losses # Get the losses for this episode
if episode_losses: # Check if there are any losses
avg_episode_loss = sum(episode_losses) / len(episode_losses)
all_metrics["losses"].append(avg_episode_loss) # Store the average loss for this episode
logger.debug(f"Average loss for episode {episode_in_phase + 1}: {avg_episode_loss:.8f}")
else:
all_metrics["losses"].append(0.0) # If no losses, append 0
logger.debug(f"No losses recorded for episode {episode_in_phase + 1}")
# Clear batch_losses to prevent memory buildup
solver.postponement.batch_losses = []
except Exception as e:
logger.warning(f"Failed to extract losses: {e}")
all_metrics["losses"].append(0.0) # Fallback in case of error
# Plot losses and exploration vs performance at save intervals
if (episode_in_phase + 1) % save_interval == 0:
loss_plot_path = os.path.join(phase_dir, "loss_plot.png") # Single file, overwritten
plot_losses(
losses=all_metrics["losses"],
save_path=loss_plot_path,
window_size=20,
phase_idx=current_phase_idx + 1,
episode_idx=episode_in_phase + 1,
total_steps=len(all_metrics["losses"]), # Now represents the number of episodes
)
logger.info(f"Updated loss plot at {loss_plot_path}")
# Plot exploration vs performance
exploration_plot_path = os.path.join(phase_dir, "exploration_vs_performance.png")
plot_exploration_vs_performance(
all_metrics,
phases,
save_path=exploration_plot_path,
current_phase=current_phase_idx,
current_episode=len(all_metrics["rewards"]),
)
logger.info(f"Updated exploration vs performance plot at {exploration_plot_path}")
# Calculate enhanced metrics for progress bar
capacity_utilization = (
(stats["total_orders"] / max(1, current_phase["env_config"]["num_vehicles"]))
if current_phase
else 0
)
undelivered_orders = stats["total_orders"] - stats["orders_delivered"]
completion_rate = (stats["orders_delivered"] / max(1, stats["total_orders"])) * 100
# Calculate average episode performance over last 10 episodes for trend
recent_rewards = phase_metrics["rewards"][-min(10, len(phase_metrics["rewards"])) :]
avg_recent_reward = sum(recent_rewards) / len(recent_rewards) if recent_rewards else reward
reward_trend = (
"↗"
if len(recent_rewards) >= 2 and recent_rewards[-1] > recent_rewards[0]
else "↘" if len(recent_rewards) >= 2 and recent_rewards[-1] < recent_rewards[0] else "→"
)
pbar.set_postfix(
{
"rew": f"{reward:.0f}".ljust(5), # Current episode reward
"avg": f"{avg_recent_reward:.0f}{reward_trend}".ljust(6), # Average recent reward with trend
"ot": f"{on_time_rate:.0f}%".ljust(4), # On-time rate
"comp": f"{completion_rate:.0f}%".ljust(4), # Completion rate (delivered/total)
"undel": f"{undelivered_orders}".ljust(4), # Undelivered orders
"post": f"{postponement_rate:.0f}%".ljust(4), # Postponement rate
"cap": f"{capacity_utilization:.1f}".ljust(4), # Orders per vehicle (capacity utilization)
"exp": f"{current_exploration_rate:.2f}".ljust(5), # Exploration rate
"loss": (
f"{all_metrics['losses'][-1]:.3f}" if all_metrics["losses"] else "0.000".ljust(6)
), # Latest loss
}
)
pbar.update(1)
# pbar.update(1)
# Save checkpoints at regular intervals
if (episode_in_phase + 1) % save_interval == 0:
# Create checkpoint name
checkpoint_path = os.path.join(
phase_dir, f"rl_aca_phase{current_phase_idx+1}_ep{episode_in_phase+1}.pt"
)
# Create resuming info
resume_info = {
"phase": current_phase_idx,
"episode": episode_in_phase + 1,
"timestamp": timestamp,
}
# Save resuming info
with open(os.path.join(phase_dir, "resuming_info.json"), "w") as f:
json.dump(resume_info, f)
# Copy latest model to checkpoint
if os.path.exists(latest_model_path):
try:
shutil.copy(latest_model_path, checkpoint_path)
logger.info(f"Saved checkpoint to {checkpoint_path}")
except Exception as e:
logger.error(f"Failed to save checkpoint: {e}")
else:
logger.warning(f"Could not save checkpoint: Model file {latest_model_path} does not exist")
# Save metrics
metrics_file = os.path.join(phase_dir, f"phased_metrics_{timestamp}.npz")
np.savez(
metrics_file,
phase_transitions=np.array(all_metrics["phase_transitions"]),
rewards=np.array(all_metrics["rewards"]),
delays=np.array(all_metrics["delays"]),
on_time_rates=np.array(all_metrics["on_time_rates"]),
postponement_rates=np.array(all_metrics["postponement_rates"]),
)
# Check if phase completion criteria are met
criteria_met, reason = check_phase_criteria(
phase_metrics=phase_metrics,
episode_count=episode_in_phase + 1,
min_episodes=min_episodes,
max_episodes=max_episodes,
stability_window=stability_window,
stability_threshold=stability_threshold,
performance_criteria=current_phase["performance_criteria"],
)
# Check if phase is complete
if criteria_met or episode_in_phase >= max_episodes:
phase_complete = True
# Save phase transition point
all_metrics["phase_transitions"].append(len(all_metrics["rewards"]) - 1)
# Save phase final model
phase_final_path = os.path.join(phase_dir, f"rl_aca_phase{current_phase_idx+1}_final.pt")
try:
# Save the model state directly instead of copying the file
solver.postponement.save_model(phase_final_path)
logger.info(f"Phase {current_phase_idx + 1} final model saved to {phase_final_path}")
except Exception as e:
logger.error(f"Failed to create final model: {e}")
# Generate comprehensive phase summary report
generate_phase_summary_report(
phase_metrics,
current_phase_idx,
phase_name,
episode_in_phase + 1,
current_phase["env_config"],
current_exploration_rate,
all_metrics,
)
# Plot phase results
plot_phase_results(phase_metrics, current_phase_idx, phase_name, phase_dir, timestamp)
# Log completion message
if criteria_met:
logger.info(f"Phase {current_phase_idx + 1} completed after {episode_in_phase + 1} episodes")
logger.info(f"Reason: {reason}")
# Increment episode counter
episode_in_phase += 1
total_completed_episodes += 1 # Increment total completed episodes
# Move to next phase
current_phase_idx += 1
start_episode = 0 # Reset episode counter for next phase
# Training complete - plot overall results
plot_training_results(all_metrics, phases, phase_dir, timestamp)
# Get path to final model
final_model_path = os.path.join(phase_dir, f"rl_aca_phase{len(phases)}_final.pt")
logger.info(f"Phased training completed. Final model saved to {final_model_path}")
return final_model_path
def check_phase_criteria(
phase_metrics: Dict,
episode_count: int,
min_episodes: int,
max_episodes: int,
stability_window: int,
stability_threshold: float,
performance_criteria: Dict,
) -> Tuple[bool, str]:
"""
Check if the performance criteria for the current phase have been met.
Args:
phase_metrics: Dictionary of metrics for the current phase
episode_count: Number of episodes run in this phase
min_episodes: Minimum episodes required before advancement
max_episodes: Maximum episodes before forced advancement
stability_window: Number of recent episodes to check for stability
stability_threshold: Maximum percentage change in reward
performance_criteria: Dictionary of criteria to meet
Returns:
Tuple of (criteria_met, reason)
"""
# Ensure minimum episodes have been run
if episode_count < min_episodes:
return False, f"Minimum episodes not reached ({episode_count}/{min_episodes})"
# Get metrics from recent episodes
if len(phase_metrics["rewards"]) < stability_window:
return False, f"Not enough data for stability check ({len(phase_metrics['rewards'])}/{stability_window})"
recent_rewards = phase_metrics["rewards"][-stability_window:]
recent_delays = phase_metrics["delays"][-stability_window:]
recent_on_time = phase_metrics["on_time_rates"][-stability_window:]
# Check reward stability using max-min range
min_reward = min(recent_rewards)
max_reward = max(recent_rewards)
# For negative rewards (common in RL), we use absolute values to calculate percentage
if min_reward < 0 and max_reward < 0:
# Both rewards are negative, so use absolute values
min_abs = abs(min_reward)
max_abs = abs(max_reward)
# Since rewards are negative, min_reward has the larger absolute value
percent_range = (min_abs - max_abs) / min_abs * 100.0
elif min_reward >= 0 and max_reward >= 0:
# Both rewards are positive
if min_reward == 0:
percent_range = float("inf") if max_reward > 0 else 0.0
else:
percent_range = (max_reward - min_reward) / min_reward * 100.0
else:
# Rewards cross zero, which indicates high instability
percent_range = 100.0 # Just set to a high value
if percent_range > stability_threshold:
return False, f"Reward not stable: {percent_range:.2f}% range > {stability_threshold:.2f}% threshold"
# Check average reward criteria
if "min_avg_reward" in performance_criteria:
avg_reward = np.mean(recent_rewards)
if avg_reward < performance_criteria["min_avg_reward"]:
return False, f"Average reward too low: {avg_reward:.2f} < {performance_criteria['min_avg_reward']:.2f}"
# Check on-time delivery rate criteria
if "min_on_time_rate" in performance_criteria:
avg_on_time = np.mean(recent_on_time)
if avg_on_time < performance_criteria["min_on_time_rate"]:
return False, f"On-time rate too low: {avg_on_time:.2f}% < {performance_criteria['min_on_time_rate']:.2f}%"
# Check maximum average delay criteria
if "max_avg_delay" in performance_criteria:
avg_delay = np.mean(recent_delays)
if avg_delay > performance_criteria["max_avg_delay"]:
return False, f"Average delay too high: {avg_delay:.2f} > {performance_criteria['max_avg_delay']:.2f}"
# Force phase transition if max episodes reached
if episode_count >= max_episodes:
return True, f"Maximum episodes reached ({max_episodes})"
# All criteria met
return True, "All criteria met"
def plot_phase_results(metrics, phase_idx, phase_name, output_dir, timestamp):
"""Plot results for a single training phase with trend lines."""
plt.figure(figsize=(15, 10))
# Number of episodes for x-axis
episodes = np.arange(len(metrics["rewards"]))
# Plot rewards
plt.subplot(2, 2, 1)
plt.plot(episodes, metrics["rewards"], label="Rewards")
# Add trend line
z = np.polyfit(episodes, metrics["rewards"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title(f"Phase {phase_idx + 1}: {phase_name} - Rewards")
plt.xlabel("Episode")
plt.ylabel("Total Reward")
plt.legend()
# Plot delays
plt.subplot(2, 2, 2)
plt.plot(episodes, metrics["delays"], label="Delays")
# Add trend line
z = np.polyfit(episodes, metrics["delays"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title(f"Phase {phase_idx + 1}: {phase_name} - Delays")
plt.xlabel("Episode")
plt.ylabel("Total Delay (minutes)")
plt.legend()
# Plot on-time rates
plt.subplot(2, 2, 3)
plt.plot(episodes, metrics["on_time_rates"], label="On-Time Rate")
# Add trend line
z = np.polyfit(episodes, metrics["on_time_rates"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title(f"Phase {phase_idx + 1}: {phase_name} - On-Time Rate")
plt.xlabel("Episode")
plt.ylabel("On-Time Rate (%)")
plt.ylim(0, 100)
plt.legend()
# Plot postponement rates
plt.subplot(2, 2, 4)
plt.plot(episodes, metrics["postponement_rates"], label="Postponement Rate")
# Add trend line
z = np.polyfit(episodes, metrics["postponement_rates"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title(f"Phase {phase_idx + 1}: {phase_name} - Postponement Rate")
plt.xlabel("Episode")
plt.ylabel("Postponement Rate (%)")
plt.ylim(0, 100)
plt.legend()
plt.tight_layout()
plt.savefig(os.path.join(output_dir, f"phase{phase_idx+1}_results_{timestamp}.png"), dpi=300)
plt.close()
def plot_training_results(metrics, phases, output_dir, timestamp):
"""Plot overall training results across all phases with trend lines."""
plt.figure(figsize=(15, 12))
# Number of episodes for x-axis
episodes = np.arange(len(metrics["rewards"]))
# Get phase transition points
phase_transitions = metrics["phase_transitions"]
# Plot rewards
plt.subplot(2, 2, 1)
plt.plot(episodes, metrics["rewards"], label="Rewards")
# Add trend line
z = np.polyfit(episodes, metrics["rewards"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title("Total Reward Across All Phases")
plt.xlabel("Total Episodes")
plt.ylabel("Reward")
for i, transition in enumerate(phase_transitions):
plt.axvline(x=transition, color="g", linestyle="--")
plt.text(
transition,
plt.ylim()[0] + (plt.ylim()[1] - plt.ylim()[0]) * 0.1,
f"P{i+1}→P{i+2}",
rotation=90,
verticalalignment="bottom",
)
plt.legend()
# Plot delays
plt.subplot(2, 2, 2)
plt.plot(episodes, metrics["delays"], label="Delays")
# Add trend line
z = np.polyfit(episodes, metrics["delays"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title("Total Delay Across All Phases")
plt.xlabel("Total Episodes")
plt.ylabel("Delay (minutes)")
for i, transition in enumerate(phase_transitions):
plt.axvline(x=transition, color="g", linestyle="--")
plt.text(
transition,
plt.ylim()[0] + (plt.ylim()[1] - plt.ylim()[0]) * 0.1,
f"P{i+1}→P{i+2}",
rotation=90,
verticalalignment="bottom",
)
plt.legend()
# Plot on-time rates
plt.subplot(2, 2, 3)
plt.plot(episodes, metrics["on_time_rates"], label="On-Time Rate")
# Add trend line
z = np.polyfit(episodes, metrics["on_time_rates"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title("On-Time Delivery Rate Across All Phases")
plt.xlabel("Total Episodes")
plt.ylabel("On-Time Rate (%)")
plt.ylim(0, 100)
for i, transition in enumerate(phase_transitions):
plt.axvline(x=transition, color="g", linestyle="--")
plt.text(
transition,
plt.ylim()[0] + (plt.ylim()[1] - plt.ylim()[0]) * 0.1,
f"P{i+1}→P{i+2}",
rotation=90,
verticalalignment="bottom",
)
plt.legend()
# Plot postponement rates
plt.subplot(2, 2, 4)
plt.plot(episodes, metrics["postponement_rates"], label="Postponement Rate")
# Add trend line
z = np.polyfit(episodes, metrics["postponement_rates"], 1)
p = np.poly1d(z)
plt.plot(episodes, p(episodes), "r--", label=f"Trend (slope={z[0]:.2f})")
plt.title("Postponement Rate Across All Phases")
plt.xlabel("Total Episodes")
plt.ylabel("Postponement Rate (%)")
plt.ylim(0, 100)
for i, transition in enumerate(phase_transitions):
plt.axvline(x=transition, color="g", linestyle="--")
plt.text(
transition,
plt.ylim()[0] + (plt.ylim()[1] - plt.ylim()[0]) * 0.1,
f"P{i+1}→P{i+2}",
rotation=90,
verticalalignment="bottom",
)
plt.legend()
plt.tight_layout()
plt.savefig(os.path.join(output_dir, f"overall_results_{timestamp}.png"), dpi=300)
plt.close()
def plot_exploration_vs_performance(all_metrics, phases, save_path, current_phase, current_episode):
"""
Plot exploration rate vs performance metrics over time.
"""
import matplotlib.pyplot as plt
import numpy as np
if len(all_metrics["rewards"]) < 5: # Not enough data to plot
return
episodes = np.arange(len(all_metrics["rewards"]))
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
# Plot 1: Exploration Rate over Time
ax1.plot(episodes, all_metrics["exploration_rates"], "b-", linewidth=2, label="Exploration Rate")
ax1.set_xlabel("Episode")
ax1.set_ylabel("Exploration Rate")
ax1.set_title("Exploration Rate Decay Over Training")
ax1.grid(True, alpha=0.3)
ax1.legend()
# Add phase transition lines
for i, transition in enumerate(all_metrics["phase_transitions"]):
ax1.axvline(x=transition, color="red", linestyle="--", alpha=0.7)
ax1.text(transition, ax1.get_ylim()[1] * 0.9, f"P{i+2}", rotation=90, verticalalignment="top", fontsize=8)
# Plot 2: Rewards vs Exploration Rate (scatter)
ax2.scatter(all_metrics["exploration_rates"], all_metrics["rewards"], c=episodes, cmap="viridis", alpha=0.6, s=20)
ax2.set_xlabel("Exploration Rate")
ax2.set_ylabel("Reward")
ax2.set_title("Reward vs Exploration Rate")
ax2.grid(True, alpha=0.3)
cbar = plt.colorbar(ax2.collections[0], ax=ax2)
cbar.set_label("Episode")
# Plot 3: Moving Average Performance
window = min(50, len(all_metrics["rewards"]) // 4)
if window > 1:
moving_avg_rewards = []
moving_avg_exploration = []
for i in range(window - 1, len(all_metrics["rewards"])):
moving_avg_rewards.append(np.mean(all_metrics["rewards"][i - window + 1 : i + 1]))
moving_avg_exploration.append(np.mean(all_metrics["exploration_rates"][i - window + 1 : i + 1]))
episodes_ma = episodes[window - 1 :]
ax3.plot(episodes_ma, moving_avg_rewards, "g-", linewidth=2, label=f"{window}-Episode MA Reward")
ax3_twin = ax3.twinx()
ax3_twin.plot(
episodes_ma, moving_avg_exploration, "r--", linewidth=2, alpha=0.7, label=f"{window}-Episode MA Exploration"
)
ax3.set_xlabel("Episode")
ax3.set_ylabel("Reward (Moving Average)", color="g")
ax3_twin.set_ylabel("Exploration Rate (Moving Average)", color="r")
ax3.set_title(f"Performance vs Exploration Trends ({window}-Episode MA)")
ax3.grid(True, alpha=0.3)
# Add phase transitions
for transition in all_metrics["phase_transitions"]:
ax3.axvline(x=transition, color="black", linestyle="--", alpha=0.5)
# Plot 4: On-Time Rate vs Exploration
ax4.scatter(
all_metrics["exploration_rates"], all_metrics["on_time_rates"], c=episodes, cmap="plasma", alpha=0.6, s=20
)
ax4.set_xlabel("Exploration Rate")
ax4.set_ylabel("On-Time Rate (%)")
ax4.set_title("On-Time Rate vs Exploration Rate")
ax4.grid(True, alpha=0.3)
cbar4 = plt.colorbar(ax4.collections[0], ax=ax4)
cbar4.set_label("Episode")
plt.suptitle(
f"Exploration vs Performance Analysis\n(Phase {current_phase+1}, Episode {current_episode})", fontsize=14
)
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches="tight")
plt.close()
def generate_phase_summary_report(
phase_metrics, phase_idx, phase_name, episodes_completed, env_config, final_exploration_rate, all_metrics
):
"""Generate comprehensive phase summary report with performance analysis."""
logger.info("\n" + "=" * 80)
logger.info(f"PHASE {phase_idx + 1} COMPLETION SUMMARY: {phase_name}")
logger.info("=" * 80)
# Basic phase info
logger.info(f"Episodes Completed: {episodes_completed}")
logger.info(f"Environment Configuration:")
logger.info(f" - Vehicles: {env_config.get('num_vehicles', 'N/A')}")
logger.info(f" - Restaurants: {env_config.get('num_restaurants', 'N/A')}")
logger.info(f" - Order Interval: {env_config.get('mean_interarrival_time', 'N/A')} min")
logger.info(f" - Final Exploration Rate: {final_exploration_rate:.3f}")
# Performance statistics
avg_reward = np.mean(phase_metrics["rewards"])
avg_delay = np.mean(phase_metrics["delays"])
avg_on_time = np.mean(phase_metrics["on_time_rates"])
avg_postponement = np.mean(phase_metrics["postponement_rates"])
# Performance trends (first 10 vs last 10 episodes)
early_rewards = phase_metrics["rewards"][: min(10, len(phase_metrics["rewards"]))]
late_rewards = phase_metrics["rewards"][-min(10, len(phase_metrics["rewards"])) :]
reward_improvement = (
np.mean(late_rewards) - np.mean(early_rewards) if len(early_rewards) > 0 and len(late_rewards) > 0 else 0
)
early_on_time = phase_metrics["on_time_rates"][: min(10, len(phase_metrics["on_time_rates"]))]
late_on_time = phase_metrics["on_time_rates"][-min(10, len(phase_metrics["on_time_rates"])) :]
on_time_improvement = (
np.mean(late_on_time) - np.mean(early_on_time) if len(early_on_time) > 0 and len(late_on_time) > 0 else 0
)
logger.info(f"\nPerformance Metrics:")
logger.info(f" - Average Reward: {avg_reward:.2f}")
logger.info(f" - Average Delay: {avg_delay:.2f} minutes")
logger.info(f" - Average On-Time Rate: {avg_on_time:.1f}%")
logger.info(f" - Average Postponement Rate: {avg_postponement:.1f}%")
logger.info(f"\nLearning Progress (First 10 vs Last 10 episodes):")
logger.info(
f" - Reward Improvement: {reward_improvement:+.2f} ({reward_improvement/abs(np.mean(early_rewards))*100:+.1f}% change)"
if early_rewards
else " - Reward Improvement: N/A"
)
logger.info(
f" - On-Time Rate Improvement: {on_time_improvement:+.1f}pp"
if early_on_time
else " - On-Time Rate Improvement: N/A"
)
# Phase comparison (if not first phase)
if phase_idx > 0 and len(all_metrics["phase_transitions"]) > 0:
prev_phase_start = all_metrics["phase_transitions"][-2] if len(all_metrics["phase_transitions"]) > 1 else 0
prev_phase_end = all_metrics["phase_transitions"][-1]
prev_avg_reward = np.mean(all_metrics["rewards"][prev_phase_start:prev_phase_end])
prev_avg_on_time = np.mean(all_metrics["on_time_rates"][prev_phase_start:prev_phase_end])
logger.info(f"\nPhase-to-Phase Comparison:")
logger.info(
f" - Reward vs Previous Phase: {avg_reward - prev_avg_reward:+.2f} ({((avg_reward - prev_avg_reward)/abs(prev_avg_reward)*100):+.1f}%)"
)
logger.info(f" - On-Time Rate vs Previous Phase: {avg_on_time - prev_avg_on_time:+.1f}pp")
# Learning insights
reward_std = np.std(phase_metrics["rewards"])
on_time_std = np.std(phase_metrics["on_time_rates"])
logger.info(f"\nStability Metrics:")
logger.info(f" - Reward Stability (std): {reward_std:.2f}")
logger.info(f" - On-Time Rate Stability (std): {on_time_std:.1f}%")
# Learning recommendations for next phase
if phase_idx < 3: # Not the final phase
if reward_improvement > 0:
logger.info(f"\n✅ Phase Learning: SUCCESSFUL - Model shows positive improvement")
else:
logger.info(f"\n⚠️ Phase Learning: CONCERNING - Model shows declining performance")
if final_exploration_rate < 0.1:
logger.info(f"✅ Exploration: ADEQUATE - Reached low exploration ({final_exploration_rate:.3f})")
else:
logger.info(f"⚠️ Exploration: HIGH - Still exploring heavily ({final_exploration_rate:.3f})")
logger.info("=" * 80 + "\n")
def find_latest_model(model_dir="data/models"):
"""Find the latest phased training model and its resume information."""
if not os.path.exists(model_dir):
return None, 0, 0
# Find phased training directories
phased_dirs = [d for d in os.listdir(model_dir) if d.startswith("phased_training_")]
if not phased_dirs:
return None, 0, 0
# Find the most recent directory
phased_dirs.sort(reverse=True)
latest_dir = os.path.join(model_dir, phased_dirs[0])
# Try to find the latest final model from the highest phase
for phase in range(10, 0, -1): # Look from phase 10 down to 1
final_model = os.path.join(latest_dir, f"rl_aca_phase{phase}_final.pt")
if os.path.exists(final_model):
logger.info(f"Found final model for phase {phase}: {final_model}")
return final_model, phase - 1, 0
# If no final models found, try the latest.pt file
latest_model = os.path.join(latest_dir, "rl_aca_latest.pt")
if os.path.exists(latest_model):
# Try to determine phase from resuming_info.json
if os.path.exists(os.path.join(latest_dir, "resuming_info.json")):
with open(os.path.join(latest_dir, "resuming_info.json"), "r") as f:
resume_info = json.load(f)
phase = resume_info.get("phase", 0)
episode = resume_info.get("episode", 0)
return latest_model, phase, episode
return latest_model, 0, 0
# Fallback: look for any pt files in the directory
model_files = [f for f in os.listdir(latest_dir) if f.endswith(".pt")]
if model_files:
model_files.sort(reverse=True) # Sort to get newest first
model_path = os.path.join(latest_dir, model_files[0])
# Try to extract phase from filename using regex
import re
phase_match = re.search(r"phase(\d+)", model_files[0])
phase = int(phase_match.group(1)) - 1 if phase_match else 0
return model_path, phase, 0
return None, 0, 0
def evaluate_model(
model_path: str,
num_episodes: int = 10,
seed: int = 100,
visualize: bool = False,
env_config=None, # Added parameter for environment config
):
"""
Evaluate a trained RL-ACA model over multiple episodes.
Args:
model_path: Path to the trained model
num_episodes: Number of evaluation episodes
district_day: Tuple of (district_id, day) for Meituan data
seed: Random seed for reproducibility
visualize: Whether to enable visualization
env_config: Optional environment configuration to use for evaluation
"""
# Metrics to track
metrics = {
"total_rewards": [],
"total_delays": [],
"on_time_rates": [],
"max_delays": [],
"total_distances": [],
"vehicle_utilizations": [],
"total_travel_times": [],
}
logger.info(f"Evaluating model: {model_path}")
# Use default environment if none provided
env_params = env_config or {}
# Evaluation loop
for episode in tqdm(range(num_episodes), desc="Evaluating RL-ACA"):
# Run an episode with training disabled
stats = run_test_episode(
solver_name="rl_aca",
seed=seed + episode,
reposition_idle_vehicles=False,
visualize=visualize,
rl_model_path=model_path,
exploration_rate=0.00,
training_mode=False, # Set to False for evaluation
env_config=env_params, # Pass as a single dictionary
)
# Track metrics
metrics["total_rewards"].append(stats["total_reward"])
metrics["total_delays"].append(sum(stats["delay_values"]) if stats["delay_values"] else 0)
metrics["max_delays"].append(stats["max_delay"])
metrics["total_distances"].append(stats["total_distance"])
# Calculate vehicle utilization
idle_rates = stats.get("active_period_idle_rates_by_vehicle", {})
if idle_rates:
vehicle_utilizations = [1 - np.mean(rates) for rates in idle_rates.values()]
metrics["vehicle_utilizations"].append(np.mean(vehicle_utilizations))
else:
metrics["vehicle_utilizations"].append(0.0)
# Calculate total travel time (in minutes)
speed = 8 # 8 km/h for 30-second intervals
if stats["total_distance"] > 0:
travel_time = (stats["total_distance"] / speed) * 60 # Convert to minutes
metrics["total_travel_times"].append(travel_time)
else:
metrics["total_travel_times"].append(0.0)
total_orders = max(1, stats["orders_delivered"])
late_orders = len(stats["late_orders"])
on_time_rate = ((total_orders - late_orders) / total_orders) * 100
metrics["on_time_rates"].append(on_time_rate)
# Calculate average metrics
avg_reward = np.mean(metrics["total_rewards"])
avg_delay = np.mean(metrics["total_delays"])
avg_on_time = np.mean(metrics["on_time_rates"])
avg_max_delay = np.mean(metrics["max_delays"])
avg_distance = np.mean(metrics["total_distances"])
avg_utilization = np.mean(metrics["vehicle_utilizations"])
avg_travel_time = np.mean(metrics["total_travel_times"])
logger.info(f"Evaluation Results ({num_episodes} episodes):")
logger.info(f"Average Reward: {avg_reward:.2f}")
logger.info(f"Average Total Delay: {avg_delay:.2f} minutes")
logger.info(f"Average On-Time Rate: {avg_on_time:.2f}%")
logger.info(f"Average Max Delay: {avg_max_delay:.2f} minutes")
logger.info(f"Average Total Distance: {avg_distance:.2f} km")
logger.info(f"Average Vehicle Utilization: {avg_utilization:.2f}%")
logger.info(f"Average Travel Time: {avg_travel_time:.2f} minutes")
return metrics
def perform_statistical_test(heuristic_data: List[float], rl_data: List[float], metric_name: str) -> Dict:
"""
Perform paired t-test to compare two groups of performance metrics.
Paired t-test was chosen because:
- Compares paired observations (same seeds) to reduce variance from different scenarios
- More sensitive to algorithmic differences by controlling for random factors
- Each heuristic episode is compared to the corresponding RL episode with same seed
- Reduces noise from different order patterns, timing, and random events
- Standard approach for algorithm comparison studies in operations research
- Provides both statistical significance and effect size for practical significance
Args:
heuristic_data: List of metric values for heuristic method (ordered by seed)
rl_data: List of metric values for RL method (ordered by same seeds)
metric_name: Name of the metric being tested
Returns:
Dictionary containing test results
"""
results = {
'metric': metric_name,
'heuristic_mean': np.mean(heuristic_data),