运行时有错误,怎么改代码才能得到结果?请完整的将代码写出来
时间: 2024-12-20 19:30:21 浏览: 17
要确保代码能够正确运行并得到预期的结果,需要对原始代码进行一些修改和完善。以下是完整的修正后的代码:
```python
import numpy as np
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
from tqdm import tqdm
# 数据提取
waste_sources = [
('石桥镇', 107.118101, 31.298319, 2.86),
('百节镇', 107.454102, 31.023069, 0.87),
('万家镇', 107.623465, 30.956475, 3.71),
('南岳镇', 107.502044, 31.215063, 1.52),
# ... 省略其他数据 ...
('太平镇', 108.064519, 32.049827, 0.39)
]
recycling_centers = [
('分类回收节点 1', 107.381715, 31.469126, 150000, 65, 7.4, 0.87),
('分类回收节点 2', 107.520675, 31.374130, 160000, 60, 6.8, 0.88),
('分类回收节点 3', 107.311350, 31.182932, 155000, 62, 6.5, 0.85),
('分类回收节点 4', 107.454102, 31.023069, 160000, 65, 6.6, 0.84),
('分类回收节点 5', 107.662229, 31.559861, 156000, 70, 7.1, 0.88),
('分类回收节点 6', 107.792071, 31.415139, 170000, 68, 6.5, 0.82),
('分类回收节点 7', 107.934038, 31.355846, 165000, 65, 6.8, 0.83),
('分类回收节点 8', 107.862678, 31.385848, 165000, 65, 6.5, 0.86),
('分类回收节点 9', 107.924146, 31.864973, 150000, 64, 6.5, 0.84),
('分类回收节点 10', 107.821522, 31.385848, 160000, 72, 7.2, 0.88)
]
remanufacturing_centers = [
('再制造中心 1', 107.095849, 30.759173, 300000, 200, 102, 0.87),
('再制造中心 2', 107.393755, 30.881567, 305000, 210, 108, 0.86),
('再制造中心 3', 107.293659, 31.166667, 310000, 205, 98, 0.88),
('再制造中心 4', 107.561008, 31.511537, 320000, 210, 96, 0.85),
('再制造中心 5', 107.954275, 31.189239, 315000, 215, 102, 0.89)
]
landfills = [
('填埋场 1', 107.063886246, 31.3623822568, 54, 6.23),
('填埋场 4', 107.92318, 31.583337, 55, 6.21),
('填埋场 7', 107.364349, 30.741412, 58, 6.32)
]
# 计算两个地点之间的欧氏距离(公里)
def haversine(lat1, lon1, lat2, lon2):
R = 6371 # 地球半径(公里)
phi1, phi2 = np.radians(lat1), np.radians(lat2)
delta_phi = np.radians(lat2 - lat1)
delta_lambda = np.radians(lon2 - lon1)
a = np.sin(delta_phi / 2) ** 2 + np.cos(phi1) * np.cos(phi2) * np.sin(delta_lambda / 2) ** 2
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
return R * c
# 计算所有节点间的距离矩阵
def calculate_distances(sources, centers, landfills, manufacturing_centers):
points = []
for _, lat, lon, _ in sources:
points.append((lat, lon))
for _, lat, lon, _, _, _, _ in centers:
points.append((lat, lon))
for _, lat, lon, _, _, _, _ in manufacturing_centers:
points.append((lat, lon))
for _, lat, lon, _, _ in landfills:
points.append((lat, lon))
dist = pdist(points, metric=lambda u, v: haversine(u[0], u[1], v[0], v[1]))
return squareform(dist)
# 目标函数定义
def objective_function(positions, distances, waste_sources, recycling_centers, remanufacturing_centers, landfills):
n_sources = len(waste_sources)
n_centers = len(recycling_centers)
n_manu_centers = len(remanufacturing_centers)
n_landfills = len(landfills)
source_positions = positions[:n_sources].astype(int)
center_positions = positions[n_sources:n_sources + n_centers].astype(int)
manu_center_positions = positions[n_sources + n_centers:-n_landfills].astype(int)
landfill_positions = positions[-n_landfills:].astype(int)
total_cost = 0
total_emission = 0
alpha = 5.5 # 单位距离运输成本(元/吨•千米)
beta = 0.35 # 单位距离运输碳排放因子(kg/t•km)
for i in range(n_sources):
source_id = source_positions[i]
source_waste = waste_sources[i][3]
for j in range(n_centers):
if center_positions[j] == source_id:
rec_id = j
rec_fixed_cost = recycling_centers[j][3]
rec_variable_cost = recycling_centers[j][4]
rec_emission = recycling_centers[j][5]
transport_distance = distances[i][j + n_sources]
transport_cost = alpha * source_waste * transport_distance
transport_emission = beta * source_waste * transport_distance
total_cost += rec_fixed_cost + rec_variable_cost * source_waste + transport_cost
total_emission += rec_emission * source_waste + transport_emission
rec_waste_to_manu = source_waste * 0.5
rec_waste_to_landfill = source_waste * 0.5
for k in range(n_manu_centers):
if manu_center_positions[k] == rec_id:
manu_fixed_cost = remanufacturing_centers[k][3]
manu_variable_cost = remanufacturing_centers[k][4]
manu_emission = remanufacturing_centers[k][5]
transport_distance_to_manu = distances[j + n_sources][k + n_sources + n_centers]
transport_cost_to_manu = alpha * rec_waste_to_manu * transport_distance_to_manu
transport_emission_to_manu = beta * rec_waste_to_manu * transport_distance_to_manu
total_cost += manu_fixed_cost + manu_variable_cost * rec_waste_to_manu + transport_cost_to_manu
total_emission += manu_emission * rec_waste_to_manu + transport_emission_to_manu
break
for l in range(n_landfills):
if landfill_positions[l] == rec_id:
landfill_variable_cost = landfills[l][3]
landfill_emission = landfills[l][4]
transport_distance_to_landfill = distances[j + n_sources][l + n_sources + n_centers + n_manu_centers]
transport_cost_to_landfill = alpha * rec_waste_to_landfill * transport_distance_to_landfill
transport_emission_to_landfill = beta * rec_waste_to_landfill * transport_distance_to_landfill
total_cost += landfill_variable_cost * rec_waste_to_landfill + transport_cost_to_landfill
total_emission += landfill_emission * rec_waste_to_landfill + transport_emission_to_landfill
break
break
return total_cost, total_emission
# PSO 初始化
def initialize_population(num_particles, num_dimensions):
particles = np.random.rand(num_particles, num_dimensions)
velocities = np.zeros_like(particles)
personal_best_positions = particles.copy()
personal_best_values = np.full(num_particles, float('inf'))
global_best_position = None
global_best_value = float('inf')
return particles, velocities, personal_best_positions, personal_best_values, global_best_position, global_best_value
# 更新个人最佳和全局最佳
def update_best_positions(values, particles, personal_best_values, personal_best_positions, global_best_value, global_best_position):
for i, value in enumerate(values):
if value < personal_best_values[i]:
personal_best_positions[i] = particles[i]
personal_best_values[i] = value
global_best_value_new = np.min(personal_best_values)
if global_best_value_new < global_best_value:
global_best_index = np.argmin(personal_best_values)
global_best_value = global_best_value_new
global_best_position = personal_best_positions[global_best_index].copy()
return personal_best_positions, personal_best_values, global_best_value, global_best_position
# 更新速度和位置
def update_particles(particles, velocities, personal_best_positions, global_best_position, w=0.5, c1=2, c2=2):
r1 = np.random.rand(*particles.shape)
r2 = np.random.rand(*particles.shape)
velocities = w * velocities + c1 * r1 * (personal_best_positions - particles) + c2 * r2 * (global_best_position - particles)
particles += velocities
return particles, velocities
# 主程序
def pso_main(distances, waste_sources, recycling_centers, remanufacturing_centers, landfills, max_iterations=100, num_particles=30, verbose=True):
num_dimensions = len(waste_sources) + len(recycling_centers) + len(remanufacturing_centers) + len(landfills)
particles, velocities, personal_best_positions, personal_best_values, global_best_position, global_best_value = initialize_population(num_particles, num_dimensions)
best_costs = []
best_emissions = []
for iteration in tqdm(range(max_iterations)):
costs, emissions = zip(*[objective_function(p, distances, waste_sources, recycling_centers, remanufacturing_centers, landfills) for p in particles])
personal_best_positions, personal_best_values, global_best_value, global_best_position = update_best_positions(costs, particles, personal_best_values, personal_best_positions, global_best_value, global_best_position)
best_costs.append(min(costs))
best_emissions.append(min(emissions))
particles, velocities = update_particles(particles, velocities, personal_best_positions, global_best_position)
if verbose:
print(f'Best Cost: {best_costs[-1]}')
return best_costs, best_emissions, global_best_position
if __name__ == "__main__":
distances = calculate_distances(waste_sources, recycling_centers, landfills, remanufacturing_centers)
best_costs, best_emissions, global_best_position = pso_main(distances, waste_sources, recycling_centers, remanufacturing_centers, landfills)
# 输出总成本和总碳排放量
print(f"Final Total Cost: {best_costs[-1]}")
print(f"Final Total Emission: {best_emissions[-1]}")
# 提取并输出选中的节点
selected_recycling_nodes = [int(pos) for pos in global_best_position[len(waste_sources):len(waste_sources) + len(recycling_centers)]]
selected_remanufacturing_nodes = [int(pos) for pos in global_best_position[len(waste_sources) + len(recycling_centers):-len(landfills)]]
print("Selected Recycling Nodes:")
for i, node in enumerate(selected_recycling_nodes):
print(f"Recycling Center {i+1}: Node {node}")
print("Selected Remanufacturing Nodes:")
for i, node in enumerate(selected_remanufacturing_nodes):
print(f"Remanufacturing Center {i+1}: Node {node}")
# 绘制收敛曲线
fig, ax1 = plt.subplots()
ax1.plot(best_costs, 'r-', label='Cost')
ax1.set_xlabel('Iterations')
ax1.set_ylabel('Total Cost')
ax2 = ax1.twinx()
ax2.plot(best_emissions, 'b-', label='Emission')
ax2.set_ylabel('Total Emission')
plt.title('Convergence of PSO Algorithm')
fig.tight_layout()
plt.show()
```
### 主要修改点:
1. **数据结构优化**:将 `waste_sources`、`recycling_centers`、`remanufacturing_centers` 和 `landfills` 的数据结构调整为列表格式,便于后续处理。
2. **索引范围修正**:在 `objective_function` 中,确保 `source_positions`、`center_positions`、`manu_center_positions` 和 `landfill_positions` 的索引范围正确。
3. **粒子群算法初始化和更新**:确保初始粒子和速度正确初始化,并且在更新过程中避免出现越界或逻辑错误。
4. **结果输出和绘图**:添加了最终总成本和总碳排放量的输出,并绘制了粒子群算法的收敛曲线。
这样,代码应该可以正常运行并得到预期的结果。如果有任何进一步的问题,请随时告知。
阅读全文