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
| import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from scipy.stats import norm from scipy.spatial import distance_matrix import random from itertools import permutations import networkx as nx from matplotlib.patches import Patch
np.random.seed(42) random.seed(42)
num_customers = 10 num_vehicles = 3 vehicle_capacity = 30 depot_coords = (0, 0) confidence_level = 0.9
customer_x = np.random.uniform(-10, 10, num_customers) customer_y = np.random.uniform(-10, 10, num_customers) customer_coords = list(zip(customer_x, customer_y))
all_coords = [depot_coords] + customer_coords
demand_means = np.random.uniform(5, 15, num_customers) demand_stds = demand_means * 0.3
dist_matrix = np.zeros((num_customers + 1, num_customers + 1)) for i in range(num_customers + 1): for j in range(num_customers + 1): if i != j: dist_matrix[i, j] = np.sqrt((all_coords[i][0] - all_coords[j][0])**2 + (all_coords[i][1] - all_coords[j][1])**2)
def calculate_route_length(route, dist_mat): length = 0 prev_node = 0 for node in route: length += dist_mat[prev_node, node] prev_node = node length += dist_mat[prev_node, 0] return length
def check_capacity_constraint(route, means, stds, capacity, confidence): route_mean_demand = sum(means[i-1] for i in route) route_var_demand = sum(stds[i-1]**2 for i in route) route_std_demand = np.sqrt(route_var_demand)
z_value = norm.ppf(confidence)
effective_demand = route_mean_demand + z_value * route_std_demand
return effective_demand <= capacity, effective_demand
def savings_algorithm_svrp(dist_mat, means, stds, capacity, confidence, num_nodes): savings = {} for i in range(1, num_nodes): for j in range(1, num_nodes): if i != j: savings[(i, j)] = dist_mat[0, i] + dist_mat[0, j] - dist_mat[i, j]
sorted_savings = sorted(savings.items(), key=lambda x: x[1], reverse=True)
routes = [[i] for i in range(1, num_nodes)]
for (i, j), saving in sorted_savings: route_i = None route_j = None for r in routes: if i in r and i == r[-1]: route_i = r if j in r and j == r[0]: route_j = r
if route_i and route_j and route_i != route_j: merged_route = route_i + route_j feasible, _ = check_capacity_constraint(merged_route, means, stds, capacity, confidence)
if feasible: routes.remove(route_i) routes.remove(route_j) routes.append(merged_route)
return routes
routes = savings_algorithm_svrp(dist_matrix, demand_means, demand_stds, vehicle_capacity, confidence_level, num_customers + 1)
total_distance = 0 route_demands = [] route_risks = []
for route in routes: route_length = calculate_route_length(route, dist_matrix) total_distance += route_length
feasible, effective_demand = check_capacity_constraint(route, demand_means, demand_stds, vehicle_capacity, confidence_level) route_mean_demand = sum(demand_means[i-1] for i in route) route_std_demand = np.sqrt(sum(demand_stds[i-1]**2 for i in route))
risk = 1 - norm.cdf((vehicle_capacity - route_mean_demand) / route_std_demand)
route_demands.append((route_mean_demand, route_std_demand, effective_demand)) route_risks.append(risk)
print(f"Number of routes: {len(routes)}") print(f"Total expected distance: {total_distance:.2f}")
route_stats = [] for i, route in enumerate(routes): mean_demand, std_demand, effective_demand = route_demands[i] route_stats.append({ 'Route': i+1, 'Customers': route, 'Mean Demand': mean_demand, 'Std Demand': std_demand, 'Effective Demand': effective_demand, 'Risk of Exceeding Capacity': route_risks[i] * 100, 'Distance': calculate_route_length(route, dist_matrix) })
route_stats_df = pd.DataFrame(route_stats) print("\nRoute Statistics:") print(route_stats_df[['Route', 'Customers', 'Mean Demand', 'Effective Demand', 'Risk of Exceeding Capacity', 'Distance']])
plt.figure(figsize=(12, 10))
plt.scatter(depot_coords[0], depot_coords[1], c='red', s=200, marker='*', label='Depot') plt.scatter(customer_x, customer_y, c='blue', s=100, label='Customers')
for i, (x, y) in enumerate(customer_coords): plt.annotate(f"{i+1}", (x, y), fontsize=12)
colors = ['green', 'purple', 'orange', 'brown', 'pink', 'gray', 'olive', 'cyan']
for i, route in enumerate(routes): color = colors[i % len(colors)]
plt.plot([depot_coords[0], customer_coords[route[0]-1][0]], [depot_coords[1], customer_coords[route[0]-1][1]], c=color, linewidth=2)
for j in range(len(route)-1): plt.plot([customer_coords[route[j]-1][0], customer_coords[route[j+1]-1][0]], [customer_coords[route[j]-1][1], customer_coords[route[j+1]-1][1]], c=color, linewidth=2)
plt.plot([customer_coords[route[-1]-1][0], depot_coords[0]], [customer_coords[route[-1]-1][1], depot_coords[1]], c=color, linewidth=2, label=f"Route {i+1}: {route}")
plt.title('Stochastic Vehicle Routing Problem Solution', fontsize=16) plt.xlabel('X Coordinate', fontsize=14) plt.ylabel('Y Coordinate', fontsize=14) plt.grid(True, linestyle='--', alpha=0.7) plt.legend(loc='best', fontsize=12) plt.axis('equal')
route_patches = [] for i, route in enumerate(routes): color = colors[i % len(colors)] route_patches.append(Patch(color=color, label=f"Route {i+1}: {route}"))
plt.legend(handles=[ plt.Line2D([0], [0], marker='*', color='w', markerfacecolor='red', markersize=15, label='Depot'), plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='blue', markersize=10, label='Customers') ] + route_patches, loc='best', fontsize=12)
plt.tight_layout() plt.savefig('svrp_solution.png', dpi=300) plt.show()
plt.figure(figsize=(14, 8))
x = np.linspace(0, 25, 100) for i in range(num_customers): y = norm.pdf(x, demand_means[i], demand_stds[i]) plt.plot(x, y, label=f"Customer {i+1}")
plt.axvline(x=vehicle_capacity, color='r', linestyle='--', label='Vehicle Capacity') plt.title('Customer Demand Distributions', fontsize=16) plt.xlabel('Demand', fontsize=14) plt.ylabel('Probability Density', fontsize=14) plt.grid(True, linestyle='--', alpha=0.7) plt.legend(fontsize=12) plt.tight_layout() plt.savefig('demand_distributions.png', dpi=300) plt.show()
plt.figure(figsize=(12, 8))
x = np.linspace(0, 60, 100) for i, route in enumerate(routes): mean_demand, std_demand, _ = route_demands[i] y = norm.pdf(x, mean_demand, std_demand) plt.plot(x, y, label=f"Route {i+1}: {route}")
plt.axvline(x=vehicle_capacity, color='r', linestyle='--', label='Vehicle Capacity') plt.title('Route Demand Distributions', fontsize=16) plt.xlabel('Total Route Demand', fontsize=14) plt.ylabel('Probability Density', fontsize=14) plt.grid(True, linestyle='--', alpha=0.7) plt.legend(fontsize=12) plt.tight_layout() plt.savefig('route_demand_distributions.png', dpi=300) plt.show()
plt.figure(figsize=(10, 6)) risk_df = pd.DataFrame({ 'Route': [f"Route {i+1}" for i in range(len(routes))], 'Risk (%)': [r * 100 for r in route_risks] }) sns.barplot(x='Route', y='Risk (%)', data=risk_df) plt.axhline(y=(1-confidence_level)*100, color='r', linestyle='--', label=f'Acceptable Risk ({(1-confidence_level)*100}%)') plt.title('Risk of Exceeding Vehicle Capacity by Route', fontsize=16) plt.xlabel('Route', fontsize=14) plt.ylabel('Risk (%)', fontsize=14) plt.grid(True, axis='y', linestyle='--', alpha=0.7) plt.legend(fontsize=12) plt.tight_layout() plt.savefig('route_risks.png', dpi=300) plt.show()
def simulate_demands(means, stds, num_simulations=1000): return np.random.normal( np.tile(means, (num_simulations, 1)), np.tile(stds, (num_simulations, 1)) )
num_simulations = 10000
simulated_demands = simulate_demands(demand_means, demand_stds, num_simulations)
route_failures = np.zeros(len(routes)) for sim in range(num_simulations): for i, route in enumerate(routes): route_demand = sum(max(0, simulated_demands[sim, j-1]) for j in route) if route_demand > vehicle_capacity: route_failures[i] += 1
empirical_risks = route_failures / num_simulations * 100
risk_comparison = pd.DataFrame({ 'Route': [f"Route {i+1}" for i in range(len(routes))], 'Theoretical Risk (%)': [r * 100 for r in route_risks], 'Empirical Risk (%)': empirical_risks })
plt.figure(figsize=(12, 6)) risk_comparison_melted = pd.melt(risk_comparison, id_vars=['Route'], var_name='Risk Type', value_name='Risk (%)') sns.barplot(x='Route', y='Risk (%)', hue='Risk Type', data=risk_comparison_melted) plt.axhline(y=(1-confidence_level)*100, color='r', linestyle='--', label=f'Acceptable Risk ({(1-confidence_level)*100}%)') plt.title('Theoretical vs. Empirical Risk Comparison', fontsize=16) plt.xlabel('Route', fontsize=14) plt.ylabel('Risk (%)', fontsize=14) plt.grid(True, axis='y', linestyle='--', alpha=0.7) plt.legend(fontsize=12) plt.tight_layout() plt.savefig('risk_comparison.png', dpi=300) plt.show()
print("\nRisk Comparison (Theoretical vs. Empirical):") print(risk_comparison)
|