Python粒子群优化算法结合热力图TIFF文件案例
1. 项目概述
本项目使用粒子群优化算法(PSO)在热力图TIFF文件中寻找温度最高点。热力图通常以地理空间数据形式存储(TIFF格式),包含温度分布信息。PSO算法模拟鸟群觅食行为,通过粒子协作在搜索空间中寻找最优解。
import numpy as np
import rasterio
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
import time
# 创建热力图数据(模拟真实场景)
def create_heatmap_tiff(filename):
x = np.linspace(-5, 5, 500)
y = np.linspace(-5, 5, 500)
X, Y = np.meshgrid(x, y)
# 创建多峰温度分布
Z = (np.sin(X)*np.cos(Y)*2 +
np.exp(-((X-2)**2 + (Y-2)**2)/2) * 3 +
np.exp(-((X+3)**2 + (Y+1)**2)/3) * 4 +
np.exp(-((X-1)**2 + (Y+3)**2)/4) * 5)
# 标准化到0-100℃范围
Z = (Z - Z.min()) / (Z.max() - Z.min()) * 100
# 保存为TIFF
with rasterio.open(
filename,
'w',
driver='GTiff',
height=Z.shape[0],
width=Z.shape[1],
count=1,
dtype=Z.dtype,
crs='EPSG:4326',
transform=rasterio.transform.from_origin(x.min(), y.max(), x[1]-x[0], y[1]-y[0])
) as dst:
dst.write(Z, 1)
# 生成热力图文件
create_heatmap_tiff('heatmap.tif')
2. 粒子群优化算法实现
class ParticleSwarmOptimizer:
def __init__(self, objective_func, bounds, num_particles=50, max_iter=100,
inertia=0.5, cognitive_param=1.5, social_param=1.5):
self.objective_func = objective_func
self.bounds = np.array(bounds)
self.num_particles = num_particles
self.max_iter = max_iter
self.inertia = inertia
self.cognitive_param = cognitive_param
self.social_param = social_param
# 初始化粒子
self.particles = np.random.uniform(
low=self.bounds[:, 0],
high=self.bounds[:, 1],
size=(self.num_particles, len(self.bounds))
)
self.velocities = np.zeros((self.num_particles, len(self.bounds)))
self.best_positions = self.particles.copy()
self.best_scores = np.full(self.num_particles, np.inf)
self.global_best_position = None
self.global_best_score = np.inf
self.history = []
def optimize(self):
for iter_num in range(self.max_iter):
for i