import os
import random
import numpy as np
import pandas as pd

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as Data

from sklearn.model_selection import train_test_split
from tqdm import tqdm

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 加载电力消耗数据
df = pd.read_csv('Electric_Power_Consumption.csv', delimiter=';',
                 parse_dates={'dt': ['Date', 'Time']}, infer_datetime_format=True,
                 na_values=['nan', '?'], index_col='dt')

# 填充缺失值
df.fillna(method='ffill', inplace=True)

# 重采样到每小时数据
df = df.resample('H').mean()

# 数据归一化
df = (df - df.mean()) / df.std()

# 将数据划分为训练集和测试集
train_df, test_df = train_test_split(df, test_size=0.2, shuffle=False)

# 将数据转换为序列
seq_len = 24 * 7  # 一周
timestep_pred = 24  # 预测未来 24 小时
train_data = []
for i in range(seq_len, len(train_df) - timestep_pred):
    train_data.append(train_df.iloc[i - seq_len:i].values.tolist())

train_data = np.array(train_data)
train_labels = train_df.iloc[seq_len + timestep_pred:].values

test_data = []
for i in range(seq_len, len(test_df) - timestep_pred):
    test_data.append(test_df.iloc[i - seq_len:i].values.tolist())

test_data = np.array(test_data)
test_labels = test_df.iloc[seq_len + timestep_pred:].values

print('训练数据集形状:train_data: %s and train_labels: %s' % (train_data.shape, train_labels.shape))
print('测试数据集形状:test_data: %s and test_labels: %s' % (test_data.shape, test_labels.shape))

train_y_ts = torch.from_numpy(train_labels).float().to(device)
train_X_ts = torch.from_numpy(train_data).float().to(device)

test_y_ts = torch.from_numpy(test_labels).float().to(device)
test_X_ts = torch.from_numpy(test_data).float().to(device)

train_set = Data.TensorDataset(train_X_ts, train_y_ts)
test_set = Data.TensorDataset(test_X_ts, test_y_ts)

num_clients = 10
num_selected = 10
num_rounds = 29
epochs = 10
batch_size = 64

# 使用 WeightedRandomSampler 解决数据不均衡问题
train_loader = []
for i in range(num_clients):
    weight = len(train_set) / num_clients
    train_loader.append(torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True,
                                                sampler=Data.WeightedRandomSampler([weight] * len(train_set), len(train_set), replacement=True)))
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True)


# 定义 LSTM 模型
class LSTM(nn.Module):
    def __init__(self, input_dim, hidden_dim, seq_len, num_layers=2):
        super(LSTM, self).__init__()
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.seq_len = seq_len
        self.num_layers = num_layers

        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_dim * seq_len, 1)

    def forward(self, x):
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).to(device)
        c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).to(device)

        out, (hn, cn) = self.lstm(x, (h0, c0))
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)

        return out


# 定义粒子
class Particle:
    def __init__(self, model):
        self.position = [torch.randn_like(param) for param in model.parameters()]
        self.velocity = [torch.zeros_like(param) for param in self.position]
        self.best_position = [param.data.detach().clone() for param in self.position]
        self.best_loss = float('inf')


