#随机位置,k-means
import math
import random

import Users
from pso import PSO
import tool
import GDOP
import NSGA2 as ns
from sklearn.cluster import KMeans
import draw
#计算用户平均snr
def function_snr(users,uavs_pos,c_association,power):
    sum=0
    for user_index in range(len(c_association)):
        snr=tool.cal_snr(uavs_pos[c_association[user_index]],users[user_index],power[c_association[user_index]][user_index])
        sum+=snr
    return sum/len(users)

#计算用户平均gdop
def function_gdop(users,uavs_pos,c_association,p_association):
    # p_association=tool.get_p_association(users,uavs_pos,c_association,len(users)*2)
    sum=0
    for user_index in p_association:
        uavs=[]
        uavs.append(uavs_pos[c_association[user_index]])
        for uav_index in p_association[user_index]:
            uavs.append(uavs_pos[uav_index])
        gdop=GDOP.calculate_gdop(uavs,users[user_index])
        sum+=gdop
    return -sum/len(users)

def punish_function(gdop,gdop_thre=-3):
    if gdop<gdop_thre:
        return -100
    else:
        return 0

def fitness(users,uavs_pos):
    c_association = tool.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
    p_association = tool.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
    p_solution=ns.init_p(uavs_pos,users)
    snr=function_snr(users, uavs_pos, c_association, p_solution)
    gdop=function_gdop(users, uavs_pos, c_association, p_association, )
    punish=punish_function(gdop)
    fitness=snr+punish
    return snr,gdop,fitness

def random_pos(k):
    min_pos=0
    max_pos=1000
    uavs=[[min_pos + (max_pos - min_pos) * random.random(), min_pos + (max_pos - min_pos) * random.random(), 100] for i in range(k)]
    return uavs

def k_means(k):
    uavs=[]
    if k > 1:
        model = KMeans(n_clusters=k,  # 聚类簇数
                       random_state=1,  # 决定质心初始化的随机数生成，使用int使随机性具有确定性。
                       max_iter=300,  # 执行一次k-means算法所进行的最大迭代数，默认300
                       ).fit(users)
        center = model.cluster_centers_
        for item in center:
            # height = random.randint(100, 800)
            height = 100
            position = [int(item[0]), int(item[1]), height]
            uavs.append(position)
        return uavs

if __name__ == '__main__':
    users = Users.getUsers("./data.csv")
    # uav_pos = random_pos(3)
    # print(fitness(users, uav_pos))
    uavs=k_means(3)
    print(fitness(users, uavs))


