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
| import numpy as np import matplotlib.pyplot as plt import networkx as nx from scipy.optimize import minimize from itertools import combinations import pandas as pd import seaborn as sns from sklearn.cluster import KMeans import warnings warnings.filterwarnings('ignore')
class EconomicZoneOptimizer: """ A class to optimize economic zone development through mathematical modeling. This includes facility location, network design, and resource allocation. """ def __init__(self, cities, populations, gdp_per_capita): """ Initialize the optimizer with city data. Parameters: cities (list): List of city names populations (list): Population of each city gdp_per_capita (list): GDP per capita for each city """ self.cities = cities self.populations = np.array(populations) self.gdp_per_capita = np.array(gdp_per_capita) self.n_cities = len(cities) np.random.seed(42) self.coordinates = np.random.rand(self.n_cities, 2) * 100 self.distance_matrix = self._calculate_distances() self.economic_potential = self.populations * self.gdp_per_capita def _calculate_distances(self): """Calculate Euclidean distances between all pairs of cities.""" distances = np.zeros((self.n_cities, self.n_cities)) for i in range(self.n_cities): for j in range(self.n_cities): distances[i, j] = np.sqrt( (self.coordinates[i, 0] - self.coordinates[j, 0])**2 + (self.coordinates[i, 1] - self.coordinates[j, 1])**2 ) return distances def calculate_infrastructure_cost(self, distance, population_i, population_j): """ Calculate infrastructure cost between two cities. Cost increases with distance but decreases with economic benefit. """ base_cost = distance * 1000 economic_factor = np.sqrt(population_i * population_j) / 10000 return base_cost / (1 + economic_factor) def optimize_hub_selection(self, max_hubs=5): """ Optimize hub selection using K-means clustering and economic potential. """ kmeans = KMeans(n_clusters=min(max_hubs, self.n_cities), random_state=42) clusters = kmeans.fit_predict(self.coordinates) hubs = [] hub_indices = [] for cluster_id in range(max(clusters) + 1): cluster_cities = np.where(clusters == cluster_id)[0] best_city = cluster_cities[np.argmax(self.economic_potential[cluster_cities])] hubs.append(self.cities[best_city]) hub_indices.append(best_city) return hub_indices, hubs def optimize_network_topology(self, hub_indices): """ Optimize network connections between hubs using minimum spanning tree approach. """ n_hubs = len(hub_indices) hub_costs = np.zeros((n_hubs, n_hubs)) for i in range(n_hubs): for j in range(n_hubs): if i != j: city_i, city_j = hub_indices[i], hub_indices[j] hub_costs[i, j] = self.calculate_infrastructure_cost( self.distance_matrix[city_i, city_j], self.populations[city_i], self.populations[city_j] ) G = nx.Graph() for i in range(n_hubs): for j in range(i + 1, n_hubs): G.add_edge(i, j, weight=hub_costs[i, j]) mst = nx.minimum_spanning_tree(G, weight='weight') return mst, hub_costs def calculate_trade_efficiency(self, hub_indices, mst): """ Calculate trade efficiency metrics for the optimized network. """ path_lengths = [] total_trade_volume = 0 for i in range(len(hub_indices)): for j in range(i + 1, len(hub_indices)): try: path_length = nx.shortest_path_length(mst, i, j, weight='weight') path_lengths.append(path_length) city_i, city_j = hub_indices[i], hub_indices[j] trade_volume = (self.economic_potential[city_i] * self.economic_potential[city_j]) / path_length total_trade_volume += trade_volume except nx.NetworkXNoPath: path_lengths.append(float('inf')) avg_path_length = np.mean([p for p in path_lengths if p != float('inf')]) efficiency_score = total_trade_volume / (avg_path_length + 1) return { 'average_path_length': avg_path_length, 'total_trade_volume': total_trade_volume, 'efficiency_score': efficiency_score, 'connectivity': len([p for p in path_lengths if p != float('inf')]) / len(path_lengths) } def run_optimization(self, max_hubs=5): """ Run the complete optimization process. """ print("🏗️ Starting Economic Zone Optimization...") print("📍 Optimizing hub selection...") hub_indices, hub_cities = self.optimize_hub_selection(max_hubs) print("🌐 Optimizing network topology...") mst, hub_costs = self.optimize_network_topology(hub_indices) print("📊 Calculating efficiency metrics...") efficiency_metrics = self.calculate_trade_efficiency(hub_indices, mst) total_cost = sum([mst[u][v]['weight'] for u, v in mst.edges()]) results = { 'hub_indices': hub_indices, 'hub_cities': hub_cities, 'network': mst, 'hub_costs': hub_costs, 'total_cost': total_cost, 'efficiency_metrics': efficiency_metrics } print("✅ Optimization complete!") return results def visualize_results(self, results): """ Create comprehensive visualizations of the optimization results. """ fig = plt.figure(figsize=(20, 15)) ax1 = plt.subplot(2, 3, 1) scatter = ax1.scatter(self.coordinates[:, 0], self.coordinates[:, 1], c=self.economic_potential, s=self.populations/1000, alpha=0.6, cmap='viridis', edgecolors='black') hub_coords = self.coordinates[results['hub_indices']] ax1.scatter(hub_coords[:, 0], hub_coords[:, 1], c='red', s=200, marker='*', edgecolors='black', linewidth=2, label='Economic Hubs') mst = results['network'] for edge in mst.edges(): i, j = results['hub_indices'][edge[0]], results['hub_indices'][edge[1]] ax1.plot([self.coordinates[i, 0], self.coordinates[j, 0]], [self.coordinates[i, 1], self.coordinates[j, 1]], 'r-', linewidth=2, alpha=0.7) for i, city in enumerate(self.cities): ax1.annotate(city, (self.coordinates[i, 0], self.coordinates[i, 1]), xytext=(5, 5), textcoords='offset points', fontsize=8) ax1.set_title('Optimized Economic Zone Network', fontsize=14, fontweight='bold') ax1.set_xlabel('X Coordinate (km)') ax1.set_ylabel('Y Coordinate (km)') plt.colorbar(scatter, ax=ax1, label='Economic Potential') ax1.legend() ax1.grid(True, alpha=0.3) ax2 = plt.subplot(2, 3, 2) edge_costs = [mst[u][v]['weight'] for u, v in mst.edges()] edge_labels = [f"Hub {u+1}-{v+1}" for u, v in mst.edges()] bars = ax2.bar(range(len(edge_costs)), edge_costs, color='skyblue', edgecolor='navy') ax2.set_title('Infrastructure Costs by Connection', fontsize=14, fontweight='bold') ax2.set_xlabel('Network Connections') ax2.set_ylabel('Cost (Million $)') ax2.set_xticks(range(len(edge_labels))) ax2.set_xticklabels(edge_labels, rotation=45) for bar, cost in zip(bars, edge_costs): ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + max(edge_costs)*0.01, f'${cost:.1f}M', ha='center', va='bottom', fontweight='bold') ax2.grid(True, alpha=0.3, axis='y') ax3 = plt.subplot(2, 3, 3) hub_potential = self.economic_potential[results['hub_indices']] non_hub_potential = np.delete(self.economic_potential, results['hub_indices']) ax3.hist([hub_potential, non_hub_potential], bins=10, alpha=0.7, label=['Hub Cities', 'Non-Hub Cities'], color=['red', 'blue']) ax3.set_title('Economic Potential Distribution', fontsize=14, fontweight='bold') ax3.set_xlabel('Economic Potential') ax3.set_ylabel('Number of Cities') ax3.legend() ax3.grid(True, alpha=0.3) ax4 = plt.subplot(2, 3, 4) metrics = results['efficiency_metrics'] metric_names = ['Avg Path Length', 'Trade Volume\n(×10⁶)', 'Efficiency Score\n(×10⁻³)', 'Connectivity'] metric_values = [ metrics['average_path_length'], metrics['total_trade_volume'] / 1e6, metrics['efficiency_score'] / 1e3, metrics['connectivity'] * 100 ] bars = ax4.bar(metric_names, metric_values, color=['orange', 'green', 'purple', 'brown']) ax4.set_title('Network Efficiency Metrics', fontsize=14, fontweight='bold') ax4.set_ylabel('Metric Values') for bar, value in zip(bars, metric_values): ax4.text(bar.get_x() + bar.get_width()/2, bar.get_height() + max(metric_values)*0.01, f'{value:.2f}', ha='center', va='bottom', fontweight='bold') ax4.grid(True, alpha=0.3, axis='y') ax5 = plt.subplot(2, 3, 5) city_data = pd.DataFrame({ 'City': self.cities, 'Population': self.populations, 'GDP_per_capita': self.gdp_per_capita, 'Economic_Potential': self.economic_potential, 'Is_Hub': [i in results['hub_indices'] for i in range(self.n_cities)] }) city_data = city_data.sort_values('Economic_Potential', ascending=True) colors = ['red' if is_hub else 'skyblue' for is_hub in city_data['Is_Hub']] bars = ax5.barh(city_data['City'], city_data['Economic_Potential'], color=colors) ax5.set_title('Cities Ranked by Economic Potential', fontsize=14, fontweight='bold') ax5.set_xlabel('Economic Potential') ax5.grid(True, alpha=0.3, axis='x') ax6 = plt.subplot(2, 3, 6) hub_benefits = [] hub_costs_individual = [] for i, hub_idx in enumerate(results['hub_indices']): benefit = self.economic_potential[hub_idx] hub_benefits.append(benefit) individual_cost = sum([mst[i][j]['weight'] for j in mst.neighbors(i)]) / 2 hub_costs_individual.append(individual_cost) scatter = ax6.scatter(hub_costs_individual, hub_benefits, s=200, alpha=0.7, c=range(len(results['hub_indices'])), cmap='plasma', edgecolors='black') for i, (cost, benefit) in enumerate(zip(hub_costs_individual, hub_benefits)): ax6.annotate(f"Hub {i+1}\n({results['hub_cities'][i]})", (cost, benefit), xytext=(10, 10), textcoords='offset points', fontsize=9, bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7)) ax6.set_title('Hub Cost-Benefit Analysis', fontsize=14, fontweight='bold') ax6.set_xlabel('Infrastructure Cost (Million $)') ax6.set_ylabel('Economic Benefit') ax6.grid(True, alpha=0.3) plt.tight_layout() plt.show() return fig
def run_economic_zone_example(): """ Run a comprehensive example of economic zone optimization. """ print("🌟 Economic Zone Development Optimization Example") print("=" * 60) cities = ['Tokyo', 'Osaka', 'Nagoya', 'Yokohama', 'Kobe', 'Kyoto', 'Fukuoka', 'Sendai'] populations = [13929000, 2691000, 2295000, 3726000, 1538000, 1474000, 1581000, 1082000] gdp_per_capita = [48000, 42000, 45000, 46000, 43000, 41000, 38000, 40000] optimizer = EconomicZoneOptimizer(cities, populations, gdp_per_capita) results = optimizer.run_optimization(max_hubs=4) print(f"\n📊 OPTIMIZATION RESULTS") print(f"=" * 40) print(f"🏆 Selected Economic Hubs: {', '.join(results['hub_cities'])}") print(f"💰 Total Infrastructure Cost: ${results['total_cost']:.1f} Million") print(f"📈 Network Efficiency Score: {results['efficiency_metrics']['efficiency_score']:.2f}") print(f"🔗 Network Connectivity: {results['efficiency_metrics']['connectivity']:.1%}") print(f"📍 Average Path Length: {results['efficiency_metrics']['average_path_length']:.1f} units") print(f"💼 Total Trade Volume: ${results['efficiency_metrics']['total_trade_volume']:.0f}") print(f"\n📊 Generating comprehensive visualizations...") fig = optimizer.visualize_results(results) print(f"\n🔍 DETAILED ANALYSIS") print(f"=" * 40) print("Hub Efficiency Rankings:") hub_data = [] for i, hub_idx in enumerate(results['hub_indices']): efficiency = optimizer.economic_potential[hub_idx] / (optimizer.populations[hub_idx] / 1000) hub_data.append({ 'Hub': results['hub_cities'][i], 'Population': optimizer.populations[hub_idx], 'Economic_Potential': optimizer.economic_potential[hub_idx], 'Efficiency_Ratio': efficiency }) hub_df = pd.DataFrame(hub_data).sort_values('Efficiency_Ratio', ascending=False) for _, row in hub_df.iterrows(): print(f" 🏙️ {row['Hub']}: Efficiency Ratio = {row['Efficiency_Ratio']:.2f}") return optimizer, results
if __name__ == "__main__": optimizer, results = run_economic_zone_example()
|