# 定义 PSO 算法
class PSO:
    def __init__(self, model, criterion, lr=0.01, momentum=0.8, weight_decay=0.1):
        self.model = model
        self.criterion = criterion
        self.lr = lr
        self.momentum = momentum
        self.weight_decay = weight_decay
        self.particles = [Particle(model) for _ in range(num_selected)]

    def step(self):
        for i in range(num_selected):
            # 更新速度
            with torch.no_grad():
                for j, param in enumerate(self.particles[i].position):
                    self.particles[i].velocity[j] = self.momentum * self.particles[i].velocity[j] \
                                                    + 2 * torch.rand_like(param) * ( \
                                                                self.particles[i].best_position[j] - param) \
                                                    + 2 * torch.rand_like(param) * (global_best_position[j] - param)

                    # 限制速度
                    self.particles[i].velocity[j].clamp_(-1, 1)

            # 更新位置
            for j, param in enumerate(self.particles[i].position):
                param.data.add_(self.lr * self.particles[i].velocity[j].detach())
                param.data.clamp_(-1, 1)

            # 评估适应度
            self.model.load_state_dict(dict(zip(self.model.state_dict().keys(), self.particles[i].position)), strict=False)
            loss = self.evaluate_fitness()

            # 更新个人最优
            if loss < self.particles[i].best_loss:
                self.particles[i].best_position = [param.data.detach().clone() for param in self.particles[i].position]
                self.particles[i].best_loss = loss

            # 更新全局最优
            if self.particles[i].best_loss < global_best_loss:
                global_best_loss = self.particles[i].best_loss
                global_best_position = [param.data.detach().clone() for param in self.particles[i].best_position]

    def evaluate_fitness(self):
        total_loss = 0.0
        with torch.no_grad():
            for data, target in test_loader:
                output = self.model(data)
                loss = self.criterion(output, target)
                total_loss += loss.item() * len(data_loader.dataset)

        return total_loss / len(test_loader.dataset)

    def get_best(self):
        best_particle = min(self.particles, key=lambda x: x.best_loss)
        return best_particle.best_position, best_particle.best_loss

    def evaluate(self, data_loader):
        total_loss = 0.0
        with torch.no_grad():
            for data, target in data_loader:
                output = self.model(data)
                loss = self.criterion(output, target)
                total_loss += loss.item() * len(data_loader)

        return total_loss / len(data_loader.dataset)


# 训练模型
input_dim = train_data.shape[2]
hidden_dim = 128
model = LSTM(input_dim, hidden_dim, seq_len).to(device)
criterion = nn.MSELoss()
optimizer_pso = PSO(model=model, criterion=criterion)

global_best_loss = float('inf')
global_best_position = None

for r in range(num_rounds):
    selected_particles = random.sample(optimizer_pso.particles, num_selected)

    for i in range(num_selected):
        # 使用 Adam 优化器
        optimizer = optim.Adam(model.parameters(), lr=0.01, weight_decay=0.1)

        # 加载粒子位置到模型
        model.load_state_dict(dict(zip(model.state_dict().keys(), selected_particles[i].position)), strict=False)

        # 训练模型
        train_loss = 0.0
        for epoch in range(epochs):
            model.train()
            for data, target in tqdm(train_loader[i], desc='训练轮次 %d/%d 客户端 %d/%d' % (r + 1, num_rounds, i + 1, num_clients)):
                if len(target.shape) == 2:
                    target = torch.unsqueeze(target, dim=2)
                target = target.permute(0, 2, 1)  # 将目标张量的形状转换为 [batch_size, seq_len, 1]
                target = target[:, :, 0]  # 将最后一维的长度为 1 的维度去掉

                optimizer.zero_grad()
                output = model(data)
                loss = criterion(output, target)
                loss.backward()
                optimizer.step()

                # 更新个人最优位置和最优损失
                selected_particles[i].best_position = [param.data.detach().clone() for param in model.parameters()]
                selected_particles[i].best_loss = optimizer_pso.evaluate_fitness()

                # 更新全局最优位置和最优损失
                if selected_particles[i].best_loss < global_best_loss:
                    global_best_loss = selected_particles[i].best_loss
                    global_best_position = [param.data.detach().clone() for param in selected_particles[i].best_position]

            # 评估模型
            model.eval()
            train_mse = optimizer_pso.evaluate(train_loader[i])
            test_mse = optimizer_pso.evaluate(test_loader)
            print('轮次 %d/%d, 客户端 %d/%d, 训练 MSE: %.4f, 测试 MSE: %.4f' % (r + 1, num_rounds, i + 1, num_clients, train_mse, test_mse))

            # 更新粒子群
            optimizer_pso.step()

            # 将模型参数复制到粒子群
            for param, particle_param in zip(model.parameters(), selected_particles[i].position):
                particle_param.data.copy_(param.data)

        # 打印最终评估
        print('最终评估, 训练 MSE: %.4f, 测试 MSE: %.4f' % (train_mse, test_mse))

        # 打印进度
        print('轮次 %d/%d, 全局最优损失: %.4f' % (r + 1, num_rounds, global_best_loss))
基于粒子群优化的电力负荷预测模型