Python粒子群优化算法结合热力图TIFF文件案例

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神经网络15044

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值