import time

import numpy as np
import random

import Users
import constants as C
import ObjectiveFuction as OF

import matplotlib.pyplot as plt

import tool


class Population:
    def __init__(self, pre_uavs,users,r_c,r_p,dim, factor, rounds, size, object_func,uav_num, CR=0.75):
        self.min_range = C.min_range
        self.max_range = C.max_range
        self.min_height=C.min_height
        self.max_height=C.max_height
        self.users=users
        self.pre_uavs=pre_uavs
        self.r_c=r_c
        self.r_p=r_p
        self.dimension = dim
        self.factor = factor
        self.rounds = rounds
        self.size = size
        self.cur_round = 1
        self.best_pos=tool.getUavInitialPos(uav_num, users)
        self.best=0
        self.best_index=0
        self.CR = CR
        self.uav_num=uav_num
        self.get_object_function_value = object_func
        # 初始化种群
        self.individuality = self.init_population()
        self.init_alloc()
        # self.object_function_values= [self.get_object_function_value(self.pre_uavs,v,self.users,self.r_c,self.r_p) for v in self.individuality]
        self.object_function_values = [self.get_object_function_value(self.pre_uavs,v,self.users,self.r_p,self.p_all,self.b_all,self.c_association,self.p_association)
                                       for v in self.individuality]
        self.mutant = None


    def init_population(self):
        X = []
        # users=Users.generate(100)#用户位置
        for i in range(self.size):
            uavs = []
            if i==0:
                uavs = tool.getUavInitialPos(self.uav_num, users)
            else:
                for index in range(self.uav_num):
                    x = np.random.uniform(self.min_range, self.max_range)
                    y = np.random.uniform(self.min_range, self.max_range)
                    z = np.random.uniform(self.min_height, self.max_height)
                    uavs.append([x, y, z])

            X.append(uavs)
        X = np.array(X)
        return X

    def init_alloc(self):
        c_association, p_association, p_all, b_all = OF.objective_resource(self.pre_uavs, self.users, self.r_c)
        self.c_association = c_association
        self.p_association = p_association
        self.p_all = p_all
        self.b_all = b_all

    def init_r_c(self):
        r_c={}
        for i in range(len(users)):
            r_c[i] = random.randint(1,4)
        return r_c

    def mutate(self):
        self.mutant = []
        for i in range(self.size):
            r0, r1, r2 = 0, 0, 0
            while r0 == r1 or r1 == r2 or r0 == r2 or r0 == i:
                r0 = random.randint(0, self.size - 1)
                r1 = random.randint(0, self.size - 1)
                r2 = random.randint(0, self.size - 1)
            tmp = self.best_pos + (self.individuality[r1] - self.individuality[r2]) * self.factor
            for i in range(len(tmp)):
                for j in range(0,2):
                    if tmp[i][j] > self.max_range:
                        tmp[i][j]= self.max_range
                    elif tmp[i][j] < self.min_range:
                        tmp[i][j]= self.min_range
                if tmp[i][2] > self.max_height:
                    tmp[i][2] = self.max_height
                elif tmp[i][2] < self.min_height:
                    tmp[i][2] = self.min_height
            # for t in range(self.dimension):
            #     if tmp[t] > self.max_range or tmp[t] < self.min_range:
            #         tmp[t] = random.uniform(self.min_range, self.max_range)
            self.mutant.append(tmp)

    def crossover_and_select(self):
        for i in range(self.size):
            Jrand = random.randint(0, self.dimension)
            for j in range(self.dimension):
                if random.random() > self.CR and j != Jrand:
                    self.mutant[i][j] = self.individuality[i][j]
                # tmp = self.get_object_function_value(self.pre_uavs,self.mutant[i],self.users,self.r_c,self.r_p)
                tmp = self.get_object_function_value(self.pre_uavs,self.mutant[i], self.users, self.r_p, self.p_all, self.b_all, self.c_association, self.p_association)
                if tmp > self.object_function_values[i]:
                    self.individuality[i] = self.mutant[i]
                    self.object_function_values[i] = tmp

    def print_best(self):
        self.best= max(self.object_function_values)
        self.best_index = self.object_function_values.index(self.best)
        self.best_pos=self.individuality[self.best_index]
        print("轮数：" + str(self.cur_round))
        print("最佳个体：" + str(self.best_pos))
        print("目标函数值：" + str(self.best))
        return self.best[0]


    def evolution(self):
        start_time = time.time()
        best=[]
        while self.cur_round <= self.rounds:
            self.mutate()
            self.crossover_and_select()
            m=self.print_best()
            best.append(m)
            self.cur_round = self.cur_round + 1
        x=[i for i in range(self.rounds)]
        print(best)
        end_time = time.time()
        run_time = end_time - start_time
        print(run_time)
        plt.plot(best, label='折线图')
        plt.show()


# 测试部分
if __name__ == "__main__":

    users = Users.getUsers("./data.csv")
    r_c={}
    r_p={}
    r=1
    for i in range(len(users)):
        r_c[i] = 4
    for i in range(len(users)):
        r_p[i] = r
        r += 1
    pre_uavs = tool.getUavInitialPos(4, users)
    p = Population(pre_uavs,users,r_c,r_p,dim=4, factor=0.8, rounds=100, size=30, object_func=OF.objective,uav_num=4,)
    p.evolution()


