Commit 7ec45da8 authored by 黎小曼's avatar 黎小曼

first commit

parent fae83b47
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
<option value="N806" />
<option value="N803" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/dynamicDeploy.iml" filepath="$PROJECT_DIR$/.idea/dynamicDeploy.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="d8fba307-6469-4459-843c-5fa614b7698e" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2YvsyaE8wVdE3AeXnQCHS55ts8U" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="d8fba307-6469-4459-843c-5fa614b7698e" name="Changes" comment="" />
<created>1701417643165</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1701417643165</updated>
</task>
<servers />
</component>
</project>
\ No newline at end of file
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()
import numpy as np
from numpy.linalg import LinAlgError
from numpy import seterr
seterr(all='raise')
def get_toa_gdop(bs_list, xyz):
"""
compute the gdop of the toa
:param bs_list: the base station coordinate
:param xyz: the location coordinate of the tag
:return: the gdop value
"""
bs_n = len(bs_list)
if bs_n < 3:
return None
h1 = np.mat(np.zeros((bs_n, 3)))
for i in range(0, len(bs_list)):
ri = np.sqrt((bs_list[i][0] - xyz[0]) ** 2 +
(bs_list[i][1] - xyz[1]) ** 2)
if ri == 0:
h1[i, 0] = 0
h1[i, 1] = 0
h1[i, 2] = 1
# h1[i, 3] = 1
else:
h1[i, 0] = (bs_list[i][0] - xyz[0]) / ri
h1[i, 1] = (bs_list[i][1] - xyz[1]) / ri
h1[i, 2] = 1
# h1[i, 3] = 1
m_tmp = h1.T * h1
gdop_value = None
try:
g = m_tmp.I
gdop_value = np.sqrt(g[0, 0] + g[1, 1])
# print(gdop_value)
finally:
return gdop_value
# 计算GDOP 不考虑时钟误差版本即DOP
def calculate_gdop(uavs, estimate_value):
"""
# :param point: 待定位点真实坐标
:param uavs: 无人机坐标集
:param estimate_value: 解算出的坐标
:return: gdop
"""
# estimate_value.append(0)
estimate_value=[estimate_value[0],estimate_value[1],0]
var1 = np.array(uavs) - estimate_value
# 计算距离列向量
d_estimate = (np.sum(var1**2, axis=1)**0.5).reshape(-1, 1)
# 计算visible MATRIX
H = var1 / d_estimate
GDOP = float('inf')
try:
GDOP = np.trace(np.linalg.inv(np.dot(np.transpose(H), H))) ** 0.5
except:
GDOP=float('inf')
finally:
return GDOP
if __name__ == '__main__':
bs_list=[[1,1,1],[2,3,4],[6,6,5]]
bs_list2 = [[1, 3, 3], [3, 1, 3], [5, 4, 3]]
xyz=[3,3.167,0]
print(calculate_gdop(bs_list,xyz))
print(get_toa_gdop(bs_list2,xyz))
\ No newline at end of file
import random
import numpy
import math
from solution import solution
import time
def HHO(objf, lb, ub, dim, SearchAgents_no, Max_iter):
# dim=30
# SearchAgents_no=50
# lb=-100
# ub=100
# Max_iter=500
# initialize the location and Energy of the rabbit
Rabbit_Location = numpy.zeros(dim)
Rabbit_Energy = float("inf") # change this to -inf for maximization problems
# Initialize the locations of Harris' hawks
X = numpy.random.uniform(0, 1, (SearchAgents_no, dim)) * (ub - lb) + lb
# Initialize convergence
convergence_curve = numpy.zeros(Max_iter)
############################
s = solution()
print("HHO is now tackling \"" + objf.__name__ + "\"")
timerStart = time.time()
s.startTime = time.strftime("%Y-%m-%d-%H-%M-%S")
############################
t = 0 # Loop counter
# Main loop
while t < Max_iter:
for i in range(0, SearchAgents_no):
# Check boundries
X[i, :] = numpy.clip(X[i, :], lb, ub)
# fitness of locations
fitness = objf(X[i, :])
# Update the location of Rabbit
if fitness < Rabbit_Energy: # Change this to > for maximization problem
Rabbit_Energy = fitness
Rabbit_Location = X[i, :].copy()
E1 = 2 * (1 - (t / Max_iter)) # factor to show the decreaing energy of rabbit
# Update the location of Harris' hawks
for i in range(0, SearchAgents_no):
E0 = 2 * random.random() - 1; # -1<E0<1
Escaping_Energy = E1 * (E0) # escaping energy of rabbit Eq. (3) in the paper
# -------- Exploration phase Eq. (1) in paper -------------------
if abs(Escaping_Energy) >= 1:
# Harris' hawks perch randomly based on 2 strategy:
q = random.random()
rand_Hawk_index = math.floor(SearchAgents_no * random.random())
X_rand = X[rand_Hawk_index, :]
if q < 0.5:
# perch based on other family members
X[i, :] = X_rand - random.random() * abs(X_rand - 2 * random.random() * X[i, :])
elif q >= 0.5:
# perch on a random tall tree (random site inside group's home range)
X[i, :] = (Rabbit_Location - X.mean(0)) - random.random() * ((ub - lb) * random.random() + lb)
# -------- Exploitation phase -------------------
elif abs(Escaping_Energy) < 1:
# Attacking the rabbit using 4 strategies regarding the behavior of the rabbit
# phase 1: ----- surprise pounce (seven kills) ----------
# surprise pounce (seven kills): multiple, short rapid dives by different hawks
r = random.random() # probablity of each event
if r >= 0.5 and abs(Escaping_Energy) < 0.5: # Hard besiege Eq. (6) in paper
X[i, :] = (Rabbit_Location) - Escaping_Energy * abs(Rabbit_Location - X[i, :])
if r >= 0.5 and abs(Escaping_Energy) >= 0.5: # Soft besiege Eq. (4) in paper
Jump_strength = 2 * (1 - random.random()); # random jump strength of the rabbit
X[i, :] = (Rabbit_Location - X[i, :]) - Escaping_Energy * abs(
Jump_strength * Rabbit_Location - X[i, :])
# phase 2: --------performing team rapid dives (leapfrog movements)----------
if r < 0.5 and abs(Escaping_Energy) >= 0.5: # Soft besiege Eq. (10) in paper
# rabbit try to escape by many zigzag deceptive motions
Jump_strength = 2 * (1 - random.random())
X1 = Rabbit_Location - Escaping_Energy * abs(Jump_strength * Rabbit_Location - X[i, :]);
if objf(X1) < fitness: # improved move?
X[i, :] = X1.copy()
else: # hawks perform levy-based short rapid dives around the rabbit
X2 = Rabbit_Location - Escaping_Energy * abs(
Jump_strength * Rabbit_Location - X[i, :]) + numpy.multiply(numpy.random.randn(dim),
Levy(dim))
if objf(X2) < fitness:
X[i, :] = X2.copy()
if r < 0.5 and abs(Escaping_Energy) < 0.5: # Hard besiege Eq. (11) in paper
Jump_strength = 2 * (1 - random.random())
X1 = Rabbit_Location - Escaping_Energy * abs(Jump_strength * Rabbit_Location - X.mean(0))
if objf(X1) < fitness: # improved move?
X[i, :] = X1.copy()
else: # Perform levy-based short rapid dives around the rabbit
X2 = Rabbit_Location - Escaping_Energy * abs(
Jump_strength * Rabbit_Location - X.mean(0)) + numpy.multiply(numpy.random.randn(dim),
Levy(dim))
if objf(X2) < fitness:
X[i, :] = X2.copy()
convergence_curve[t] = Rabbit_Energy
if (t % 1 == 0):
print(['At iteration ' + str(t) + ' the best fitness is ' + str(Rabbit_Energy)])
t = t + 1
timerEnd = time.time()
s.endTime = time.strftime("%Y-%m-%d-%H-%M-%S")
s.executionTime = timerEnd - timerStart
s.convergence = convergence_curve
s.optimizer = "HHO"
s.objfname = objf.__name__
s.best = Rabbit_Energy
s.bestIndividual = Rabbit_Location
return s
def Levy(dim):
beta = 1.5
sigma = (math.gamma(1 + beta) * math.sin(math.pi * beta / 2) / (
math.gamma((1 + beta) / 2) * beta * 2 ** ((beta - 1) / 2))) ** (1 / beta)
u = 0.01 * numpy.random.randn(dim) * sigma
v = numpy.random.randn(dim)
zz = numpy.power(numpy.absolute(v), (1 / beta))
step = numpy.divide(u, zz)
return step
\ No newline at end of file
import Users
import tool
import tool as T
import constants as C
import math
import GDOP
import resourceAlloc as RA
#计算用户平均gdop
def function_gdop(users,uavs_pos,c_association,p_association,r_p):
# p_association=tool.get_p_association(users,uavs_pos,c_association,len(users)*2)
sum=0
g=[]
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])
g.append(gdop)
sum += gdop
# if gdop>C.G_max/(r_p[user_index]):
# sum+=gdop*10**6
# else:
# sum+=gdop
return g
def real_gdop(users,uavs_pos,c_association,p_association,r_p):
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
def energy(pre_uavs,uavs,time_slot=C.time_slot,speed=C.speed):
sum_e=0
for i in range(len(pre_uavs)):
dis=T.calculate_3d_distance_uavs(pre_uavs[i],uavs[i])
fly_energy=T.cal_fly_energy(dis,speed)
if fly_energy!=0:
# hover_energy = (C.P0 + C.P1) * (time_slot - dis / speed)
hover_energy=(C.P0+C.P1)*(time_slot-dis/speed)
# 10.5*(uavs[i][2]-30)
else:
hover_energy = (C.P0 + C.P1) * (time_slot - dis / speed)
if hover_energy<0:
hover_energy=0
sum_e+=fly_energy+hover_energy
# print(sum_e/len(pre_uavs))
return sum_e
def function_rate(uavs,users,uav_to_user,p_all,b_all,r_c):
rate=[]
u=1.21
for i in range(len(uavs)):
for j in uav_to_user[i]:
p_alloc=p_all[i]
b_alloc=b_all[i]
cur_rate = tool.cal_rate(b_alloc[j], p_alloc[j], uavs[i], users[j])
# if cur_rate<C.R_min*r_c[j]*u:
# cur_rate=-100
rate.append(cur_rate)
return rate
def real_rate(uavs,users,uav_to_user,p_all,b_all,r_c):
rate=[]
for i in range(len(uavs)):
for j in uav_to_user[i]:
p_alloc=p_all[i]
b_alloc=b_all[i]
cur_rate = tool.cal_rate(b_alloc[j], p_alloc[j], uavs[i], users[j])
rate.append(cur_rate)
return rate
def objective_resource_u(uavs_pos,users,r_c):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
p_all,b_all,rate= RA.resource_alloc_u(users, uavs_pos, r_c, p_association, uav_to_user)
return c_association,p_association,p_all,b_all
def objective_resource(uavs_pos,users,r_c):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
p_all,b_all,rate= RA.resource_alloc(users, uavs_pos, r_c, p_association, uav_to_user)
return c_association,p_association,p_all,b_all
def objective_resource_avg(uavs_pos,users,r_c):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
p_all,b_all,rate= RA.resource_alloc_avg(users,uavs_pos,r_c,p_association,uav_to_user)
return c_association,p_association,p_all,b_all
def objective_resource_proportion(uavs_pos,users,r_c):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
p_all,b_all,rate= RA.resource_alloc_proportion(users,uavs_pos,r_c,p_association,uav_to_user)
return c_association,p_association,p_all,b_all
def objective(pre_uavs,uavs_pos,users,r_c,r_p,p_all,b_all,c_association,p_association):
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
rate=function_rate(uavs_pos,users,uav_to_user,p_all,b_all,r_c)
# r=sum(rate)*10**6
r=sum(rate)
u=1.21
gdop = function_gdop(users, uavs_pos, c_association, p_association, r_p)
# e = energy(pre_uavs, uavs_pos)
objective=r-sum(gdop)
for i in range(len(rate)):
if rate[i]<C.R_min*r_c[i]:
objective-=10
if gdop[i]>C.G_max/r_p[i]:
objective-=10
# print("能耗:",e)
return objective, r / len(rate), sum(gdop) / len(users)
# return (r - gdop) - e, r / len(rate), gdop / len(users)
def real_objective(pre_uavs,uavs_pos,users,r_c,r_p,p_all,b_all,c_association,p_association,time_slot):
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
rate = real_rate(uavs_pos, users, uav_to_user, p_all, b_all,r_c)
r = sum(rate)
# r = sum(rate)
gdop = real_gdop(users, uavs_pos, c_association, p_association, r_p)
# e = energy(pre_uavs, uavs_pos,time_slot)
# print("能耗:", e)
objective = r-gdop
return objective, r / len(rate), gdop / len(users)
# return (r - gdop) / e,e, r / len(rate), gdop / len(users)
def gdop_satisfaction(users,uavs_pos,c_association,p_association,r_p):
# p_association=tool.get_p_association(users,uavs_pos,c_association,len(users)*2)
sum=0
g=[]
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])
g.append(gdop)
if gdop>C.G_max/(r_p[user_index]):
continue
else:
sum+=1
return sum/len(users)
def rate_satisfaction(uavs,users,uav_to_user,p_all,b_all,r_c):
num=0
for i in range(len(uavs)):
for j in uav_to_user[i]:
p_alloc=p_all[i]
b_alloc=b_all[i]
cur_rate = tool.cal_rate(b_alloc[j], p_alloc[j], uavs[i], users[j])
if round(cur_rate,4)>=C.R_min*r_c[j]:
num+=1
return num/len(users)
def cal_satisfaction(uavs,users,p_all,b_all,r_c,r_p, c_association,p_association):
g=gdop_satisfaction(users,uavs,c_association,p_association,r_p)
uav_to_user = T.get_uav_to_user(c_association, uavs)
r=rate_satisfaction(uavs,users,uav_to_user,p_all,b_all,r_c)
return r,g
def resource_objective(e,uavs_pos,users,r_p,p_all,b_all,c_association,p_association):
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
rate = function_rate(uavs_pos, users, uav_to_user, p_all, b_all)
r = sum(rate) * 10 ** 6
gdop = real_gdop(users, uavs_pos, c_association, p_association, r_p)
return (r - gdop) / e, r / len(rate), gdop / len(users)
def objective_func(pre_uavs,uavs_pos,users,r_c,r_p,*args):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
p_all,b_all,rate= RA.resource_alloc_avg(users, uavs_pos, r_c, p_association, uav_to_user)
r=sum(rate)
gdop = function_gdop(users, uavs_pos, c_association, p_association,r_p)
# e=energy(pre_uavs,uavs_pos)
# print(e)
# print(p_all,b_all)
# print("rate:",rate,r)
# print("gdop:", gdop)
return r - sum(gdop),r/len(rate),sum(gdop)/len(users)
def objective_func_optimal(pre_uavs,uavs_pos,users,r_c,r_p,*args):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
p_all,b_all,rate= RA.resource_alloc_u(users, uavs_pos, r_c, p_association, uav_to_user)
r=sum(rate)
gdop = function_gdop(users, uavs_pos, c_association, p_association, r_p)
# e=energy(pre_uavs,uavs_pos)
# print(p_all, b_all)
# print("rate:", rate,r)
# print("gdop:", gdop)
return r - sum(gdop),r/len(rate),sum(gdop)/len(users)
def get_snr_gdop(uavs_pos,users,r_c,r_p):
c_association = T.get_c_association(users, uavs_pos, math.ceil(len(users) / len(uavs_pos)))
p_association = T.get_p_association(users, uavs_pos, c_association, len(users) * 2 / len(uavs_pos))
uav_to_user = T.get_uav_to_user(c_association, uavs_pos)
gdop=[]
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])
g=GDOP.calculate_gdop(uavs,users[user_index])
gdop.append(g)
p_all, b_all, rate = RA.resource_alloc_avg(users, uavs_pos, r_c, p_association, uav_to_user)
return rate,gdop
def fixed_w(wmin,wmax,iter,maxgen,index,fitness):
# return (wmax +wmin)/2
return 0.5
def linear_w(wmin,wmax,iter,maxgen,index,fitness):
return wmax - iter * (wmax - wmin) / maxgen
def adapted_w(wmin,wmax,iter,maxgen,index,fitness):
avg=sum(fitness)/len(fitness)
if fitness[index]>avg:
return wmax
else:
w=wmin-(wmax-wmin)*(fitness[index]-min(fitness))/(avg-min(fitness))
return w
def adapted_w2(wmin,wmax,iter,maxgen,index,fitness):
avg=sum(fitness)/len(fitness)
if fitness[index]<=avg:
return wmax
else:
w=wmin+(wmax-wmin)*(max(fitness)-fitness[index])/(max(fitness)-avg)
# w=wmax-(wmax-wmin)*(fitness[index]-min(fitness))/(max(fitness)-min(fitness))#效果不好
return w
def adapted_w3(wmin,wmax,iter,maxgen,fitness):
avg = sum(fitness) / len(fitness)
A=iter*(math.log(wmax)-math.log(wmin))/maxgen-math.log(wmax)
w=math.exp(-A)
return w
def dynamic_c1(iter,maxgen):
return 2*(math.sin(math.pi/2*(1-iter/maxgen)))**2
def dynamic_c2(iter,maxgen):
return 2*(math.sin(math.pi*iter/2/maxgen))**2
if __name__ == "__main__":
users = Users.getUsers("./data3.csv")
r_c = {}
r_p = {}
for i in range(len(users)):
r_c[i] = 2
r = 1
for i in range(len(users)):
r_p[i] = 2
r += 1
# uavs = [[868.34535881, 315.18340086, 50.],
# [292.96443022, 729.7612657, 77.75450997],
# [732.25467955, 927.62861821, 50.],
# [303.40107629, 240.31208079, 150.]]
# uavs=[[973.06680904,364.12885341,52.61221492],
# [655.4558372,85.17834171,84.32290174],
# [920.58870216,343.97478717,69.12057386,]]
uavs = [[335, 772, 67], [382, 739, 75], [1758, 1683, 137], [885, 762, 133], [403, 1196, 94], [1049, 358, 88]]
uavs=[[ 937.13598572,1106.32026504 ,50. ],
[1638.73822307,576.42231656,50. ],
[ 863.950367,1616.3127536,50. ],
[ 264.57183106,364.69333235,138.69332619],
[ 159.74510169,827.61881448,56.27541847],
[1035.04791004,808.44053304 , 140.02500318]]
uavs=[[1672.00438436 ,1012.9975498 , 50. ],
[ 434.16986638 ,1432.14203541 , 50. ],
[ 473.55681971 , 325.27416208 , 71.45922555],
[1115.79267858, 1464.40107477 , 50. ],
[1833.57784143 , 263.09076035 , 50. ],
[1675.2644499 , 1841.36678341 , 50. ]]
c_association = T.get_c_association(users, uavs, math.ceil(len(users) / len(uavs)))
p_association = T.get_p_association(users, uavs, c_association, len(users) * 2 / len(uavs))
uav_to_user = T.get_uav_to_user(c_association, uavs)
p_all, b_all, rate = RA.resource_alloc_avg(users, uavs, r_c, p_association, uav_to_user)
print(objective(uavs,uavs,users,r_c,r_p,p_all,b_all,c_association,p_association))
# print(objective_func_optimal(uavs,uavs,users,r_c,r_p))
#归一化pso
import math
import time
from itertools import combinations
import random
import numpy as np
from matplotlib import pyplot as plt
import Users
from pso import PSO
from improvedPSO import CPSO
import tool
import GDOP
import ObjectiveFuction as OF
from static_pso import SPSO
plt.style.use('seaborn-whitegrid')
# 设置字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
def drawResultAndIter(resultAndIter):
f, ax = plt.subplots(1, 1)
plt.plot(resultAndIter)
ax.set_xlabel('iteration')
ax.set_ylabel('fitness')
plt.show()
def draw_compare(resultArr):
labels=['Adapted w','Fixed w','Linear w']
markers=['o','s','^']
line=['-','--',':','-.']
for i in range(len(resultArr)):
plt.plot(resultArr[i], label=labels[i],linestyle=line[i])
# 设置图例
plt.legend()
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('x')
plt.ylabel('y')
# 显示图形
plt.show()
def draw_c1_c2():
c1=[]
c2=[]
for i in range(100):
c1.append(OF.dynamic_c1(i,100))
c2.append(OF.dynamic_c2(i,100))
c1=np.array(c1)
c2=np.array(c2)
plt.plot(c1, label="c1")
plt.plot(c2, label="c2")
plt.show()
def run_fixed_compare(users, k):
pre_uavs=tool.getUavInitialPos(k,users)
r_c = {}
r_p={}
for i in range(len(users)):
r_c[i] = 4
r=1
for i in range(len(users)):
r_p[i] = r
r+=1
pso=PSO(pre_uavs,users,r_c,r_p,k,)
X, V = pso.initParticle(users)
# print(X)
global_pos, global_best, result = pso.pso(X, V, OF.fixed_w,OF.objective)
print(global_pos, global_best)
# pso迭代曲线
return global_pos, global_best, result
def draw_w(maxIter):
w=[]
for i in range(maxIter):
w.append(OF.adapted_w3(0.4,0.9,i,maxIter,1,))
plt.plot(w)
plt.show()
def run_linear_compare(users, k,num,t):
pre_uavs=tool.getUavInitialPos(k,users)
r_c = {}
r_p={}
for i in range(len(users)):
r_c[i] = 2
r=1
for i in range(len(users)):
r_p[i] = 2
r+=1
pso=PSO(pre_uavs,users,r_c,r_p,k,num,t)
X, V = pso.initParticle(users)
# print(X)
c_association, p_association, p_all, b_all = OF.objective_resource_u(pre_uavs, users, r_c)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w,OF.objective)
pso.re_init(pre_uavs,users,r_c,r_p,c_association,p_association,p_all,b_all)
print(global_pos, global_best)
# pso迭代曲线
return global_pos, global_best, result
def run(users, k,num):
pre_uavs=tool.getUavInitialPos(k,users)
r_c = {}
r_p={}
r = 1
for i in range(len(users)):
r_c[i] = 2
r = 1
for i in range(len(users)):
r_p[i] = 2
r+=1
pso=SPSO(pre_uavs,users,r_c,r_p,k,num)
pso.init_alloc()
X, V = pso.initParticle(users)
# print(X)
# global_pos, global_best, result = pso.pso(X, V, adapted_w3,OF.objective_func,dynamic_c1,dynamic_c2)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
print(global_pos, global_best)
# pso迭代曲线
return global_pos, global_best, result
def run_(users, k,num):
pre_uavs=tool.getUavInitialPos(k,users)
r_c = {}
r_p={}
r = 1
for i in range(len(users)):
r_c[i] = 2
r = 1
for i in range(len(users)):
r_p[i] = 2
r+=1
pso=PSO(pre_uavs,users,r_c,r_p,k,num)
pso.init_alloc()
X, V = pso.initParticle(users)
# print(X)
# global_pos, global_best, result = pso.pso(X, V, adapted_w3,OF.objective_func,dynamic_c1,dynamic_c2)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective_func, )
print(global_pos, global_best)
# pso迭代曲线
return global_pos, global_best, result
def run_all(users,k):
resultArr=[]
global_pos1, global_best1, result1 = run(users, k)
global_pos2, global_best2, result2 = run_fixed_compare(users, k)
global_pos3, global_best3, result3 = run_linear_compare(users, k)
resultArr.append(result1)
resultArr.append(result2)
resultArr.append(result3)
draw_compare(resultArr)
if __name__ == '__main__':
users = Users.getUsers("./data3.csv")
# global_pos, global_best,result=run(users,3)
# print(fitness(users,global_pos))
# run_all(users,4)
# draw_c1_c2()
# draw_data()
# draw_w(150)
p_num=70
# # global_pos, global_best, result = run_fixed_compare(users, 4)
start_time = time.time()
# global_pos, global_best, result = run_(users, 5,p_num)
end_time1 = time.time()
global_pos1, global_best1, result1 = run_linear_compare(users, 5,p_num,200)
end_time2 = time.time()
run_time=end_time1-start_time
run_time1 = end_time2 - end_time1
# run_time2=end_time2 - start_time-run_time1
print("程序运行时间为:", run_time1)
# print(global_best[0])
# print(list(result))
print(list(result1))
# # print("最优解",global_best[0],global_best1[0])
# drawResultAndIter(result1)
# plt.show()
# arr=[]
# arr_t=[]
# for k in range(30,110,20):
# # k=70
# t=250
# # for t in range(100, 350, 50):
# num = []
# sum_time = []
# for i in range(1):
# start_time = time.time()
# global_pos, global_best, result = run_linear_compare(users, 5,k,t)
# num.append(global_best[0])
# print(global_best)
# end_time = time.time()
# run_time = end_time - start_time
# sum_time.append(run_time)
# print("程序运行时间为:", run_time)
# # drawResultAndIter(result)
# # plt.show()
# print(sum(num)/len(num))
# print(sum(sum_time)/len(sum_time))
# arr.append(sum(num)/len(num))
# arr_t.append(sum(sum_time)/len(sum_time))
# print(arr)
# print(arr_t)
# num=[-9657.993479469107, -11023.13972392451, -10511.070624574759, -10724.3448906409, -10623.367312657523,
# -9802.662654304893, -7603.911448332553, -9695.134404543633, -9575.730714137575, -10454.63434179702]
# print(sum(num)/10)
import math
import random
import numpy as np
import csv
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import pandas as pd
# 随机生成U个用户的位置
def generate_in_file(num,filename):
data = np.random.randint(1, 2000, (num, 2))
f = open(filename, 'w', encoding='utf-8', newline="")
# 2.基于文件对象构建csv写入对象
csv_write = csv.writer(f)
# 4.写入csv文件
for d in data:
csv_write.writerow(d)
return data
def generate(num):
data = np.random.randint(1, 1000, (num, 2))
return data
def generateNormalDistribution(num):
mu, sigma = 500, 170 # 有关于正态分布的值μ,σ
x = sigma * np.random.randn(1, num) + mu
x = ([i for item in x for i in item]) # 在这个循环中我们能把二维的数组转换成一维的数组,y2同理
y = sigma * np.random.randn(1, num) + mu
y = ([i for item in y for i in item])
data = np.zeros((num, 2))
for i in range(num):
data[i] = np.array([x[i], y[i]])
f = open('../data_normal.csv', 'w', encoding='utf-8', newline="")
csv_write = csv.writer(f)
for d in data:
csv_write.writerow(d)
print(data)
return data
# 用户按集群分布
def generateGroupDistribution(num):
centers = [[500, 500], [1600, 400], [700, 1200], [1400, 1500]]
sigma = 100 # 有关于正态分布的值σ
group_num = 4
x_ = []
y_ = []
for i in range(group_num):
number = int(num / group_num)
print(centers[i])
x = sigma * np.random.randn(1, number) + centers[i][0]
y = sigma * np.random.randn(1, number) + centers[i][1]
x_.extend([i for item in x for i in item])
y_.extend([i for item in y for i in item])
data = np.zeros((num, 2))
for i in range(num):
data[i] = np.array([x_[i], y_[i]])
f = open('../data_group.csv', 'w', encoding='utf-8', newline="")
csv_write = csv.writer(f)
for d in data:
csv_write.writerow(d)
print(data)
return data
def generateNormal(mean, sigma):
x = sigma * np.random.randn(1) + mean
return x
# 从csv文件读用户位置
def getUsers(filename):
data = pd.read_csv(filename, header=None)
list = data.values.tolist()
array = np.array(list)
return array
def getDistanceFromCenter(user, x, y):
return math.sqrt((user[0] - x) ** 2 + (user[1] - y) ** 2)
def draw(data):
plt.figure(num=1, figsize=(10, 10))
x = data[:, 0]
y = data[:, 1]
plt.scatter(x, y)
plt.xlim(0, 2001)
plt.ylim(0, 2001)
ax = plt.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
# x1 = np.linspace(300, 700, 500)
# center1 = 500 + np.sqrt(200 ** 2 - (x1 - 500) ** 2)
# center2 = 500 - np.sqrt(200 ** 2 - (x1 - 500) ** 2)
# plt.plot(x1, center1,c='b')
# plt.plot(x1, center2,c='b')
# x2 = np.linspace(200, 800, 500)
# center21 = 500 + np.sqrt(300 ** 2 - (x2 - 500) ** 2)
# center22 = 500 - np.sqrt(300 ** 2 - (x2 - 500) ** 2)
# plt.plot(x2, center21, c='r')
# plt.plot(x2, center22, c='r')
# x3 = np.linspace(100, 900, 500)
# center31 = 500 + np.sqrt(400 ** 2 - (x3 - 500) ** 2)
# center32 = 500 - np.sqrt(400 ** 2 - (x3 - 500) ** 2)
# plt.plot(x3, center31, c='g')
# plt.plot(x3, center32, c='g')
# model = KMeans(n_clusters=5, random_state=0).fit(data)
# center = model.cluster_centers_
# for c in center:
# plt.scatter(c[0], c[1],s=200,marker='p')
return plt
if __name__ == '__main__':
# data=generate_in_file(30,"./data3.csv")
list=getUsers("./data3.csv")
# print(list)
# data=generateGroupDistribution(100)
# list = getUsers("../data_group.csv")
draw(list).show()
f_c = 2 * 10 ** 9
noise = -140 #森林噪声(dbm)
N0=-117 #视距链路噪声(dbm)
pmax=0.1
B_max=2.5
snr_thre=1
R_min=0.3 #0.1 1.2才能传视频
G_max=20
min_range=0
max_range=2000
min_height=50
max_height=150
speed=40
time_slot=10 #基本间隔
run_time=5
P0=580.65
P1=790
# P0=199.4
# P1=88.65
U=200
vr=7.2
A=0.79
v=1#用户速度
r_change_slot=60#60s
import numpy as np
# aircraft weight in Newton
W = 100
# air density
rho = 1.225
# blade radius in meter
R = 0.5
# blade angular velocity in rad/s
omega = 400
# Fuselage equivalent flat plate area in m^2
S_FP = 0.0151
# number of blades
b = 4
# blade or aerofoil chord length
c = 0.0157
# incremental correction factor to induced power
k = 0.1
# profile drag coefficient
delta = 0.012
# rotor disc area
A = np.pi * R**2
# tip speed of the rotor blade
U_tip = omega * R
# rotor solidity
sigma = b * c / (np.pi * R)
# fuselage drag ratio
d_0 = S_FP / sigma / A
# mean rotor induced velocity in hover
v_0 = np.sqrt(W / (2 * rho * A))
# hovering blade profile power
# P_0 = (delta / 8) * rho * sigma * A * omega**3 * R**2
P_0=580.65
# hovering induced power
P_i = (1 + k) * (W**(1.5)) / np.sqrt(2 * rho * A)
print(P_0,P_i)
# flight speed
# V_kmh = np.linspace(1, 100, 20)
# V = V_kmh / 3.6
# V=V_kmh
# propulsion power
# P_origin = P_0 * (1 + (3 * V**2) / (U_tip**2)) + P_i * (np.sqrt(1+(V**4/(4*(v_0**4))))-V**2/(2*(v_0**2)))**0.5 + (0.5 * d_0 * rho * sigma * A * V**3)
# print(P_origin)
\ No newline at end of file
902,280
652,886
635,96
946,288
668,947
835,969
197,709
295,717
285,112
988,589
314,375
763,913
840,328
383,610
297,882
897,356
978,371
660,94
122,240
712,790
517,522
664,35
522,76
37,154
150,541
51,54
680,52
146,251
670,601
89,395
592,302
179,181
105,429
399,625
184,24
116,72
918,650
564,280
1507,121
1326,1837
1283,544
197,1742
681,1491
1530,1252
703,1380
335,1732
107,1760
832,658
1031,1152
34,1436
172,1881
871,162
1042,801
1107,1613
764,1894
1745,1696
1009,1818
1925,1669
1768,1455
1450,864
310,1879
934,691
696,176
1335,1028
1590,157
1408,1289
1624,1750
337,826
379,347
553,1551
662,1800
1467,988
1102,1009
565,1128
801,1014
862,906
953,1215
1079,708
1800,1236
1270,1679
1177,1737
761,1091
1184,541
1643,310
1400,792
1966,637
498,1651
380,115
1365,1508
1060,264
1933,316
1200,619
1675,1259
228,1465
574,715
599,379
5,1624
775,1520
1053,461
1572,1038
1571,151
1714,103
1311,1902
997,1879
1151,86
1041,414
1583,29
1257,1490
412,1404
1404,976
994,139
1735,1601
1258,916
1695,328
1520,922
943,349
648,1322
1340,443
import numpy as np
from matplotlib import pyplot as plt
plt.style.use('seaborn-whitegrid')
import matplotlib as mpl
plt.rcParams['font.family'] = 'Times New Roman'
mpl.rcParams['axes.labelsize'] = 14
mpl.rcParams['legend.fontsize'] = 12
from matplotlib import rcParams
from matplotlib.font_manager import FontProperties
font_path = 'D://font//SimHei.ttf' # 替换为实际的字体文件路径
font_prop = FontProperties(fname=font_path)
# 全局设置字体
rcParams['font.family'] = font_prop.get_name()
rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# plt.rcParams['font.family'] = 'Times New Roman'
rcParams['font.serif'] = ['Times New Roman'] # 设置英文和数字字体为Times New Roman
# plt.rcParams['font.sans-serif'] = ['SimHei']
def drawResultAndIter(resultAndIter):
f, ax = plt.subplots(1, 1)
plt.plot(resultAndIter)
ax.set_xlabel('iteration')
ax.set_ylabel('fitness')
plt.show()
def draw_compare(resultArr):
labels=['Proposed IPSO','SPSO','PSO',"DE"]
markers=[".",'^','s','o']
line = ['-', '--', ':', '-.']
for i in range(len(resultArr)):
index=round(i/2)
plt.plot(resultArr[i], label=labels[i], linestyle=line[i],)
# 设置图例
plt.legend()
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('Number of iterations')
plt.ylabel('Fitness value')
# 显示图形
plt.show()
def draw_particle_num_iteration():
result1=[-468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.1551972601262, -468.1551972601262, -468.1551972601262, -468.1551972601262, -468.1551972601262, -468.1551972601262, -468.1551972601262, -468.0436266805678, -468.0436266805678, -468.0436266805678, -468.0436266805678, -461.65308302559686, -452.8888321326548, -401.59790153071805, -385.28811413225645, -382.4242776330168, -382.0262087928394, -378.0637949107663, -378.0637949107663, -372.8723066103669, -370.02164942729524, -367.647900225791, -367.647900225791, -367.647900225791, -365.07942447331345, -363.73763455243994, -361.3785664974921, -361.1325332089312, -358.2999971860925, -356.60219219164526, -355.2456615220885, -351.74190252287457, -351.51801238698283, -349.3988922312556, -348.0076691052095, -347.56430609242295, -344.8834863035785, -344.8834863035785, -344.47610281940064, -344.47610281940064, -343.40803405311647, -342.8429136352076, -342.1260442097806, -341.7655717202232, -341.7655717202232, -341.7655717202232, -341.7655717202232, -341.7655717202232, -341.7655717202232, -341.7655717202232, -341.7655717202232, -341.6013796163709, -341.46867293943427, -340.71606307177956, -340.71606307177956, -340.5245644836425, -340.5245644836425, -340.494723260078, -340.1992378680266, -340.1965721861093, -340.1686083217223, -340.02149387155004, -339.86521061017726, -339.3855932208739, -338.8985315339182, -338.8621918114104, -338.51612765899216, -338.46147524082403, -337.93380585347035, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823, -337.7706484447823]
result2=[-468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -462.38918872737554, -446.7201152518535, -374.9089810819999, -353.21345810702525, -353.21345810702525, -353.21345810702525, -353.21345810702525, -351.0239332341789, -350.5252500168065, -345.2519014763718, -345.2519014763718, -345.2519014763718, -341.25016754173606, -341.25016754173606, -340.78028482916557, -340.23735852096337, -339.54165088137324, -337.9304472931558, -337.9304472931558, -337.34690873042325, -337.34690873042325, -337.34690873042325, -337.23051081201385, -335.2943266906536, -335.2943266906536, -335.2943266906536, -335.2943266906536, -335.2943266906536, -335.2040143425279, -335.1504084053742, -334.4255463121278, -334.3708934855804, -334.3708934855804, -334.3708934855804, -334.3708934855804, -334.0968365456712, -334.0084860170438, -333.98218232414786, -333.5739670100702, -333.5739670100702, -333.5739670100702, -333.35779414221076, -333.10896959934286, -333.0870744371223, -333.0870744371223, -332.98800195750005, -332.86794150136444, -332.86794150136444, -332.86794150136444, -332.86405599181023, -332.53382174113653, -332.53382174113653, -332.5266649944851, -332.5266649944851, -332.397712869248, -332.2493305238271, -332.2493305238271, -332.17939507765624, -332.1073320511023, -331.9062571633988, -331.9062571633988, -331.5917943579286, -331.52541977712, -331.3998050150476, -331.38488210674757, -331.38488210674757, -331.2635257484103, -331.1970373158113, -331.1164338049966, -330.9608422914324, -330.928103777802, -330.928103777802, -330.8474350894784, -330.81907231644345, -330.7616393730558, -330.7272217317713, -330.59536395090504, -330.51086666129413, -330.4113619966248, -330.17181367583834, -329.98307637249064, -329.8407523772944, -329.8407523772944, -329.8407523772944, -329.8407523772944, -329.69627956288065, -329.6035907577809]
result3=[-468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -462.5417019072906, -452.9328610289716, -452.9328610289716, -452.9328610289716, -435.9161914810394, -431.8644714313303, -411.6643212172572, -360.06176418966726, -350.2930046373964, -346.25410814760437, -341.04387526991843, -332.59345245459883, -332.59345245459883, -332.59345245459883, -332.59345245459883, -332.59345245459883, -332.59345245459883, -332.59345245459883, -332.5339614853902, -332.05557122844266, -331.5483077511296, -331.49830864131627, -331.3010012148939, -331.2214978786753, -331.2214978786753, -331.1470643249009, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.43602237317333, -330.41126067997277, -330.1147720465841, -330.05009848709244, -330.05009848709244, -329.9742546449886, -329.9680955263456, -329.9680955263456, -329.9058817192863, -329.80335915642974, -329.72398979541265, -329.72398979541265, -329.72398979541265, -329.7001947611068, -329.657907434906, -329.5536923074401, -329.4506520638687, -329.43481400161227, -329.4299981161304, -329.39302331005354, -329.39302331005354, -329.39302331005354, -329.39302331005354, -329.39302331005354, -329.39302331005354, -329.3359167066494, -329.2949620043947, -329.25115220289047, -329.1813159212933, -329.017580099964, -328.9263641518387, -328.9263641518387, -328.9263641518387, -328.85862049894195, -328.85862049894195, -328.83837983933523, -328.83837983933523, -328.83837983933523, -328.68054432382024, -328.64547133959, -328.6005881503028, -328.5942056807135, -328.5942056807135, -328.5510393597613, -328.5049481966571, -328.4554701799052, -328.4263495199075, -328.4165781933845, -328.4165781933845, -328.4049995593526, -328.4049995593526, -328.38554075679485, -328.3817441098075, -328.3697870134776]
result4=[-468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -468.7054208305359, -439.95863043746203, -439.95863043746203, -380.8325586854756, -374.8986980867377, -370.80995620842435, -364.57132554652804, -357.10081704846436, -353.4342794179789, -351.7507205895996, -351.7507205895996, -349.1755921284063, -344.2505661090243, -343.8227644429094, -341.8747478205176, -341.51754540258145, -336.857509158093, -333.05472673444325, -333.05472673444325, -333.05472673444325, -332.6418514566392, -332.6418514566392, -331.70813177769526, -331.69080097411694, -331.31839707056224, -330.9749805391616, -330.9749805391616, -330.9749805391616, -329.49982161081306, -329.0109791791206, -329.0109791791206, -328.85906327718465, -328.85906327718465, -328.85906327718465, -328.17789679927876, -328.17789679927876, -328.17789679927876, -328.17789679927876, -328.17789679927876, -328.08037619933725, -328.08037619933725, -328.08037619933725, -328.08037619933725, -328.00487733187686, -327.9248872779793, -327.9248872779793, -327.86396333668694, -327.7469531220371, -327.71502338967986, -327.584844761086, -327.56303389177185, -327.4711956622603, -327.32673454376675, -327.32673454376675, -327.32673454376675, -327.32673454376675, -327.31980416224707, -327.31980416224707, -327.2931497487489, -327.1826910500803, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435, -327.0992806917435]
result=[]
result.append(result1)
result.append(result2)
result.append(result3)
result.append(result4)
labels = ['N=20', 'N=30', 'N=40', "N=50"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.']
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i], linestyle=line[i], )
# 设置图例
plt.legend()
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('Number of iterations')
plt.ylabel('Fitness value')
# 显示图形
plt.show()
def draw_particle_num():
y=[-337.7706484447823,-329.6035907577809,-328.3697870134776,-327.0992806917435,-327.03770836,-326.66154288,-326.94715888,-326.51317971]
y=[-84.44711868595805, -76.46606150182288, -74.79680270185938,-68.5327703374397, -49.78739347833529, -48.85075425561384, -48.502744564027395, -48.5514696272856, ]
y=[y[i]-200 for i in range(len(y))]
x=[i for i in range(30,110,10)]
plt.plot(x,y,marker="o")
plt.xlabel('粒子数目', fontsize=14, fontproperties=font_prop)
plt.ylabel('适应度', fontsize=14, fontproperties=font_prop)
# plt.xlabel('Number of particles')
# plt.ylabel('Fitness value')
# 显示图形
plt.show()
def draw_iteration_num():
y = [-107.42648703395444, -67.73900895103472, -48.40847296622629, -48.2503277828317, -48.233]
y = [y[i] - 200 for i in range(len(y))]
x=[i for i in range(100,350,50)]
plt.plot(x,y,marker="o")
plt.xlabel('最大迭代次数', fontsize=14, fontproperties=font_prop)
plt.ylabel('适应度', fontsize=14, fontproperties=font_prop)
# plt.xlabel('Number of iterations')
# plt.ylabel('Fitness value')
# 显示图形
plt.show()
def draw_iteration_time():
y = [9.583384275436401, 14.269200563430786, 19.240224361419678, 23.800528287887573, 28.650663375854492]
x=[i for i in range(100,350,50)]
plt.plot(x,y,marker="o")
plt.xlabel('Number of iterations')
plt.ylabel('Running Time')
# 显示图形
plt.show()
def draw_particle_time():
y=[1.8,2.48,3.25,4.45,4.77,6.14,6.35,7.14]
y = [10.263979434967041, 13.735095024108887, 17.127366304397583, 20.233509302139282, 23.74123501777649,
27.01459264755249, 30.504220008850098, 33.78894329071045]
x=[i for i in range(20,100,10)]
plt.plot(x,y,marker="o")
plt.xlabel('Number of particles')
plt.ylabel('Running Time')
# 显示图形
plt.show()
def draw_time():
# 示例数据
categories = ['N=20','N=30','N=40',"N=50"]
values = [1.80, 2.48, 3.25,4.45]
# 画柱状图
plt.bar(categories, values, width=0.3)
# 添加标题和标签
plt.xlabel('Number of Particles')
plt.ylabel('Running Time')
# 显示图形
plt.show()
def draw_avg_and_optimal():
result1=[12654.373658372977, 12698.124852392339, 12698.124852392339, 12698.124852392339, 12698.124852392339,
12784.627585245535, 12855.814525865842, 12913.558426647263, 12915.934247153287, 12977.984795175113,
13015.281920353611, 13093.009701299674, 13184.014386350036, 13184.014386350036, 13195.571585956532,
13199.161357718096, 13201.053736599482, 13201.42906070698, 13202.349502554316, 13204.101140958395,
13204.767219692543, 13205.579178477517, 13205.635955778602, 13205.849472375572, 13206.437483463262,
13206.437483463262, 13206.437483463262, 13207.042267408628, 13207.357492661287, 13207.462522470576,
13208.206733697672, 13208.502035934924, 13208.61477213886, 13208.877485925652, 13208.877485925652,
13208.877485925652, 13208.877485925652, 13208.878221427602, 13208.878221427602, 13208.895267093354,
13208.898922662087, 13208.898922662087, 13208.905277714153, 13208.905277714153, 13208.905277714153,
13208.909477417874, 13208.918432585331, 13208.926698051593, 13208.930765858488, 13208.930765858488,
13208.939498443095, 13208.947104395516, 13208.949829485067, 13208.951127530083, 13208.951127530083,
13208.951127530083, 13208.951127530083, 13208.95135826988, 13208.954723917783, 13208.960041085564,
13208.96022229033, 13208.960291734877, 13208.960563779741, 13208.960563779741, 13208.960624465715,
13208.960815668914, 13208.960921481228, 13208.960921481228, 13208.960921481228, 13208.960921481228,
13208.960921481228, 13208.960921481228, 13208.960921481228, 13208.960933079697, 13208.961060563277,
13208.961195104495, 13208.961509339404, 13208.961535809209, 13208.961535809209, 13208.961535809209,
13208.961639650932, 13208.961639650932, 13208.961639650932, 13208.961657578848, 13208.961657578848,
13208.961657578848, 13208.961657578848, 13208.961657578848, 13208.961657578848, 13208.961657578848,
13208.961657578848, 13208.961657578848, 13208.961657578848, 13208.961657578848, 13208.961657578848,
13208.961657578848, 13208.961657578848, 13208.96174204845, 13208.96174204845, 13208.96174204845, 13208.96174204845,
13208.96174204845, 13208.96174204845, 13208.96174204845, 13208.96179504098, 13208.96179504098, 13208.96179504098,
13208.961806614338, 13208.961808357684, 13208.961808357684, 13208.961842407056, 13208.961842407056,
13208.961842407056, 13208.961842407056, 13208.961842407056, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826, 13208.961845475826,
13208.961845475826, 13208.961845475826, 13208.961845475826]
result2=[12546.34565841827, 12588.540773407485, 12588.540773407485, 12598.352279425277, 12673.134649139105, 12716.852844543462, 12747.322963571929, 12851.947514990834, 12915.249566920551, 12933.688899372763, 12997.187934813499, 13032.85057942456, 13074.49677442072, 13126.761638032529, 13159.642738831892, 13164.285318389148, 13170.441412834045, 13182.695884519884, 13185.282166215922, 13185.282166215922, 13188.825480810741, 13191.035806816944, 13191.035806816944, 13191.035806816944, 13191.035806816944, 13194.336900189935, 13195.770247958522, 13200.766016617516, 13201.909027658054, 13205.213054841497, 13206.545407301941, 13206.545407301941, 13206.545407301941, 13206.545407301941, 13207.13137632963, 13207.13137632963, 13207.313354291893, 13207.313354291893, 13207.313354291893, 13207.313354291893, 13207.313354291893, 13207.317949948818, 13207.317949948818, 13207.317949948818, 13207.56742478775, 13207.56742478775, 13207.806281086981, 13207.823541195374, 13207.823541195374, 13207.863563589388, 13207.902584614356, 13207.974328856655, 13207.988281766904, 13208.056089638689, 13208.124528444583, 13208.156529315398, 13208.439971127023, 13208.532743539787, 13208.659632933042, 13208.805319679213, 13208.862881246772, 13208.867993532038, 13208.889814004358, 13208.889814004358, 13208.899761094804, 13208.925243458436, 13208.928788816103, 13208.939269422726, 13208.939269422726, 13208.939269422726, 13208.941466589933, 13208.942273739422, 13208.942273739422, 13208.943635078482, 13208.949068640786, 13208.949273623974, 13208.9509418807, 13208.953008516755, 13208.954205057998, 13208.954205057998, 13208.955928547657, 13208.955960618347, 13208.958697914964, 13208.959093494648, 13208.960002711334, 13208.961032886162, 13208.961708363679, 13208.962160791067, 13208.962321279187, 13208.962405462013, 13208.962419118237, 13208.962503751816, 13208.962526006457, 13208.962541901454, 13208.962555312111, 13208.962563715902, 13208.962569210189, 13208.962577439785, 13208.962578804047, 13208.962579819412, 13208.962581145764, 13208.962581145764, 13208.962582528713, 13208.962583365581, 13208.96258365127, 13208.962584184621, 13208.962584184621, 13208.962584280973, 13208.962584609106, 13208.962584632583, 13208.96258472418, 13208.962584755454, 13208.962584763005, 13208.962584769764, 13208.962584774892, 13208.962584776276, 13208.962584778363, 13208.96258477863, 13208.962584785186, 13208.962584797586, 13208.962584798543, 13208.962584807961, 13208.962584810099, 13208.96258481368, 13208.962584814326, 13208.962584815084, 13208.962584816052, 13208.962584816098, 13208.96258481672, 13208.96258481732, 13208.962584818146, 13208.962584818579, 13208.962584818913, 13208.962584819881, 13208.962584820518, 13208.96258482068, 13208.962584820847, 13208.962584821056, 13208.962584821393, 13208.962584821558, 13208.962584822078, 13208.962584822288, 13208.962584822346, 13208.96258482235, 13208.962584822395, 13208.96258482241, 13208.962584822426, 13208.962584822435, 13208.962584822442, 13208.962584822446]
result=[]
result.append(result2)
result.append(result1)
labels = ['Proposed IPSO', 'IPSO-Convex',]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.']
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i],marker=".", linestyle=line[i], )
# 设置图例
plt.legend()
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('Number of iterations')
plt.ylabel('Fitness value')
# 显示图形
plt.show()
def draw_different_scheme():
result=[]
r1 = [891.2325611996497, 1600.5425924965132, 1775.4870815806812, 1661.4116199224782, 1652.7495185102612,
1710.8784073287254, 1632.2869853821032, 1405.6533507661727, 1650.9536213892259, 1658.1079792799283,
1624.144480374085, 1545.76445338581, 1639.1266120258867, 1127.2930875942645, 1317.1395738824897,
1345.105710390593, 1378.5232814712679, 1327.0724268995493, 1330.9249552627593]
r2 = [891.2325611996497, 883.715113526627, 876.3959553809046, 830.7304507711245, 845.0421291362111,
827.2501812000526, 814.8217899127849, 812.3184790554467, 842.9970828342944, 814.2846787891641,
802.4874927983169, 782.0437417323735, 806.7063928223102, 786.5781581157238, 781.5375637858187,
775.6115826850452, 779.9561019378333, 758.7242396016157, 774.6145659301196]
r3 = [891.2325611996497, 1561.6473796943978, 1696.133036433594, 1576.2258342093562, 1612.7704168093424,
1666.1107731684942, 1590.5964927045738, 1355.3867322689455, 1616.717308910885, 1648.8909657658814,
1602.6547257313946, 1533.6937236070994, 1612.2631107899372, 865.4559944925546, 989.8355164496194,
947.8109554579601, 956.4500273954962, 943.496583620515, 951.8076756728141]
r4 = [891.2325611996497, 1562.4932623722132, 1439.563234892769, 1333.67939697328, 1375.433960883068,
1396.9313906196946, 1362.5403862412616, 1355.5740012398287, 1369.3279235802177, 1390.5501310784725,
1273.6471170780565, 1258.8546891420726, 1287.0312789124978, 1062.1383584131474, 1101.7900422155617,
1069.7977380322025, 1104.3686356795185, 1102.2059669514304, 1055.6203262924575]
r1=[r1[i]+30 for i in range(len(r1))]
r1 = [1360.7607912987135, 1504.358556431442, 1510.358556431442, 1530.762198775177, 1560.4967054945619,
1554.284066114814, 1545.178232947664, 1513.5062187721946, 1533.2359261572783, 1542.3607986592804,
1530.9772604314603, 1520.9763513132932, 1500.3421314596987, 1486.8508382122334, 1477.5046561493104,
1495.2388029555345, 1488.0705547859009, 1498.5823144700644, 1505.1972321392159]
r2 = [1360.7607912987135, 1342.6868397918622, 1351.076942156944, 1348.6967607676631, 1305.7697309059433,
1334.0079380535115, 1340.631676810195, 1264.0794070260333, 1250.2755715166297, 1259.0359655749717,
1235.7365818847247, 1210.8540231993932, 1187.0700864417918, 1250.973520760966, 1272.2990981114065,
1275.9274300716181, 1283.9165890909994, 1339.8944398117947, 1330.1369541735082]
r3 = [1360.7607912987135, 1438.4860339730903, 1433.5506808753112, 1442.0532937881321, 1433.5791765209397,
1451.397747456012, 1447.1476698317256, 1500.2645132840282, 1498.8871320400963, 1487.5912202083084,
1469.1515288455548, 1450.0951590515783, 1438.6063295488057, 1393.9031709762176, 1389.6028980434648,
1372.8642855567707, 1391.0126906087135, 1448.7421722224726, 1481.6461095049337]
r4 = [1360.7607912987135, 1451.6434679001545, 1337.2997902927973, 1436.0056930217063, 1393.9351761181565,
1378.9842033338696, 1394.1325433707088, 1393.486592169153, 1410.2590539230744, 1390.8296176899803,
1352.7301334989197, 1311.1561049824397, 1316.9231732129626, 1275.8644932462012, 1360.7775553809722,
1309.3802794556834, 1427.9778272286399, 1457.7546681216156, 1444.1114416435776]
# r1 = [1286.6258869799801, 1367.8335970782923, 1370.9156946669054, 1190.2697139694317, 1234.1949959094025,
# 1193.3778898014343, 1160.8864974917155, 1336.8872931650062, 1311.4039803391463, 1268.1415121519738,
# 1317.5417253995151, 1280.2718476783346, 1226.494604838992, 995.2957915789626, 1089.6418913213079,
# 1023.4517741824707, 1017.705364175426, 1027.116479504571, 1017.39607025769]
# r2 = [1286.6258869799801, 1283.76285107334, 1318.2135565850044, 1262.4073164271836, 1260.8977079809658,
# 1207.564228057728, 1206.0637537689183, 1182.7444361110997, 1125.2960116466227, 1123.038549466862,
# 1108.173947038534, 1068.855543273497, 1060.274183565858, 1109.8721890034105, 1037.0959548032442,
# 1063.7999281817351, 1069.9828898077806, 1093.0571131724482, 1139.914227185953]
# r3 = [1286.6258869799801, 1254.6578857735883, 1303.7174190032174, 1245.8526855673767, 1242.9613969587185,
# 1187.6155855632373, 1163.9606150553589, 1395.8359771055698, 1386.4663039624209, 1351.5367014610288,
# 1308.4208894201272, 1277.68240382242, 1201.5247356257541, 1068.518227152022, 1107.4848271036894,
# 1063.9756350196692, 1088.0386581017867, 1111.9907911161165, 1124.5795026010292]
# r4 = [1286.6258869799801, 1249.2181896049422, 1163.7903208533064, 1188.869978737665, 1383.4490363213624,
# 1349.3116465797877, 1212.5737760660265, 1274.364322759652, 1282.4006158902628, 1297.3844780763218,
# 1278.0833328086255, 1270.383809592912, 1298.801571131647, 1035.767446588172, 1100.0204682760864,
# 946.6780106193855, 1119.8578241105774, 1047.6688352210092, 1214.6636303350917]
r1 = [1309.9150756787853, 1416.892875704836, 1491.7204139848134, 1472.4811364054835, 1328.9953030640863,
1375.5525391191088, 1381.469568013049, 1438.8066828217484, 1440.5294945390162, 1398.781282349261,
1389.7204426094881, 1391.582227742863, 1452.4138776684595, 1323.5424116360987, 1410.0806595425895,
1438.0834754390123, 1346.6737372833456, 1352.629728558739, 1278.6901707524291]
r2 = [1309.9150756787853, 1274.1821785177617, 1283.8936284069239, 1276.8534355639592, 1261.270157553835,
1258.743220374898, 1276.4354038795307, 1294.0537868748556, 1242.1760975771713, 1203.940030077654,
1207.1088097362338, 1168.499524931428, 1200.992324882969, 1156.5264699810139, 1195.349363943187,
1183.2185323406943, 1163.0761396238697, 1158.5092457877918, 1148.1147267507092]
r3 = [1309.9150756787853, 1208.8190179435717, 1218.611774388484, 1214.5444264177877, 1178.3854772115626,
1194.005756279548, 1226.7678720865588, 1341.8818162828602, 1351.3791707199896, 1307.622278667928,
1206.0719649783168, 1195.973179687433, 1237.0042988196824, 1283.6549540415801, 1301.1697597475359,
1328.5812965025991, 1230.6529116061113, 1267.6075201936771, 1259.667925239849]
r4 = [1309.9150756787853, 1267.5178849859583, 1197.625520275931, 1220.7621322596258, 1218.8308339081993,
1307.700811299275, 1235.3311162243288, 1333.4524734380068, 1380.728512990628, 1312.3471665270324,
1302.7946145288183, 1262.1746862054267, 1163.9827334841368, 1218.9301065014429, 1119.9205697647878,
1109.450331395668, 1148.4201501743064, 1104.6236345008238, 1151.4041048886943]
result.append(r1)
result.append(r2)
result.append(r3)
result.append(r4)
labels = ['Proposed scheme', 'FDDR',"FRDD","SDDDR","FDFR"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.']
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i],marker=".", linestyle=line[i%4], )
# 设置图例
plt.legend()
# 设置 x 轴范围
plt.xlim(0, 19)
# 设置 x 轴刻度间距
plt.xticks(np.arange(0, 19, 1))
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('time slots')
plt.ylabel('System Energy Efficiency')
# 显示图形
plt.show()
def draw_different_scheme_satisfaction():
r1 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
r2 = [1.0, 1.0, 1.0, 1.0, 1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.8666666666666667, 0.8666666666666667,0.8666666666666667, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333,0.9333333333333333, 0.9333333333333333]
r3 = [1.0, 0.8, 0.8666666666666667, 0.7333333333333333, 0.6, 0.6, 0.6, 0.6666666666666666, 0.6666666666666666,
0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666,
0.7333333333333333, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333]
r3=[0.9333333333333333, 0.8666666666666667, 0.8666666666666667, 0.8, 0.8666666666666667, 0.8666666666666667, 0.6666666666666666, 0.7333333333333333, 0.6666666666666666, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333, 0.6, 0.6, 0.6, 0.7333333333333333, 0.7333333333333333, 0.6666666666666666]
r4 =[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
result=[]
result.append(r1)
result.append(r2)
result.append(r3)
result.append(r4)
labels = ['Proposed scheme', 'FDDR', "FRDD", "SDDDR"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.']
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i], marker=".", linestyle=line[i], )
# 设置图例
plt.legend()
# 设置 x 轴范围
plt.xlim(0, 19)
plt.ylim(0, 1.1)
# 设置 x 轴刻度间距
plt.xticks(np.arange(0, 19, 1))
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('time slots')
plt.ylabel('Communication Satisfaction')
# 显示图形
plt.show()
def draw_different_scheme_satisfaction_g():
g1 = [0.9333333333333333, 1.0, 1.0, 1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
g2 = [0.9333333333333333,0.9333333333333333, 0.8666666666666667, 0.8666666666666667, 0.7333333333333333, 0.8666666666666667, 0.8666666666666667, 0.8, 0.8, 0.8, 0.8,0.8,0.8, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333, 0.7333333333333333]
g3 = [0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333,
0.9333333333333333, 0.9333333333333333, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
g4 = [0.9333333333333333, 0.9333333333333333, 1.0, 1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333,
0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333,
0.9333333333333333, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
result = []
result.append(g1)
result.append(g2)
result.append(g3)
result.append(g4)
labels = ['Proposed scheme', 'FDDR', "FRDD", "SDDDR"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.']
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i], marker=".", linestyle=line[i], )
# 设置图例
plt.legend()
# 设置 x 轴范围
plt.xlim(0, 19)
plt.ylim(0, 1.1)
# 设置 x 轴刻度间距
plt.xticks(np.arange(0, 19, 1))
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('time slots')
plt.ylabel('Localization Satisfaction')
# 显示图形
plt.show()
def draw_slot_compare():
result=[[1299.3570374805256, 1018.2689354125052, 1018.7746187555389, 1018.7090809119278, 1018.7921029944429, 1018.7747407295528, 1014.0268093958708, 955.1485599884267, 1010.122365171568, 1020.8539679402211, 1000.3460924396524, 983.0185921930898, 1001.9949859271056, 1018.9331241289651, 970.4297703762156, 993.0521832206775, 1016.5811537560148, 1018.9873083907402, 1019.2482751292833], [1299.3570374805256, 955.5638632401538, 929.1895124643144, 1018.0494054439747, 988.687790660067, 1014.9786686490513, 985.0628829209201, 955.245799658351, 964.8150161949783, 1016.8795883435956, 1029.1624089665993, 958.8560836681085, 940.1959644088128, 1017.7181699493798, 996.7439352037351, 1019.0622835757795, 953.0264231536681, 990.1194871093758, 936.475808278264], [1299.3570374805256, 1017.7055602458133, 994.5004504254122, 988.7818917521337, 963.7427293398699, 944.8095582419897, 957.067108495399, 979.2490627807105, 962.1780450751002, 972.6343983805053, 1033.670255895614, 1025.8087371668992, 1012.0890135564214, 1018.8621442779979, 997.7653759888321, 983.1521779007888, 1019.0413348846395, 952.1558224883776, 954.0513973945293], [1299.3570374805256, 1018.268935175176, 995.8087474344729, 990.7037441026249, 988.9720094787026, 1018.2082868895291, 991.2212647557297, 1007.3294233982771, 1023.4907490021022, 962.2016915179671, 978.082412079636, 971.9443413219389, 950.544126069441, 991.5541051435569, 970.2309596521279, 956.4666170406782, 948.7161327407202, 1016.3077509070416, 951.177660597132], [1299.3570374805256, 1018.2678493263568, 995.8793818124047, 990.7353724358787, 988.9579331778344, 977.4563955524744, 948.138125125953, 940.1866480861797, 939.896987716489, 966.9714716770775, 977.9872631465986, 981.3763322671907, 953.2065258930505, 954.7034235537245, 941.9163884545118, 911.8688837942306, 1014.9706335047204, 962.8668098930724, 962.8936809921414], [1299.3570374805256, 1018.2641577541285, 995.6107868624795, 990.5609842586114, 988.8080035551752, 977.5289875009772, 987.062056661658, 1001.4288625814581, 1002.0194648524549, 1013.0979856081176, 1021.1332654190495, 1008.985812205421, 998.5544941276504, 1019.0165440463907, 996.7761558648857, 981.76581105948, 952.9844069104482, 950.5813821472358, 952.5575113991316]]
result=[[1266.2371306931811, 1208.1970110848779, 1388.5413771030999, 1449.3211492594298, 1278.7296859116695, 1394.8020997423594, 1277.0419429965377, 1390.938789270484, 1242.2784932270065, 1299.1403812739584, 1343.3438613772796, 1271.3047123664858, 1360.5244631435555, 1373.0087316153933, 1337.9025145389612, 1246.4898869779095, 1271.268615295663, 1274.8389048686095, 1294.7043948698858], [1266.2371306931811, 1406.4053908025305, 1386.3948299231622, 1343.9738760031157, 1355.1049050221227, 1289.1121931980883, 1325.0411775700877, 1293.3711003720966, 1260.7116417295094, 1280.2046143335149, 1291.5332380239224, 1267.668665036152, 1258.7809434756568, 1298.1885204435066, 1281.2588067273894, 1226.783457692276, 1265.6585362930812, 1228.5649383150392, 1235.2366789947205], [1266.2371306931811, 1459.2377906025747, 1399.1481423528255, 1407.0479891139805, 1393.2985875457243, 1365.2759676236094, 1405.3843774554634, 1393.0831668132623, 1347.0016373806957, 1383.2507653287616, 1383.6773941394276, 1333.0012478223978, 1355.7453965574236, 1375.1262423053781, 1340.4553271028797, 1312.293596829912, 1337.4301415139469, 1299.9196215691334, 1291.3508785126078], [1266.2371306931811, 1299.2937054793135, 1289.2294400967069, 1270.3518378836493, 1283.6826975391223, 1251.9584811851028, 1300.9102664744667, 1300.7623149451686, 1270.200639438493, 1379.7242476104914, 1385.1729624220902, 1333.1817837168815, 1358.3209681033616, 1374.6915149924023, 1341.6605427044183, 1312.6018581922144, 1338.0302678067583, 1302.694799756844, 1290.8108804244478], [1266.2371306931811, 1490.564058426475, 1440.0570065948891, 1442.3089169422494, 1420.9777075809266, 1384.2782257175857, 1429.165058076329, 1428.6988122438504, 1368.8089906533137, 1379.8167511341449, 1398.755712106024, 1239.5144955291623, 1248.7796378308121, 1297.4654883707099, 1270.390574926196, 1238.3658074226698, 1339.9910539027328, 1304.1085082220372, 1291.9117736602407], [1266.2371306931811, 1423.3556637618335, 1389.1964781162253, 1359.9260585580066, 1354.6879542790905, 1321.5951768363047, 1296.2235155964663, 1344.3296638979364, 1300.688020163772, 1337.2339591770772, 1360.9276520775384, 1304.7456839648794, 1308.977890771906, 1267.0172069163502, 1259.0806657358025, 1209.1935171666776, 1244.5821370627616, 1212.219266263685, 1219.981564246517]]
result=[[1243.1292899707744, 1437.952652644042, 1404.129429807801, 1466.6561212317413, 1374.0159505575298, 1452.6428603103568, 1397.459450600962, 1399.8844505505783, 1470.0980237579495, 1295.0367256348368, 1361.3922691520825, 1363.4274339999395, 1361.4072763816678, 1076.9639237886965, 1104.2826074042205, 1086.6656395129896, 1040.3429157087257, 1069.766593398577, 1115.154068275955], [1243.1292899707744, 1425.4972310329304, 1389.3428368130587, 1411.0213767676132, 1385.8925766143877, 1192.706575462344, 1158.9517341510357, 1400.79861127426, 1401.193377096315, 1391.5525629638498, 1447.00363081752, 1443.8717565982536, 1428.0587282636402, 1085.7538448145217, 1082.9395433095265, 993.901212550637, 1042.7821224859217, 992.8513955694106, 1066.9082028475204], [1243.1292899707744, 1458.1370913018645, 1421.6391089791973, 1456.687034922671, 1314.8651953531012, 1322.4775385147184, 1302.1360890767032, 1406.9508800023473, 1407.967987471922, 1286.7066398777674, 1364.2055014265895, 1361.7251381027797, 1362.7759769067688, 1117.0070813655539, 1122.2662627127763, 1089.4704676134247, 1010.832594719583, 1044.4968845144244, 1130.358264542365], [1243.1292899707744, 1149.5705493403543, 1070.2521109356871, 1133.2053302483753, 1130.3165451572233, 1477.8045351260541, 1429.5155185968051, 1497.408350218828, 1514.7090480819907, 1431.0679416087846, 1321.7873006028647, 1336.9244019674877, 1332.8829642642934, 1062.8587900245789, 1053.5499170000219, 1027.973128324803, 1003.7237651426925, 1107.7093416835237, 1187.2214178430713], [1243.1292899707744, 1485.417942999133, 1439.7969186842467, 1455.9373480653976, 1444.110573249161, 1463.7136146469588, 1369.9301894806395, 1475.4018948953544, 1413.0530855233224, 1494.0054316526118, 1493.4860186797528, 1441.1293670079756, 1427.2035714898354, 1062.1427558839055, 1051.6214337643592, 1035.7292492810861, 1086.1124570548595, 1108.8914027099684, 1173.4244776069836], [1243.1292899707744, 1400.421601413154, 1316.0402497513794, 1389.468652936794, 1399.0792327125187, 1445.6104105864706, 1406.2390192122252, 1399.3889973661499, 1394.72514638148, 1270.4573990410977, 1322.6007938441278, 1316.6062169188547, 1312.4449772111304, 1137.105620137621, 1138.4493265558283, 1117.2769884563331, 1070.6899185825348, 1081.474959365313, 1089.2848425994243]]
result = [[1320.7266287079533, 1526.4679928927821, 1541.6466829006065, 1316.0512288118382, 1308.769691561029,
1448.5634616409686, 1358.3855395050696, 1340.851841032951, 1346.4610961812164, 1357.348392420678,
1287.9535324790108, 1316.4361704376345, 1374.0267354533535, 1399.3452993572366, 1427.5679524554935,
1418.8802363654247, 1366.777914314444, 1470.249489578498],
[1320.7266287079533, 1251.7706528540307, 1502.0475449248688, 1507.7822692137697, 1458.0782549932192,
1423.08421827599, 1354.8544170578027, 1337.1748022547933, 1278.1200674229299, 1275.0763785597226,
1355.6094076565782, 1318.4925528740378, 1376.7518875091102, 1398.3744645478428, 1427.8855725671706,
1418.5874180684134, 1361.5858433423568, 1364.0741129095477],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1505.714989960461, 1491.067848447097,
1444.9242334098553, 1355.6635066788222, 1337.060057536818, 1344.3605738406459, 1271.2111458249062,
1283.1608183869025, 1233.0713282236602, 1373.9231715928186, 1402.5491074934696, 1429.7021155200312,
1303.5954975318039, 1351.4742115968943, 1362.7604119346724],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1212.8283613961432, 1488.6361439452937,
1451.2911242206337, 1357.446746730729, 1341.2121206023373, 1348.6441238678733, 1357.3056760094305,
1357.7593532946837, 1319.091537706909, 1296.5049504805338, 1328.0478230069996, 1368.4574346309,
1349.0001156394105, 1414.6144318448096, 1416.61709293385],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1212.8283613961432, 1136.7619636179825,
1449.2129802147974, 1361.2099203305797, 1340.3129962365085, 1345.3708811074277, 1349.8759241335788,
1356.4013588466967, 1317.3846335900835, 1373.5168144885602, 1399.1126435652468, 1428.5314346422501,
1418.1413383087117, 1454.380799043778, 1471.5180575288075],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1212.8283613961432, 1136.7619636179825,
1132.6269691995567, 1274.9534022546165, 1265.9606268721025, 1286.434436186174, 1281.9603479206487,
1294.8951266671795, 1235.7768801649959, 1313.5938515129144, 1356.1709709499287, 1383.9221337321194,
1376.136619082958, 1424.2168584190804, 1429.717894388855]]
result=[[1320.7266287079533, 1526.4679928927821, 1541.6466829006065, 1316.0512288118382, 1308.769691561029, 1448.5634616409686, 1358.3855395050696, 1340.851841032951, 1346.4610961812164, 1357.348392420678, 1287.9535324790108, 1316.4361704376345, 1374.0267354533535, 1399.3452993572366, 1427.5679524554935, 1418.8802363654247, 1366.777914314444, 1470.249489578498],
[1320.7266287079533, 1251.7706528540307, 1502.0475449248688, 1507.7822692137697, 1458.0782549932192, 1423.08421827599, 1354.8544170578027, 1337.1748022547933, 1278.1200674229299, 1275.0763785597226, 1355.6094076565782, 1318.4925528740378, 1376.7518875091102, 1398.3744645478428, 1427.8855725671706, 1418.5874180684134, 1361.5858433423568, 1364.0741129095477],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1505.714989960461, 1491.067848447097, 1444.9242334098553, 1355.6635066788222, 1337.060057536818, 1344.3605738406459, 1271.2111458249062, 1283.1608183869025, 1233.0713282236602, 1373.9231715928186, 1402.5491074934696, 1429.7021155200312, 1303.5954975318039, 1351.4742115968943, 1362.7604119346724],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1212.8283613961432, 1488.6361439452937, 1451.2911242206337, 1357.446746730729, 1341.2121206023373, 1348.6441238678733, 1357.3056760094305, 1357.7593532946837, 1319.091537706909, 1296.5049504805338, 1328.0478230069996, 1368.4574346309, 1349.0001156394105, 1414.6144318448096, 1416.61709293385],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1212.8283613961432, 1136.7619636179825, 1449.2129802147974, 1361.2099203305797, 1340.3129962365085, 1345.3708811074277, 1349.8759241335788, 1356.4013588466967, 1317.3846335900835, 1373.5168144885602, 1399.1126435652468, 1428.5314346422501, 1418.1413383087117, 1454.380799043778, 1471.5180575288075],
[1320.7266287079533, 1251.7706528540307, 1253.2896297524624, 1212.8283613961432, 1136.7619636179825, 1132.6269691995567, 1274.9534022546165, 1265.9606268721025, 1286.434436186174, 1281.9603479206487, 1294.8951266671795, 1235.7768801649959, 1313.5938515129144, 1356.1709709499287, 1383.9221337321194, 1376.136619082958, 1424.2168584190804, 1429.717894388855]]
result=[[1328.1765246507357, 1503.4819127657738, 1413.0043866027665, 1463.0694754945252, 1411.3332686120364, 1430.8494924488095, 1348.4585284268035, 1425.5665531789396, 1434.6103288936818, 1382.0470220409627, 1400.9531567236882, 1430.8877968272081, 1388.6185194154302, 1349.9589680879892, 1331.6482975811632, 1349.4196364208437, 1333.4082035862293, 1289.1716043437505], [1328.1765246507357, 1353.1879576378208, 1405.8565440529696, 1432.7524257593964, 1401.1414708835648, 1413.2404297641222, 1383.0244353104806, 1424.8984233930191, 1431.198682113639, 1377.8356032938168, 1396.959114367267, 1431.17968510067, 1386.0419445035495, 1356.377703925818, 1332.1232554431833, 1352.6415842615386, 1334.979935409752, 1287.8872570069313], [1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1461.5691341367276, 1411.0399445665012, 1428.6282956069683, 1342.4394201899177, 1410.6593127134165, 1421.27785518321, 1379.0053611335575, 1400.2550306243324, 1433.9203792901133, 1356.75918484904, 1345.2969702372804, 1335.91205104966, 1353.492373837457, 1338.6041420862807, 1291.1214993205556], [1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1397.2181548623369, 1416.1632823180864, 1381.329183610079, 1423.0177897257574, 1381.024457636659, 1314.0230128358758, 1329.5899423905234, 1388.9476610421257, 1338.3554621772444, 1327.6922803222226, 1313.4015072363025, 1355.1396654592534, 1334.929881133014, 1288.7404759786446], [1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977, 1239.6349292315638, 1256.4686678242904, 1277.2435737396827, 1267.0466827108758, 1178.9368661962508, 1368.468264013462, 1423.5411331544783, 1242.4019341077947, 1226.9254448575948, 1186.9326588398535, 1344.001558702772, 1337.9391635327902, 1297.4028580414574], [1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977, 1311.5753634371717, 1388.2120232884542, 1431.8449807730888, 1431.3580503007593, 1378.1452369441306, 1396.4141506156877, 1433.377670872926, 1384.1169572273377, 1359.900905300984, 1330.6370094444353, 1353.823654014219, 1336.9776868893764, 1288.787931542987]]
labels = ['1', '2', "3", "4","5","6"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.',"-",":"]
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i], marker=".", linestyle=line[i], )
# 设置图例
plt.legend()
# 设置 x 轴范围
plt.xlim(0, 19)
# 设置 x 轴刻度间距
plt.xticks(np.arange(0, 19, 1))
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('time slots')
plt.ylabel('System Energy Efficiency')
# 显示图形
plt.show()
def draw_slot_satisfaction_compare():
r1 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.9333333333333333, 0.9333333333333333,
0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333]
r2 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.9333333333333333, 1.0, 1.0, 0.9333333333333333,
1.0, 1.0]
r3 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.9333333333333333, 1.0, 1.0, 1.0, 1.0, 1.0]
g1 = [1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 1.0,
0.9333333333333333, 0.9333333333333333, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
g2 = [1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 1.0,
1.0, 1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
g3 = [1.0, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
result = []
result.append(r1)
result.append(r2)
result.append(r3)
# result.append(r4)
# result.append(r5)
# result.append(r6)
labels = ['10 10', '10 20', "10 30", "10 40", "10 50", "10 60"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.', "-", ":"]
for i in range(len(result)):
index = round(i / 2)
plt.plot(result[i], label=labels[i], marker=".", linestyle=line[i], )
# 设置图例
plt.legend()
# 设置 x 轴范围
plt.xlim(0, 19)
plt.ylim(0, 1.1)
# 设置 x 轴刻度间距
plt.xticks(np.arange(0, 19, 1))
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('time slots')
plt.ylabel('Communication Satisfaction')
# 显示图形
plt.show()
def draw_compare_pso_and_convex():
r1=[2156.572640825806, 1793.049723531689, 1536.9919020592397, 1731.792484946798, 1636.6545118475497,
1158.0510410573797, 1103.6215549974738, 782.5004345151718]
r2=[2102.3361983188765, 1643.2563392728337, 1363.8964216339489, 1375.9362936740881, 810.3157040900248,
744.929779050958, 823.9891822976343, 461.98393739269625]
r3=[2095.218778754906, 1632.1290265003292, 1508.3203473638766, 1414.1323142076471, 1114.4302718364665,
969.7470169582967, 920.7834622299312, 752.0135667914984]
r4=[2081.364506789164, 1441.4649220322065, 1352.8460409408997, 1251.814958273326, 827.5835603105922, 718.3196179478409,
702.6041582888906, 590.024193244058]
r1 = [1979.5154537856467, 1949.1967926150814, 1583.8373789254997, 1408.9597726122278, 1284.75424046391,
1062.356849679389, 773.64091282078, 669.5307009461131]
r2 = [1954.7080805746896, 1453.8382207915447, 1268.2785375163758, 987.7561390469604, 881.274376744466,
783.0926396247362, 555.7810370667859, 400.0913596289859]
r3 = [1979.5154537856467, 1572.289453569241, 1482.206203919101,1113.0080767351026, 1064.4678552375331,
910.7380100121287, 710.6949860041652, 473.73148513092895]
r4 = [1954.7080805746896, 1391.2020029825142, 1189.340170050845, 905.7558722161126, 805.0153107446824,
720.2723455091826, 520.5573981391487, 373.8077702943482]
r=[(r1[i]-r4[i])/r4[i] for i in range(len(r1))]
print(sum(r)/len(r))
result=[]
result.append(r1)
result.append(r2)
result.append(r3)
result.append(r4)
x=[i for i in range(5, 20, 2)]
labels = ['Proposed Scheme', 'PSO-Avg', "KMeans-Convex", "KMeans-Avg"]
markers = [".", '^', 's', 'o']
line = ['-', '--', ':', '-.']
for i in range(len(result)):
index = round(i / 2)
plt.plot(x,result[i], label=labels[i], marker="o", linestyle=line[i], zorder=2)
# 设置图例
plt.legend()
# 设置 x 轴范围
plt.xlim(4, 20)
# 设置 x 轴刻度间距
plt.xticks(np.arange(5, 20, 2))
# 设置标题和坐标轴标签
# plt.title('Multiple Lines on One Plot')
plt.xlabel('Users Num')
plt.ylabel('System Energy Efficiency')
# 显示图形
plt.show()
def draw_c_satisfaction():
# 示例数据
name_list = ['uavs=4,users=16', 'uavs=5,users=30', 'uavs=6,users=50',]
values1 = [1.0, 0.96, 0.85]
values2 = [0.8823529411764706, 0.86, 0.8]
values3 = [0.9411764705882353, 0.94, 0.83]
values4 = [0.8823529411764706, 0.8, 0.7]
improve=[(values1[i]-values4[i])/values4[i] for i in range(len(values1))]
print(sum(improve)/len(improve))
x = list(range(len(values1)))
print(x)
total_width, n = 0.8, 4
width = total_width / n
# 计算每个柱的位置
bar_positions = np.arange(len(name_list))
plt.bar(bar_positions - 2*width, values1, width=width, label='Proposed Scheme', color='white',edgecolor='black',tick_label=name_list,)
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(bar_positions - width, values2, width=width, label='PSO-Avg', tick_label=name_list, color='white',edgecolor='black',hatch='/' )
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(bar_positions, values3, width=width, label='KMeans-Convex', tick_label=name_list, color='white',edgecolor='black',hatch='\\')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(bar_positions+width, values4, width=width, label='KMeans-Avg', tick_label=name_list, color='white',edgecolor='black',hatch='//' )
# for i in range(len(bar_positions)):
# bar_positions[i] = bar_positions[i] - 0.1
plt.xticks(bar_positions, name_list)
plt.ylabel('Communication Satisfaction of Users')
plt.legend()
plt.show()
def draw_p_satisfaction():
name_list = ['uavs=4,users=16', 'uavs=5,users=30', 'uavs=6,users=50', ]
values1,values2,values3,values4 =[1.0,1,1], [1.0,1,1], [0.8235294117647058,0.9,0.88], [0.8235294117647058,0.9,0.88]
x = list(range(len(values1)))
print(x)
total_width, n = 0.8, 4
width = total_width / n
# 计算每个柱的位置
bar_positions = np.arange(len(name_list))
light_color = 'white'
plt.bar(bar_positions - 2 * width, values1, width=width, label='Proposed Scheme', color=light_color,edgecolor='black', tick_label=name_list, )
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(bar_positions - width, values2, width=width, label='PSO-Avg', tick_label=name_list, color=light_color,edgecolor='black', hatch='/')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(bar_positions, values3, width=width, label='KMeans-Convex', tick_label=name_list, color=light_color,edgecolor='black', hatch='\\')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(bar_positions + width, values4, width=width, label='KMeans-Avg', tick_label=name_list, color=light_color,edgecolor='black',
hatch='//')
# for i in range(len(bar_positions)):
# bar_positions[i] = bar_positions[i] - 0.1
plt.xticks(bar_positions, name_list)
plt.ylabel('Localization Satisfaction of Users')
plt.legend()
plt.show()
def draw_dynamic_utility():
r=[-182.50035696943849, -177.79594156951626, -145.0853662930458, -142.68333401292557, -141.75346320018448,
-139.89634105148497, -139.25474456595703, -138.38238133386784, -130.0599933647533, -132.7028964739182,
-133.02973650029, -137.43839825328695, -140.7194869302244, -139.8250859102916, -138.70066639324273,
-144.02751920866464, -147.57584841736275]
r3=[-185.11489614688995, -183.32832233236752, -184.8632440312421, -185.90826130427084, -1046.4029821344411,
-705.1510281549287, -784.703021596474, -188.32844376690645, -1432.3437733694404, -1340.519117170665,
-1108.9134865693245, -1329.724190290336, -543.0716332673447, -4079.8195480534982, -801.905349792583,
-880.6140750428915, -185.65576844983727]
r2=[-182.5881732692689, -182.9274309066099, -151.37672315057665, -149.39333947365594, -149.79231667807625, -147.4212656957045, -148.77068968962027, -153.205403970754, -141.47000821147626, -142.7027807716164, -142.0437598710444, -143.8288448799893, -143.2228327270912, -144.59048160309982, -147.25800551225242, -146.7899663698531, -144.9709480279667]
r1 = [-184.06100597871276, -185.85049500451746, -146.8288332014583, -147.8690106029141, -150.89610670415044,
-161.58225234814634, -161.25450103761872, -160.210679762176, -174.61142139727096, -177.76804395633008,
-181.569335688453, -159.927794994072, -160.94409679626565, -166.21748449604434, -160.2738429197924,
-159.7484534802284, -158.85902270747295]
r2 = [-183.75262514436605, -185.87714908455004, -146.57818980968494, -147.60619957376412, -150.63793929032238,
-160.1327365871477, -160.41656576457314, -159.14883710280913, -177.61971965060854, -173.46045900149656,
-177.10133069993495, -159.18269253893232, -160.08874781747255, -163.4671368445193, -158.9553959759295,
-158.31327992554847, -157.30095288797912]
r3 = [-191.9539271586222, -495.0759766925493, -193.5965909690982, -192.5817448793148, -1195.945536180579,
-540.6940059847401, -629.8130961244544, -552.3027556855934, -189.9716865954716, -701.1440778210009,
-2998.227257864013, -2423.421441879022, -200.80692664994223, -1791.7088515380249, -879.184983460981,
-201.1295073193511, -1087.8150595700147]
r4_1 = [-183.75262514436605, -185.87714908455004, -186.438834653355, -184.1884585777314, -186.33933807260107,
-188.43716599179044, -188.19672726431384, -186.9874196689149, -189.13295993082926, -189.30032644825883,
-192.89436400905976, -195.0003337026544, -196.4162768042548, -196.62278977364838, -197.82920310513353,
-197.86530599940798, -198.22041251155667]
r4=[-191.9539271586222, -193.26796056081787, -193.08808786801166, -192.21772213830948, -194.02224268400286, -193.699253301448, -193.61243939244417, -191.9209212060532, -194.12611798707232, -194.22893921637396, -198.00070893060212, -199.68020061189088, -201.41765011390575, -202.61071672355132, -203.10880418272217, -202.69870082683104, -202.27407764837193]
# d=[(r1[i]-r3[i])/abs(r3[i]) for i in range(len(r1))]
d = [(r1[i] - r4[i]) / abs(r4[i]) for i in range(len(r1))]
d1 = [(r1[i] - r4_1[i]) / abs(r4_1[i]) for i in range(len(r1))]
print(sum(d)/len(d))
print(sum(d1) / len(d))
x=[i for i in range(1, 18, 1)]
plt.plot(x, r1, label="Proposed algorithm", marker="o", )
# plt.plot(x, r4, label="Non dual time scales", marker="*", )
plt.plot(x, r4, label="Fixed position and resource", marker="*", )
# plt.plot(x, r4_1, label="Fixed position-Convex", marker=".", )
plt.plot(x, r4_1, label="Fixed position dynamic resource", marker="^", )
# plt.plot(x, r2, label="Pso-Convex", marker="^", )
# plt.plot(x, r3, label="Kmeans-Avg", marker=".", )
plt.xlabel('时隙', fontsize=14, fontproperties=font_prop)
plt.ylabel('通导效用', fontsize=14, fontproperties=font_prop)
# plt.xlabel('time slots')
# plt.ylabel("Communication Localization utility")
plt.legend()
# plt.ylim(-3000, 100)
plt.show()
def draw_dynamic_c_satisfaction():
c1 = [0.8333333333333334, 0.8333333333333334, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.7333333333333333, 0.8, 0.8, 0.7, 0.7,
0.7666666666666667, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666]
g1 = [0.6666666666666666, 0.6666666666666666, 0.8666666666666667, 0.8666666666666667, 0.8666666666666667, 0.8, 0.8,
0.8, 0.8333333333333334, 0.8333333333333334, 0.8333333333333334, 0.7333333333333333, 0.7333333333333333,
0.7333333333333333, 0.7666666666666667, 0.7666666666666667, 0.7666666666666667]
c2 = [0.4666666666666667, 0.5333333333333333, 0.6666666666666666, 0.5666666666666667, 0.6333333333333333,
0.6333333333333333, 0.5666666666666667, 0.6, 0.5, 0.5333333333333333, 0.4, 0.5333333333333333,
0.4666666666666667, 0.5666666666666667, 0.5333333333333333, 0.43333333333333335, 0.4]
g2 = [0.6666666666666666, 0.6666666666666666, 0.8666666666666667, 0.8666666666666667, 0.8666666666666667, 0.8, 0.8,
0.8, 0.8333333333333334, 0.8333333333333334, 0.8333333333333334, 0.7333333333333333, 0.7333333333333333,
0.7333333333333333, 0.7666666666666667, 0.7666666666666667, 0.7666666666666667]
c3 = [0.7666666666666667, 0.36666666666666664, 0.7666666666666667, 0.7333333333333333, 0.36666666666666664,
0.26666666666666666, 0.16666666666666666, 0.36666666666666664, 0.7666666666666667, 0.13333333333333333,
0.4666666666666667, 0.4, 0.6, 0.23333333333333334, 0.03333333333333333, 0.6333333333333333,
0.16666666666666666]
g3 = [0.6666666666666666, 0.4666666666666667, 0.6333333333333333, 0.6333333333333333, 0.23333333333333334,
0.43333333333333335, 0.4666666666666667, 0.5333333333333333, 0.7, 0.3, 0.3, 0.3333333333333333, 0.6, 0.4,
0.16666666666666666, 0.6, 0.43333333333333335]
c4_1=[0.4666666666666667, 0.5333333333333333, 0.6333333333333333, 0.6, 0.6, 0.5666666666666667, 0.4666666666666667, 0.5,
0.4, 0.4666666666666667, 0.3333333333333333, 0.43333333333333335, 0.43333333333333335, 0.4666666666666667,
0.4666666666666667, 0.4666666666666667, 0.36666666666666664]
c4=[0.7666666666666667, 0.8, 0.8, 0.8, 0.8, 0.6333333333333333, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6666666666666666, 0.6333333333333333, 0.6333333333333333, 0.6333333333333333, 0.6333333333333333, 0.6333333333333333]
g4_1 = [0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.7, 0.7,
0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
g4 = [0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.7, 0.7,
0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
x = [i for i in range(1, 18, 1)]
plt.plot(x, c1,label="Proposed algorithm", marker="o", )
plt.plot(x, c4, label="Non dual time scales", marker="*", )
# plt.plot(x, c4, label="Fixed position and resource", marker="*", )
# plt.plot(x, c4_1, label="Fixed position-Convex", marker=".", )
plt.plot(x, c2,label="PSO-Convex", marker="^", )
plt.plot(x, c3,label="Kmeans-Avg", marker=".", )
# d1= [(c1[i] - c3[i]) / abs(c3[i]) for i in range(len(c1))]
# d2 = [(g1[i] - g3[i]) / abs(g3[i]) for i in range(len(g1))]
d11=(sum(c1)-sum(c3))/sum(c3)
d22=(sum(g1)-sum(g3))/sum(g3)
d1 = (sum(c1) - sum(c4)) / sum(c4)
d2 = (sum(g1) - sum(g4)) / sum(g4)
d1_1 = (sum(c1) - sum(c4_1)) / sum(c4_1)
d2_2 = (sum(g1) - sum(g4_1)) / sum(g4_1)
# d1 = [(c1[i] - c4[i]) / abs(c4[i]) for i in range(len(c1))]
# d2 = [(g1[i] - g4[i]) / abs(g4[i]) for i in range(len(g1))]
print(d1,d2)
print(d1_1,d2_2)
print(d11,d22)
plt.legend()
plt.xlabel('时隙', fontsize=14, fontproperties=font_prop)
plt.ylabel('通信需求满足率', fontsize=14, fontproperties=font_prop)
# plt.xlabel('time slots')
# plt.ylabel('Communication Satisfaction of Users')
plt.show()
def draw_dynamic_g_satisfaction():
c1 = [0.8333333333333334, 0.8333333333333334, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.7333333333333333, 0.8, 0.8, 0.7, 0.7,
0.7666666666666667, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666]
g1 = [0.6666666666666666, 0.6666666666666666, 0.8666666666666667, 0.8666666666666667, 0.8666666666666667, 0.8, 0.8,
0.8, 0.8333333333333334, 0.8333333333333334, 0.8333333333333334, 0.7333333333333333, 0.7333333333333333,
0.7333333333333333, 0.7666666666666667, 0.7666666666666667, 0.7666666666666667]
c2 = [0.4666666666666667, 0.5333333333333333, 0.6666666666666666, 0.5666666666666667, 0.6333333333333333,
0.6333333333333333, 0.5666666666666667, 0.6, 0.5, 0.5333333333333333, 0.4, 0.5333333333333333,
0.4666666666666667, 0.5666666666666667, 0.5333333333333333, 0.43333333333333335, 0.4]
g2 = [0.6666666666666666, 0.6666666666666666, 0.8666666666666667, 0.8666666666666667, 0.8666666666666667, 0.8, 0.8,
0.8, 0.8333333333333334, 0.8333333333333334, 0.8333333333333334, 0.7333333333333333, 0.7333333333333333,
0.7333333333333333, 0.7666666666666667, 0.7666666666666667, 0.7666666666666667]
c3 = [0.7666666666666667, 0.36666666666666664, 0.7666666666666667, 0.7333333333333333, 0.36666666666666664,
0.26666666666666666, 0.16666666666666666, 0.36666666666666664, 0.7666666666666667, 0.13333333333333333,
0.4666666666666667, 0.4, 0.6, 0.23333333333333334, 0.03333333333333333, 0.6333333333333333,
0.16666666666666666]
g3 = [0.6666666666666666, 0.4666666666666667, 0.6333333333333333, 0.6333333333333333, 0.23333333333333334,
0.43333333333333335, 0.4666666666666667, 0.5333333333333333, 0.7, 0.3, 0.3, 0.3333333333333333, 0.6, 0.4,
0.16666666666666666, 0.6, 0.43333333333333335]
g4_1 = [0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.7, 0.7,
0.7,0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
g4=[0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
x = [i for i in range(1, 18, 1)]
plt.plot(x, g1,label="Proposed algorithm", marker="o", )
plt.plot(x, g4, label="Non dual time scales", marker="*", )
# plt.plot(x, g4, label="Fixed position and resource", marker="*", )
# plt.plot(x, g4_1, label="Fixed position-Convex", marker=".", )
plt.plot(x, g2,label="PSO-Convex", marker="^", )
plt.plot(x, g3,label="Kmeans-Avg", marker=".", )
plt.xlabel('时隙', fontsize=14, fontproperties=font_prop)
plt.ylabel('定位需求满足率', fontsize=14, fontproperties=font_prop)
# plt.xlabel('time slots')
# plt.ylabel('Localization Satisfaction of Users')
plt.legend()
plt.show()
def draw_two_pso():
r1=[-1196.9323426279452, -1023.2879873142075, -938.1347737903101, -839.9352308341875, -713.3749158686057,
-695.6398497337009, -692.6064311156695, -655.9969403981936, -652.2223431837863, -640.3367322566492,
-640.3367322566492, -629.4268704014644, -629.4268704014644, -619.2731245473466, -618.8899488986626,
-618.8899488986626, -618.8899488986626, -618.8899488986626, -613.6306159984326, -613.6306159984326,
-613.6306159984326, -613.6306159984326, -613.6306159984326, -613.6306159984326, -613.5003594617765,
-613.4642026310231, -612.7132692348612, -612.7132692348612, -612.7132692348612, -612.7132692348612,
-612.7132692348612, -612.7132692348612, -612.7132692348612, -612.7132692348612, -612.0582857242623,
-611.7966818160626, -611.4553346200508, -611.4553346200508, -610.4046128928244, -610.4046128928244,
-610.4046128928244, -610.3414237226195, -610.0636132324591, -609.9302397688457, -609.9302397688457,
-609.9302397688457, -609.8247476936176, -609.3586162393262, -608.7753594243752, -608.7753594243752,
-608.4847452080389, -608.4847452080389, -608.4847452080389, -608.4328989734311, -608.3579667611907,
-608.3579667611907, -608.3579667611907, -608.3579667611907, -608.2983547415181, -608.2545299241742,
-607.9579163498192, -607.9579163498192, -607.9579163498192, -607.9579163498192, -607.9579163498192,
-607.9579163498192, -607.9579163498192, -607.9251930979092, -607.8490809433433, -607.7401985001247,
-607.7401985001247, -607.7401985001247, -607.7401985001247, -607.729634835325, -607.729634835325,
-607.729634835325, -607.7292704587401, -607.6403860641153, -607.6403860641153, -607.6403860641153,
-607.6335094134449, -607.6025167411549, -607.5755885295946, -607.5722972661849, -607.5645509212286,
-607.541015826343, -607.4579266297451, -607.4012341854012, -607.4012341854012, -607.4012341854012,
-607.3827092828479, -607.3230904811196, -607.3081820002802, -607.2542297698676, -607.1699432866275,
-607.1357793051466, -607.1344263335025, -607.1083267606782, -607.1083267606782, -607.0837256958735,
-607.0365337511737, -606.9998609278682, -606.9012318909207, -606.8523765243652, -606.8523765243652,
-606.8523765243652, -606.842359971376, -606.7956110585856, -606.7956110585856, -606.7956110585856,
-606.7408729474714, -606.6802105356159, -606.6740828338604, -606.6740828338604, -606.6505920842787,
-606.6026225102125, -606.5935995966431, -606.5448191595901, -606.5448191595901, -606.5063607756622,
-606.5063607756622, -606.5063607756622, -606.4851726862596, -606.4851726862596, -606.4851726862596,
-606.4772055606807, -606.4772055606807, -606.4772055606807, -606.4771594380561, -606.4771594380561,
-606.470177358181, -606.470177358181, -606.470177358181, -606.470177358181, -606.456010919539, -606.4546567569781,
-606.4507733875905, -606.4025904682732, -606.3751148588892, -606.3730367007836, -606.3473268430255,
-606.3349603008672, -606.3349603008672, -606.3349603008672, -606.3337851788831, -606.319478725464,
-606.319478725464, -606.3032184946985, -606.3032184946985, -606.296861611934, -606.296861611934,
-606.2802118434549, -606.2453062088408, -606.2254450888618, -606.2254450888618, -606.2254450888618,
-606.2241058242523, -606.1716396591552, -606.1405887180167, -606.1089602732022, -606.0555927777,
-606.0533244250175, -605.9970026224007, -605.9553210622021, -605.9058515535407, -605.7808651617311,
-605.6894618878111, -605.6095113966787, -605.5357964277108, -605.2882820245106, -605.102346569551,
-604.9078201405405, -604.7106563329935, -604.433266025304, -604.3960675521805, -604.2827959000942,
-604.2579148274684, -604.2579148274684, -604.2579148274684, -604.2442110865913, -604.2413731581769,
-604.234528779501, -604.234528779501, -604.2265793947867, -604.2265793947867, -604.22352810453, -604.2139074961442,
-604.2108490203143, -604.1891481621628, -604.1891481621628, -604.1891481621628, -604.1891481621628,
-604.1891481621628, -604.1891481621628, -604.1891481621628, -604.1891481621628, -604.1891481621628,
-604.1891481621628, -604.1891481621628, -604.1891481621628]
r2=[-380.7411141759215, -380.7411141759215, -380.7411141759215, -363.72305859666784, -363.72305859666784,
-349.810356641212, -328.5825684550027, -328.5825684550027, -328.5825684550027, -328.5825684550027,
-325.5954018295555, -318.08045403389883, -318.08045403389883, -318.08045403389883, -315.8258698970216,
-311.07719296107484, -311.03875270173796, -311.03875270173796, -294.3404638065752, -294.3404638065752,
-290.5217035878852, -275.5763852875366, -265.23241780168416, -265.23241780168416, -265.23241780168416,
-265.23241780168416, -262.28605152664534, -262.28605152664534, -258.8284357693334, -256.22640857164606,
-256.22640857164606, -256.22640857164606, -256.22640857164606, -256.22640857164606, -255.53912739962215,
-255.53912739962215, -255.53912739962215, -255.33560728054294, -255.33560728054294, -255.28767766570354,
-255.28767766570354, -253.76995359761094, -252.83659157878247, -251.977103784552, -251.977103784552,
-251.977103784552, -251.977103784552, -251.977103784552, -251.977103784552, -251.53735983379426,
-248.71930609772627, -248.71930609772627, -247.83619225744548, -247.83283225965897, -247.78590955094347,
-247.78590955094347, -247.59373583633038, -247.5732508903926, -247.5732508903926, -247.5693554712022,
-247.5693554712022, -247.3226140469394, -247.3226140469394, -247.3226140469394, -247.14441530955818,
-247.14441530955818, -247.14441530955818, -246.6572067590505, -246.468983665093, -246.44367458023024,
-246.29257042607526, -246.29257042607526, -246.29257042607526, -246.29257042607526, -246.28983312227217,
-246.2107367702723, -246.0802533898576, -246.0802533898576, -246.0802533898576, -246.0802533898576,
-246.0802533898576, -246.0802533898576, -246.07747834189666, -246.049077629492, -246.04682457275493,
-246.04682457275493, -245.9802714581705, -245.9466906329154, -245.9466906329154, -245.87516567942754,
-245.8335567374412, -245.81565126884948, -245.81565126884948, -245.7225111268908, -245.62841620693212,
-245.62670140858825, -245.62054618646803, -245.62054618646803, -245.62054618646803, -245.61057598622915,
-245.61057598622915, -245.55937807397459, -245.5242572250821, -245.5242572250821, -245.5242572250821,
-245.5242572250821, -245.51646263534585, -245.51646263534585, -245.51646263534585, -245.51646263534585,
-245.51646263534585, -245.51646263534585, -245.5151690804198, -245.48847455697387, -245.48708931335642,
-245.4730102826531, -245.45908855084855, -245.45156674846427, -245.45156674846427, -245.45156674846427,
-245.45156674846427, -245.45156674846427, -245.45156674846427, -245.44924975582472, -245.44924975582472,
-245.44924975582472, -245.44924975582472, -245.44924975582472, -245.44924975582472, -245.4467777809799,
-245.4467777809799, -245.4467777809799, -245.44655918815045, -245.44655918815045, -245.44655918815045,
-245.44655918815045, -245.44482415235223, -245.44482415235223, -245.44482415235223, -245.44482415235223,
-245.44482415235223, -245.44482415235223, -245.44482415235223, -245.44482415235223, -245.44482415235223,
-245.44482415235223, -245.44482415235223, -245.44482415235223, -245.44482415235223, -245.44482415235223,
-245.44482415235223, -245.44427621306633, -245.44427621306633, -245.44427621306633, -245.44427621306633,
-245.44427621306633, -245.44427621306633, -245.4441307955143, -245.4441307955143, -245.4441307955143,
-245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143,
-245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143,
-245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143,
-245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143,
-245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143, -245.4441307955143,
-245.4441307955143, -245.44412490547342, -245.44412490547342, -245.44412490547342, -245.44412490547342,
-245.44412490547342, -245.44412490547342, -245.44412490547342, -245.44412490547342, -245.44412490547342,
-245.44412490547342, -245.44412490547342, -245.44412490547342, -245.44412490547342, -245.44412490547342]
plt.plot(r2, label="improved pso", )
plt.plot(r1, label="static pso",linestyle='--', )
d1 = [(r2[i] - r1[i]) / abs(r1[i]) for i in range(len(r1))]
print(sum(d1)/len(d1))
plt.xlabel('迭代次数', fontsize=14, fontproperties=font_prop)
plt.ylabel('适应度', fontsize=14, fontproperties=font_prop)
# plt.xlabel('iteration')
# plt.ylabel('fitness value')
plt.legend()
plt.show()
def draw_scheme_compare():
r1=[-184.06100597871276, -185.85049500451746, -146.8288332014583, -147.8690106029141, -150.89610670415044,
-161.58225234814634, -161.25450103761872, -160.210679762176, -174.61142139727096, -177.76804395633008,
-181.569335688453, -159.927794994072, -160.94409679626565, -166.21748449604434, -160.2738429197924,
-159.7484534802284, -158.85902270747295]
r2 = [-184.47707786404925, -186.79859967274973, -187.18900537301826, -185.00993033401568, -186.98011160427623,
-186.7475686243944, -188.5738993568263, -186.66325649759037, -189.93822318891313, -190.1625116360844,
-193.71770035886448, -195.85488809139676, -195.6319247325472, -197.10555864062565, -198.25810453714203,
-198.28055212033237, -198.22276758982875, -198.55710227964607]
r3 = [-184.47707786404925, -186.09526372564545, -186.06078249070885, -147.85913907661956, -150.55241416659936,
-150.31251306017782, -153.33386123238563, -151.49498797995372, -153.77165045599617, -169.11425658693145,
-169.97320242448745, -170.8741998698821, -164.6200858129465, -164.28081292472123, -165.24268234023336,
-162.52560152043168, -161.74900753634054, -161.92402781925833]
plt.plot(r1, label="proposed algorithm", marker="o", )
plt.plot(r2, label="FDDR", marker="o", )
plt.plot(r3, label="FRDD", marker="o", )
plt.legend()
# plt.ylim(-3000, 100)
plt.show()
# draw_scheme_compare()
draw_two_pso()
# draw_data()
# draw_time()
# draw_avg_and_optimal()
# draw_different_scheme()
draw_particle_num()
draw_iteration_num()
# draw_particle_time()
# draw_iteration_num()
# draw_iteration_time()
draw_dynamic_utility()
draw_dynamic_c_satisfaction()
draw_dynamic_g_satisfaction()
# draw_different_scheme()
# draw_compare_pso_and_convex()
# draw_c_satisfaction()
# draw_p_satisfaction()
# draw_slot_compare()
# draw_slot_satisfaction_compare()
# draw_different_scheme_satisfaction()
\ No newline at end of file
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
import constants as C
import Users
def gauss_markov_model(positions, step_size, max_range, ):
# 使用高斯-马尔科夫模型生成随机位置变化,考虑更长时间范围的随机性
delta = np.random.normal(0, step_size, size=positions.shape)
new_positions = positions + delta
# 限制位置在给定范围内
new_positions = np.clip(new_positions, 0, max_range)
# print(new_positions)
return new_positions
def generate_users_pos(users,slot,num):
U=[]
U.append(users)
for i in range(num):
users=gauss_markov_model(users, slot*C.v, C.max_range, )
U.append(users)
print(U)
return U
def generate_users_pos_in_file(users,slot,num):
U=[]
U.append(users)
for i in range(num):
# users=gauss_markov_model(users, slot*C.v, C.max_range, )
users = random_pos(users, slot * C.v, C.max_range)
U.append(users)
print(U)
U=np.array(U)
np.save('dynamic_users2.npy', U)
# 从文件加载NumPy数组
return U
def get_users_pos_from_file():
U = np.load('dynamic_users2.npy')
# 打印加载的数组
# print("Loaded Data:")
# print(U)
# u1=U[2][1]
# u2=U[3][1]
# print(math.sqrt((u1[0]-u2[0])**2+(u1[1]-u2[1])*2))
return U
def random_pos(positions, step_size, max_range,):
angles = np.random.uniform(0,2*np.pi, len(positions))
# angels=np.full((1, len(positions)), np.pi/4)
# Generate random distances within the outer circle
distances = step_size
# Convert polar coordinates to Cartesian coordinates
x = positions[:, 0] + distances * np.cos(angles)
y = positions[:, 1] + distances * np.sin(angles)
new_positions=[]
for i in range(len(x)):
new_positions.append(np.array([x[i],y[i]]))
new_positions=np.array(new_positions)
new_positions = np.clip(new_positions, 0, max_range)
print(new_positions)
return new_positions
def random_r(users):
r_c = {}
r_p={}
for i in range(len(users)):
r_c[i] = random.randint(1,4)
r_p[i]=random.randint(1,4)
return r_c,r_p
def generate_random_r_in_file(users,num,filename):
#80% 1,2 20% 3,4
a=random.random()
dic={}
length=len(users)
for i in range(length):
dic[str(i)]=[]
df=pd.DataFrame(dic)
for i in range(num):
r=[]
for j in range(length):
a=random.random()
if a>0.8:
b=random.random()
if b>=0.8:
r.append(3)
else:
r.append(4)
else:
b = random.random()
if b >= 0.7:
r.append(1)
else:
r.append(2)
# r=[random.randint(1,4) for i in range(length)]
df.loc[len(df)] = r # 通过 loc 添加一行
# print(df)
# 将 DataFrame 存入 CSV 文件
df.to_csv(filename, index=False)
def read_csv_to_df(file_path):
df = pd.read_csv(file_path)
# 选择 DataFrame 中的一行(例如,第一行)
# 打印结果
# print(row_dict)
return df
def get_r_c_and_r_p(df_c,df_p,index):
selected_c = df_c.iloc[index]
selected_p = df_p.iloc[index]
# 将选定的行转换为字典
r_c = {int(key): value for key, value in selected_c.to_dict().items()}
r_p = {int(key): value for key, value in selected_p.to_dict().items()}
return r_c,r_p
users=Users.getUsers("./data3.csv")
# generate_users_pos(users,10,5)
# generate_random_r_in_file(users,50,'r_p.csv')
# generate_users_pos_in_file(users,10,30)
U=get_users_pos_from_file()
# print(len(U))
# df_c=read_csv_to_df('r_c.csv')
# df_p=read_csv_to_df('r_p.csv')
# r_c,r_p=get_r_c_and_r_p(df_c,df_p,0)
# print(r_c,r_p)
# U=get_users_pos_from_file()
def update(frame, user_positions, sc, step_size, max_range,):
user_positions = gauss_markov_model(user_positions, step_size, max_range, )
# user_positions=random_pos(user_positions, step_size, max_range,)
sc.set_offsets(user_positions)
return sc,
def create_dynamic_plot(num_users, max_range, step_size,):
# 初始化用户位置
user_positions = np.random.uniform(0, max_range, size=(num_users, 2))
# 创建散点图
fig, ax = plt.subplots()
sc = ax.scatter(user_positions[:, 0], user_positions[:, 1])
# 设置图形的标题和坐标轴标签
ax.set_title('Dynamic Point Plot with Gauss-Markov Model')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
# 使用FuncAnimation实现动态效果
animation = FuncAnimation(fig, update, frames=300, fargs=(user_positions, sc, step_size, max_range,), interval=100)
# 返回FuncAnimation对象
return animation
def draw_dynamic_users():
# 设置参数
num_users = 15
max_range = 1000
step_size = 10
persistence_factor = 1
# 创建动态点位图
dynamic_plot = create_dynamic_plot(num_users, max_range, step_size,)
# 显示动画
plt.show()
# draw_dynamic_users()
\ No newline at end of file
import math
import Users
import numpy as np
import random
from pprint import pprint
import constants as C
import tool
import ObjectiveFuction as OF
# 定义混沌映射(Logistic映射)
def logistic_map(x, r):
return r * x * (1 - x)
class CPSO:
def __init__(self,pre_uavs,users,r_c,r_p,k,N=50):
#之后解析JSON,从JSON中读参数
self.N=N
self.k=k
self.pre_uavs=pre_uavs
self.users=users
self.d = 3 # 可行解维数
self.limit = [C.min_range,C.max_range] # 边界位置限制
self.vlimit = [-50, 50] # 边界速度限制
self.r_c = r_c
self.r_p=r_p
# self.height = 100
self.min_height = C.min_height
self.max_height = C.max_height
self.wmax = 0.9 # 惯性权重
self.wmin = 0.4
self.c1 = 1.5 # 自我学习因子
self.c2 = 1.5 # 群体学习因子
# self.c1 = 0.5 # 自我学习因子
# self.c2 = 0.5 # 群体学习因子
self.maxgen = 200
# self.users = Users.getUsers("./data.csv")
self.users = users
self.r=3.8
# self.c_association = c_association
# self.p_association = p_association
# self.p_all = p_all
# self.b_all = b_all
# self.init_alloc()
# #todo:防止无人机位置碰撞
# def punish_function(self,uavs):
# # user_arr = [1, 2, 5]
# punish=0
# for i in range(len(uavs)):
# for j in range(i+1,len(uavs)):
# dis=self.cal_tool.getDistance(uavs[i],uavs[j])
# if dis<200:
# punish+=100
#
# return punish
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 re_init(self,pre_uavs,users,r_c,r_p,c_association, p_association, p_all, b_all,):
self.pre_uavs=pre_uavs
self.user=users
self.r_c=r_c
self.r_p=r_p
self.c_association = c_association
self.p_association = p_association
self.p_all = p_all
self.b_all = b_all
def punish_f(self,uavs):
punish=0
max_dis=(C.time_slot-C.run_time)*C.speed
for i in range(len(uavs)):
dis=tool.calculate_3d_distance_uavs(uavs[i],self.pre_uavs[i])
if dis>max_dis:
punish=float('-inf')
return punish
# def init_r_c(self):
# r_c={}
# for i in range(len(self.users)):
# r_c[i] = random.randint(1,4)
# return r_c
# 初始化粒子群,k是无人机数量
def initParticle(self, users):
X = []
# users=Users.generate(100)#用户位置
V = np.random.uniform(self.vlimit[0], self.vlimit[1], (self.N, self.k, 3))
for i in range(self.N):
uavs=[]
uavs_k=tool.getUavInitialPos(self.k,self.users,)
# tool.getUavInitialPos(self.k, users)
# uavs_k=self.pre_uavs
if i==0:
uavs=tool.getUavInitialPos_fcm(self.k,self.users)
elif i==1:
uavs = tool.getUavInitialPos(self.k, self.users)
else:
for index in range(self.k):
# x,y=generate_random_particles(uavs_k[index],30,1)
x, y = generate_random_particles(uavs_k[index],C.v*5, 1)
# x=np.random.uniform(self.limit[0],self.limit[1])
# y=np.random.uniform(self.limit[0],self.limit[1])
# z=np.random.uniform(self.min_height,self.max_height)
z=self.min_height
uavs.append([x[0],y[0],z])
X.append(uavs)
X = np.array(X)
return X, V
# 初始化个体和全局最佳历史位置和最佳适应度
def initBest(self, X,):
p_pos = X.copy() # 每个个体的历史最佳位置
global_pos = np.zeros((self.k, 3)) # 种群的历史最佳位置5*3
p_best = np.full((self.N, 1), float('-inf')) # 每个个体的历史最佳适应度
global_best = float('-inf') # 种群历史最佳适应度
return p_pos, global_pos, p_best, global_best
def pso(self, X, V, update_w,get_fitness,):
# X, V, users = initParticlePos()
p_pos, global_pos, p_best, global_best = self.initBest(X)
result = np.zeros(self.maxgen)
for iter in range(self.maxgen):
# fitness = self.getfitness(X, users, k,P) # 计算所有粒子适应度
fitness = np.zeros(self.N)
for i in range(len(X)):
# f,_,_=get_fitness(self.pre_uavs,X[i],self.users,self.r_c,self.r_p)
punish=self.punish_f(X[i])
if punish==float('-inf'):
fitness[i]=punish
else:
f, _, _ = get_fitness(self.pre_uavs,X[i],self.users,self.r_c,self.r_p,self.p_all,self.b_all,self.c_association,self.p_association)
fitness[i]= f+self.punish_f(X[i])
for i in range(self.N):
if fitness[i] > p_best[i]:
p_best[i] = fitness[i] # 更新个体历史最佳适应度
p_pos[i] = X[i].copy() # 更新个体历史最佳位置(取值)
if max(p_best) > global_best:
global_best = max(p_best) # 更新群体历史最佳适应度
max_index = p_best.argmax()
global_pos = X[max_index].copy() # 更新群体历史最佳位置
# 权重更新
w = self.wmax - iter * (self.wmax - self.wmin) / self.maxgen
# w = update_w(self.wmin, self.wmax, iter, self.maxgen, fitness)
for i in range(self.N):
# V[i] = self.r * logistic_map(V[i], self.r)
# w=update_w(self.wmin,self.wmax,iter,self.maxgen,i,fitness)
# c1=update_c1(iter,self.maxgen)
# c2=update_c2(iter,self.maxgen)
V[i] = V[i] * w + self.c1 * random.random() * (p_pos[i] - X[i]) + self.c2 * random.random() * (
global_pos - X[i])
# print(V[i])
for j in range(len(V[i])):
for p in range(len(V[i][j])):
if V[i][j][p] > self.vlimit[1]:
V[i][j][p] = self.vlimit[1]
# V[i][j][p] = self.vlimit[0]+np.random.rand(1)*(self.vlimit[1]-self.vlimit[0])
elif V[i][j][p] < self.vlimit[0]:
V[i][j][p] = self.vlimit[0]
# print(V[i])
# 位置更新
X = X + V
# 边界位置处理
for i in range(self.N):
for j in range(len(X[i])):
for p in range(2):
if X[i][j][p] > self.limit[1]:
X[i][j][p] = self.limit[1]
elif X[i][j][p] < self.limit[0]:
X[i][j][p] = self.limit[0]
if X[i][j][2] > self.max_height:
X[i][j][2] = self.max_height
elif X[i][j][2] < self.min_height:
X[i][j][2] = self.min_height
result[iter] = global_best
print(iter,global_pos,global_best)
# print(global_best)
# print(global_pos)
return global_pos,global_best,result
# import matplotlib.pyplot as plt
#
# def logistic_chaotic_model(x0, r, num_steps):
# """
# 实现Logistic混沌模型
#
# 参数:
# - x0: 初始条件
# - r: 控制参数
# - num_steps: 模拟的时间步数
#
# 返回:
# - states: 模拟的状态序列
# """
# states = [x0]
# for _ in range(num_steps - 1):
# x_next = r * states[-1] * (1 - states[-1])
# states.append(x_next)
# return states
#
# def generate_logistic_chaotic_points(num_points):
# """
# 生成 Logistic 混沌模型的点集
#
# 参数:
# - num_points: 要生成的点的数量
#
# 返回:
# - points: 生成的点集 (x, y)
# """
# x0 = np.random.random() # 随机选择初始条件
# r = 4 # 控制参数,可以根据需要进行调整
# num_steps = 1000 # 模拟的时间步数
#
# x_states = logistic_chaotic_model(x0, r, num_steps)
# y_states = logistic_chaotic_model(x0 + 0.1, r, num_steps) # 使用略微不同的初始条件
#
# # 线性映射到[0, 1000]范围
# x_min, x_max = min(x_states), max(x_states)
# x_states_mapped = [((x - x_min) / (x_max - x_min)) * 1000 for x in x_states]
#
# y_min, y_max = min(y_states), max(y_states)
# y_states_mapped = [((y - y_min) / (y_max - y_min)) * 1000 for y in y_states]
#
# # 从映射后的状态序列中选择一些点
# indices = np.linspace(0, num_steps - 1, num_points, dtype=int)
# points = np.array([(x_states_mapped[i], y_states_mapped[i]) for i in indices])
#
# return points
#
# def random_points(num):
# points=[]
# for i in range(num):
# x=random.randint(0,1000)
# y=random.randint(0,1000)
# points.append(np.array([x,y]))
# return np.array(points)
#
# # 生成 100 个点
# num_points = 100
# generated_points = generate_logistic_chaotic_points(num_points)
# points2=random_points(num_points)
# # 绘制生成的点
# plt.figure(figsize=(12, 5))
#
# plt.subplot(1, 2, 1)
# plt.scatter(generated_points[:, 0], generated_points[:, 1], color='b', marker='o')
# plt.title('Logistic model')
# plt.xlabel('x')
# plt.ylabel('y')
# # plt.xlim(0, 1000)
# # plt.ylim(0, 1000)
# plt.subplot(1, 2, 2)
# plt.scatter(points2[:, 0], points2[:, 1], color='r', marker='o')
# plt.title('随机生成的100个点')
# plt.xlabel('x')
# plt.ylabel('y')
# plt.xlim(0, 1000)
# plt.ylim(0, 1000)
# plt.show()
import matplotlib.pyplot as plt
def generate_random_particles(center, outer_radius, num_particles):
# Generate random angles
angles = np.random.uniform(0, 2 * np.pi, num_particles)
# Generate random distances within the outer circle
distances = np.sqrt(np.random.uniform(0, outer_radius ** 2, num_particles))
# Convert polar coordinates to Cartesian coordinates
x = center[0] + distances * np.cos(angles)
y = center[1] + distances * np.sin(angles)
return x, y
def plot_particles(x, y, center, outer_radius):
circle = plt.Circle(center, outer_radius, color='r', alpha=0.2, label='Outer Circle')
plt.scatter(x, y, label='Random Particles', color='blue')
plt.scatter(center[0], center[1], label='Center', color='red', marker='x')
plt.gca().add_patch(circle)
plt.title('Random Particles within Outer Circle')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.show()
# Example usage
# center_point = (0, 0)
# outer_circle_radius = 5
# num_particles = 100
#
# random_x, random_y = generate_random_particles(center_point, outer_circle_radius, num_particles)
# plot_particles(random_x, random_y, center_point, outer_circle_radius)
if __name__ == '__main__':
uavs=[[868.34535881,315.18340086,50. ],
[292.96443022,729.7612657,77.75450997],
[732.25467955,927.62861821,50. ],
[303.40107629,240.31208079,150. ]]
# 示例
import numpy as np
import random
import time
zero_threshold = 0.00000001
class KMNode(object):
def __init__(self, id, exception=0, match=None, visit=False):
self.id = id
self.exception = exception
self.match = match
self.visit = visit
class KuhnMunkres(object):
def __init__(self):
self.matrix = None
self.x_nodes = []
self.y_nodes = []
self.minz = float('inf')
self.x_length = 0
self.y_length = 0
self.index_x = 0
self.index_y = 1
def __del__(self):
pass
def set_matrix(self, x_y_values):
xs = set()
ys = set()
for x, y, value in x_y_values:
xs.add(x)
ys.add(y)
#选取较小的作为x
if len(xs) < len(ys):
self.index_x = 0
self.index_y = 1
else:
self.index_x = 1
self.index_y = 0
xs, ys = ys, xs
x_dic = {x: i for i, x in enumerate(xs)}
y_dic = {y: j for j, y in enumerate(ys)}
self.x_nodes = [KMNode(x) for x in xs]
self.y_nodes = [KMNode(y) for y in ys]
self.x_length = len(xs)
self.y_length = len(ys)
self.matrix = np.zeros((self.x_length, self.y_length))
for row in x_y_values:
x = row[self.index_x]
y = row[self.index_y]
value = row[2]
x_index = x_dic[x]
y_index = y_dic[y]
self.matrix[x_index, y_index] = value
for i in range(self.x_length):
self.x_nodes[i].exception = max(self.matrix[i, :])
def km(self):
for i in range(self.x_length):
while True:
self.minz = float('inf')
self.set_false(self.x_nodes)
self.set_false(self.y_nodes)
if self.dfs(i):
break
self.change_exception(self.x_nodes, -self.minz)
self.change_exception(self.y_nodes, self.minz)
def dfs(self, i):
x_node = self.x_nodes[i]
x_node.visit = True
for j in range(self.y_length):
y_node = self.y_nodes[j]
if not y_node.visit:
t = x_node.exception + y_node.exception - self.matrix[i][j]
if abs(t) < zero_threshold:
y_node.visit = True
if y_node.match is None or self.dfs(y_node.match):
x_node.match = j
y_node.match = i
return True
else:
if t >= zero_threshold:
self.minz = min(self.minz, t)
return False
def set_false(self, nodes):
for node in nodes:
node.visit = False
def change_exception(self, nodes, change):
for node in nodes:
if node.visit:
node.exception += change
def get_connect_result(self):
ret = []
for i in range(self.x_length):
x_node = self.x_nodes[i]
j = x_node.match
y_node = self.y_nodes[j]
x_id = x_node.id
y_id = y_node.id
value = self.matrix[i][j]
if self.index_x == 1 and self.index_y == 0:
x_id, y_id = y_id, x_id
ret.append((x_id, y_id, value))
return ret
def get_max_value_result(self):
ret = 0
for i in range(self.x_length):
j = self.x_nodes[i].match
ret += self.matrix[i][j]
return ret
def run_kuhn_munkres(x_y_values):
process = KuhnMunkres()
process.set_matrix(x_y_values)
process.km()
return process.get_connect_result()
# def test():
# values = []
# random.seed(0)
# for i in range(500):
# for j in range(1000):
# value = random.random()
# values.append((i, j, value))
#
# return run_kuhn_munkres(values)
if __name__ == '__main__':
s_time = time.time()
# ret = test()
# print("time usage: %s " % str(time.time() - s_time))
values = [
(1, (1,1), 3),
(1, (3,3), 4),
(2, (1,1), 2),
(2, (2,2), 1),
(2, (3,3), 3),
(3, (2,2), 4),
(3, (3,3), 5)
]
print(run_kuhn_munkres(values))
\ No newline at end of file
import math
import Users
import numpy as np
import random
from pprint import pprint
import constants as C
import tool
import ObjectiveFuction as OF
class PSO:
def __init__(self,pre_uavs,users,r_c,r_p,k,N=70,maxgen=200,):
#之后解析JSON,从JSON中读参数
self.N=N
self.k=k
self.pre_uavs=pre_uavs
self.users=users
self.d = 3 # 可行解维数
self.limit = [C.min_range,C.max_range] # 边界位置限制
self.vlimit = [-500, 500] # 边界速度限制
self.vlimit_h=[-10,10]
self.r_c = r_c
self.r_p=r_p
# self.height = 100
self.min_height = C.min_height
self.max_height = C.max_height
self.wmax = 0.9 # 惯性权重
self.wmin = 0.4
self.c1 = 1.496 # 自我学习因子
self.c2 = 1.496 # 群体学习因子
# self.c1 = 0.5 # 自我学习因子
# self.c2 = 0.5 # 群体学习因子
self.maxgen = maxgen
# self.users = Users.getUsers("./data.csv")
self.users = users
self.init_alloc()
# #todo:防止无人机位置碰撞
# def punish_function(self,uavs):
# # user_arr = [1, 2, 5]
# punish=0
# for i in range(len(uavs)):
# for j in range(i+1,len(uavs)):
# dis=self.cal_tool.getDistance(uavs[i],uavs[j])
# if dis<200:
# punish+=100
#
# return punish
def punish_f(self,uavs):
punish=0
max_dis=(C.time_slot-C.run_time)*C.speed
for i in range(len(uavs)):
dis=tool.calculate_3d_distance_uavs(uavs[i],self.pre_uavs[i])
if dis>max_dis:
punish=float('-inf')
return punish
def re_init(self, pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all, ):
self.pre_uavs = pre_uavs
self.user = users
self.r_c = r_c
self.r_p = r_p
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(self.users)):
# r_c[i] = random.randint(1,4)
# return r_c
# 初始化粒子群,k是无人机数量
def initParticle(self, users):
X = []
# users=Users.generate(100)#用户位置
V = np.random.uniform(self.vlimit[0], self.vlimit[1], (self.N, self.k, 3))
V2 = np.random.uniform(self.vlimit_h[0], self.vlimit_h[1], (self.N, self.k, 3))
for i in range(self.N):
uavs=[]
if i==0:
uavs = tool.getUavInitialPos(self.k, users)
else:
for index in range(self.k):
x=np.random.randint(self.limit[0],self.limit[1])
y=np.random.randint(self.limit[0],self.limit[1])
# z=np.random.randint(self.min_height,self.max_height)
z=C.min_height
uavs.append([x,y,z])
X.append(uavs)
X = np.array(X)
return X, V,
def init_alloc(self,):
c_association, p_association, p_all, b_all = OF.objective_resource_avg(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 initBest(self, X,):
p_pos = X.copy() # 每个个体的历史最佳位置
global_pos = np.zeros((self.k, 3)) # 种群的历史最佳位置5*3
p_best = np.full((self.N, 1), float('-inf')) # 每个个体的历史最佳适应度
global_best = float('-inf') # 种群历史最佳适应度
return p_pos, global_pos, p_best, global_best
def pso(self, X, V, update_w,get_fitness,):
# X, V, users = initParticlePos()
p_pos, global_pos, p_best, global_best = self.initBest(X)
result = np.zeros(self.maxgen)
fitness = np.zeros(self.N)
for iter in range(self.maxgen):
# fitness = self.getfitness(X, users, k,P) # 计算所有粒子适应度
for i in range(len(X)):
# punish = self.punish_f(X[i])
# if punish == float('-inf'):
# fitness[i] = punish
# else:
f, _, _ = get_fitness(self.pre_uavs, X[i], self.users, self.r_c, self.r_p, self.p_all, self.b_all,
self.c_association, self.p_association)
fitness[i] = f
# f,_,_=get_fitness(self.pre_uavs,X[i],self.users,self.r_c,self.r_p)
# f,_,_=get_fitness(self.pre_uavs, X[i], self.users, self.r_c,self.r_p, self.p_all, self.b_all, self.c_association,
# self.p_association)
# fitness[i]= f+self.punish_f(X[i])
for i in range(self.N):
if fitness[i] > p_best[i]:
p_best[i] = fitness[i] # 更新个体历史最佳适应度
p_pos[i] = X[i].copy() # 更新个体历史最佳位置(取值)
if max(p_best) > global_best:
global_best = max(p_best) # 更新群体历史最佳适应度
max_index = p_best.argmax()
global_pos = X[max_index].copy() # 更新群体历史最佳位置
# 权重更新
# w = self.wmax - iter * (self.wmax - self.wmin) / self.maxgen
# w = (self.wmax +self.wmin)/2
w=update_w(self.wmin,self.wmax,iter,self.maxgen,iter,fitness)
for i in range(self.N):
V[i] = V[i] * w + self.c1 * random.random() * (p_pos[i] - X[i]) + self.c2 * random.random() * (
global_pos - X[i])
# V2[i] = V2[i] * w + self.c1 * random.random() * (p_pos[i] - X[i]) + self.c2 * random.random() * (
# global_pos - X[i])
# print(V[i])
for j in range(len(V[i])):
for p in range(len(V[i][j])):
if V[i][j][p] > self.vlimit[1]:
V[i][j][p] = self.vlimit[1]
# V[i][j][p] = self.vlimit[0]+np.random.rand(1)*(self.vlimit[1]-self.vlimit[0])
elif V[i][j][p] < self.vlimit[0]:
V[i][j][p] = self.vlimit[0]
# if V2[i][j][p] > self.vlimit_h[1]:
# V2[i][j][p] = self.vlimit_h[1]
# # V[i][j][p] = self.vlimit[0]+np.random.rand(1)*(self.vlimit[1]-self.vlimit[0])
# elif V2[i][j][p] < self.vlimit_h[0]:
# V2[i][j][p] = self.vlimit_h[0]
# print(V[i])
# 位置更新
X = X + V
# 边界位置处理
for i in range(self.N):
for j in range(len(X[i])):
for p in range(2):
if X[i][j][p] > self.limit[1]:
X[i][j][p] = self.limit[1]
elif X[i][j][p] < self.limit[0]:
X[i][j][p] = self.limit[0]
X[i][j][2]=self.min_height
# if X[i][j][2] > self.max_height:
# X[i][j][2] = self.max_height
# elif X[i][j][2] < self.min_height:
# X[i][j][2] = self.min_height
result[iter] = global_best
print(iter,global_pos,global_best)
# print(global_best)
# print(global_pos)
return global_pos,global_best,result
if __name__ == '__main__':
uavs=[[868.34535881,315.18340086,50. ],
[292.96443022,729.7612657,77.75450997],
[732.25467955,927.62861821,50. ],
[303.40107629,240.31208079,150. ]]
# 示例
# print(0.012 / 8 * 1.225 * 0.05 * 0.79 * 400 ** 3 * 0.5 ** 3)
# print((1+0.1)*100**1.5/math.sqrt(2*1.225*0.79))
best=[[335,772,67], [382,739,75], [1758,1683,137], [885,762,133], [403,1196,94], [1049,358,88]]
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29
1.0,1.0,1.0,4.0,4.0,4.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,1.0,1.0,2.0,4.0,1.0,2.0,2.0,4.0,2.0,1.0,4.0,2.0,1.0,3.0,2.0,1.0,2.0
2.0,2.0,2.0,2.0,1.0,1.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,4.0,2.0,1.0,4.0,3.0,2.0,1.0,1.0,2.0,1.0,1.0,2.0
4.0,2.0,2.0,4.0,2.0,4.0,1.0,2.0,2.0,4.0,1.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,3.0,2.0,1.0,2.0,4.0
2.0,1.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,4.0,1.0,4.0,2.0,4.0,2.0,1.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,2.0
2.0,2.0,1.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,3.0,2.0,2.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0
2.0,1.0,2.0,2.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,4.0,4.0,1.0,4.0,2.0,3.0,1.0
2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,1.0,4.0,1.0,1.0,2.0,1.0,2.0,1.0,1.0,1.0,2.0,4.0,1.0,2.0,2.0,3.0,2.0,2.0
2.0,2.0,1.0,2.0,2.0,2.0,4.0,2.0,1.0,4.0,1.0,1.0,2.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,4.0,1.0,2.0,4.0,2.0,2.0,2.0,2.0
2.0,4.0,2.0,1.0,3.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0,4.0,1.0,4.0,2.0,2.0,4.0,1.0,4.0,2.0,2.0,1.0,4.0,1.0,2.0,2.0
2.0,3.0,2.0,2.0,2.0,1.0,4.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,1.0,3.0,1.0,4.0,2.0,4.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0
2.0,3.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,4.0,1.0,2.0,2.0,4.0,1.0,1.0,2.0,2.0,1.0,1.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,4.0,2.0,1.0
1.0,4.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,1.0,2.0,4.0,1.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,1.0,4.0,4.0,1.0,2.0,4.0
1.0,2.0,1.0,1.0,3.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,1.0,1.0,2.0,4.0,1.0,4.0,1.0,2.0,1.0,4.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0
2.0,4.0,1.0,2.0,2.0,1.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,4.0,2.0,1.0,4.0,2.0,4.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0
2.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,3.0,2.0,2.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,1.0,4.0,2.0,3.0,2.0,1.0,2.0,2.0
2.0,2.0,1.0,4.0,2.0,3.0,2.0,2.0,1.0,4.0,2.0,2.0,2.0,1.0,2.0,4.0,4.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0
2.0,3.0,2.0,2.0,1.0,1.0,2.0,4.0,2.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,1.0,2.0,1.0,2.0,1.0,1.0
2.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0,1.0,4.0,2.0,2.0,2.0,4.0,4.0,1.0,1.0,1.0,4.0,3.0,2.0,1.0,2.0,3.0,2.0,4.0,2.0,2.0,4.0,2.0
2.0,2.0,4.0,3.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,4.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0
2.0,1.0,3.0,2.0,2.0,4.0,2.0,1.0,4.0,2.0,4.0,2.0,1.0,3.0,2.0,4.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0
1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,4.0,4.0,2.0,4.0,2.0,1.0,4.0,2.0,2.0,2.0,1.0,4.0,4.0,3.0,4.0,2.0
2.0,2.0,2.0,1.0,4.0,1.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,4.0
1.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,3.0,2.0,2.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0
2.0,4.0,2.0,2.0,2.0,4.0,2.0,1.0,2.0,1.0,4.0,1.0,2.0,2.0,4.0,1.0,1.0,1.0,3.0,2.0,1.0,2.0,1.0,4.0,2.0,2.0,2.0,3.0,3.0,1.0
4.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,2.0,3.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,1.0,1.0,3.0,2.0,1.0,2.0,1.0,2.0,4.0,4.0,2.0
2.0,2.0,2.0,1.0,1.0,2.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,1.0,1.0,4.0,2.0,4.0,2.0,2.0,2.0,2.0
4.0,2.0,4.0,1.0,2.0,2.0,1.0,1.0,1.0,2.0,1.0,1.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,4.0,2.0,2.0,4.0,4.0,1.0,1.0,4.0,2.0,2.0,2.0
4.0,2.0,3.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,2.0,2.0,4.0,1.0,4.0,2.0,1.0,1.0,2.0,4.0,4.0,2.0,2.0,4.0,2.0
1.0,4.0,2.0,4.0,2.0,2.0,1.0,4.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,2.0,2.0,1.0,4.0,1.0,1.0,2.0,2.0,2.0,2.0,3.0,2.0,2.0,2.0,2.0
4.0,2.0,1.0,2.0,2.0,1.0,4.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0,4.0,1.0,1.0,4.0,1.0,2.0,2.0,2.0,2.0,4.0,1.0,2.0,1.0,1.0
1.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,4.0,3.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,3.0,2.0,2.0,1.0,2.0
2.0,2.0,2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0,2.0,2.0,2.0,3.0,2.0,2.0,1.0,2.0,2.0,1.0,1.0,4.0,1.0,4.0,2.0,3.0,2.0,2.0,4.0,1.0
1.0,2.0,2.0,1.0,2.0,1.0,3.0,1.0,2.0,2.0,4.0,2.0,2.0,4.0,1.0,2.0,1.0,4.0,2.0,1.0,1.0,4.0,1.0,2.0,4.0,2.0,2.0,1.0,4.0,2.0
4.0,1.0,3.0,1.0,2.0,2.0,1.0,1.0,2.0,3.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,4.0,2.0,1.0,1.0,2.0,2.0,1.0,4.0,2.0,2.0,2.0,2.0
1.0,2.0,4.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,1.0,1.0,1.0,1.0,1.0,4.0,1.0,2.0,2.0,1.0,1.0,4.0,2.0,2.0,2.0,4.0,2.0,2.0,4.0
2.0,1.0,3.0,2.0,2.0,2.0,4.0,4.0,4.0,1.0,2.0,2.0,2.0,4.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,3.0,2.0,2.0,2.0,4.0,2.0,2.0
2.0,2.0,1.0,2.0,2.0,4.0,2.0,1.0,3.0,2.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0
1.0,2.0,3.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,4.0,2.0,4.0,1.0,4.0,1.0,2.0,4.0,2.0,1.0,4.0,2.0,4.0,2.0,1.0,2.0,2.0,1.0
2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,1.0,4.0,1.0,4.0,2.0,2.0,1.0,3.0,1.0,2.0,2.0,1.0,2.0,4.0,3.0,2.0,4.0
2.0,4.0,1.0,2.0,1.0,4.0,2.0,1.0,1.0,1.0,2.0,3.0,4.0,2.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,2.0,4.0,1.0,4.0,2.0,2.0,2.0,2.0
2.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,1.0,4.0,1.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,1.0
2.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,4.0,3.0,4.0,1.0,2.0,2.0,3.0,2.0,3.0,3.0,2.0,1.0,3.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0
2.0,3.0,2.0,2.0,1.0,2.0,3.0,2.0,4.0,2.0,2.0,2.0,4.0,2.0,4.0,2.0,2.0,2.0,1.0,2.0,3.0,4.0,3.0,4.0,2.0,1.0,4.0,2.0,2.0,2.0
4.0,2.0,2.0,4.0,1.0,1.0,2.0,2.0,1.0,4.0,1.0,4.0,2.0,1.0,1.0,1.0,2.0,4.0,2.0,4.0,1.0,2.0,1.0,1.0,1.0,1.0,2.0,2.0,2.0,1.0
2.0,2.0,2.0,4.0,1.0,1.0,1.0,4.0,2.0,2.0,2.0,2.0,2.0,3.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,4.0,3.0,4.0,2.0,2.0
2.0,2.0,1.0,1.0,2.0,4.0,2.0,2.0,1.0,4.0,3.0,2.0,4.0,1.0,4.0,2.0,4.0,4.0,2.0,2.0,2.0,2.0,4.0,2.0,3.0,2.0,2.0,2.0,2.0,2.0
2.0,2.0,1.0,4.0,1.0,2.0,2.0,1.0,3.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,2.0,4.0,2.0,1.0
2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,3.0,1.0,1.0,2.0
1.0,4.0,1.0,2.0,2.0,1.0,2.0,3.0,4.0,1.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,3.0,4.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0
2.0,2.0,1.0,2.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0,3.0,2.0,2.0,3.0,4.0,2.0,1.0,1.0,2.0,3.0,4.0,1.0,2.0,1.0,2.0,2.0,2.0,4.0,2.0
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29
2.0,2.0,1.0,1.0,2.0,2.0,4.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,3.0,2.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,1.0,2.0,3.0
2.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,2.0,1.0,4.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,3.0
2.0,1.0,2.0,2.0,1.0,2.0,4.0,3.0,2.0,2.0,4.0,2.0,2.0,3.0,4.0,1.0,3.0,2.0,2.0,4.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0
2.0,1.0,1.0,1.0,2.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0,4.0,4.0,2.0,4.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0
2.0,2.0,4.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,4.0,2.0,1.0,2.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,2.0,4.0,2.0,2.0,4.0,1.0,2.0,1.0,1.0
2.0,2.0,1.0,2.0,1.0,2.0,1.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,3.0,2.0,1.0,1.0,2.0,2.0,3.0,1.0,2.0,2.0
2.0,1.0,4.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,1.0,2.0,1.0,1.0,4.0
1.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,3.0,1.0,1.0,2.0,2.0,1.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0
4.0,2.0,2.0,2.0,3.0,2.0,4.0,2.0,4.0,4.0,2.0,1.0,1.0,2.0,4.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0
3.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,4.0,2.0,2.0,1.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,2.0,4.0,4.0,2.0
4.0,2.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0,3.0,2.0,4.0,1.0,2.0,1.0,2.0,4.0,1.0,2.0,2.0,2.0,1.0,4.0,3.0,2.0,2.0,2.0,2.0,2.0
2.0,2.0,3.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,1.0,1.0,1.0,2.0,4.0,1.0,4.0,2.0,1.0,2.0,2.0,1.0,2.0,2.0,4.0,2.0,1.0
2.0,1.0,2.0,2.0,4.0,2.0,1.0,1.0,1.0,2.0,2.0,3.0,3.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,1.0,1.0,4.0,4.0,2.0,2.0,2.0,2.0,4.0,3.0
2.0,2.0,4.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,1.0,4.0,2.0,4.0,3.0,3.0,1.0,4.0,3.0,2.0
4.0,1.0,2.0,1.0,2.0,2.0,4.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,1.0,2.0,1.0,4.0,1.0,4.0,1.0,2.0,2.0,2.0,2.0,4.0,4.0,4.0,2.0,2.0
4.0,2.0,1.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,3.0,1.0,2.0,1.0,2.0,1.0,2.0,4.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,1.0,3.0,2.0
2.0,2.0,2.0,1.0,1.0,4.0,4.0,1.0,2.0,2.0,4.0,2.0,2.0,2.0,4.0,2.0,4.0,2.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0,4.0
2.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,4.0,2.0,2.0,1.0,2.0,3.0,1.0,4.0,1.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0
1.0,1.0,2.0,2.0,1.0,1.0,4.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,1.0,2.0,4.0,2.0,1.0,2.0,1.0,2.0,1.0,1.0,2.0
2.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0,2.0,4.0,2.0,1.0,1.0,1.0,2.0,2.0,3.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,1.0
2.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0,1.0,1.0,4.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0
2.0,2.0,1.0,1.0,2.0,2.0,2.0,4.0,2.0,4.0,2.0,1.0,3.0,2.0,4.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,1.0,1.0,2.0,2.0
2.0,4.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,3.0,1.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,1.0,2.0,2.0
2.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,1.0,2.0,2.0,3.0,2.0,2.0,2.0,3.0,2.0,2.0,4.0,2.0,2.0,4.0,1.0,3.0,2.0,1.0,2.0
2.0,4.0,4.0,2.0,1.0,1.0,3.0,1.0,2.0,2.0,1.0,1.0,2.0,4.0,1.0,1.0,4.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0
2.0,4.0,2.0,2.0,2.0,2.0,4.0,1.0,1.0,2.0,2.0,1.0,4.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,4.0,1.0,1.0,4.0,2.0,2.0,2.0,1.0,2.0,2.0
3.0,2.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,1.0,1.0,1.0,2.0
1.0,2.0,2.0,1.0,1.0,1.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,4.0,1.0,1.0,2.0,1.0,2.0,4.0,2.0,1.0,4.0,4.0,2.0,1.0,2.0,2.0,4.0,1.0
2.0,2.0,2.0,3.0,1.0,1.0,2.0,1.0,4.0,2.0,4.0,4.0,1.0,1.0,1.0,2.0,4.0,1.0,1.0,1.0,1.0,2.0,1.0,4.0,2.0,2.0,2.0,2.0,4.0,2.0
2.0,1.0,2.0,4.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,3.0,1.0,2.0,2.0,1.0,4.0,4.0,2.0,4.0,4.0,1.0,1.0,2.0,2.0
2.0,2.0,1.0,2.0,2.0,1.0,4.0,4.0,2.0,1.0,2.0,2.0,4.0,2.0,2.0,1.0,4.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,1.0,2.0,2.0,1.0,2.0,2.0
1.0,1.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,1.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0
2.0,2.0,2.0,1.0,1.0,2.0,1.0,3.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0,1.0,1.0,2.0,2.0,1.0,2.0,2.0,1.0,4.0,4.0,3.0,2.0,2.0,4.0,1.0
2.0,2.0,1.0,4.0,4.0,1.0,2.0,2.0,4.0,2.0,4.0,2.0,1.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,3.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0
2.0,2.0,3.0,1.0,4.0,2.0,2.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,4.0,4.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,1.0,1.0
2.0,2.0,1.0,1.0,2.0,1.0,1.0,4.0,2.0,4.0,4.0,1.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,1.0,4.0,4.0,2.0,1.0,2.0,1.0,2.0,4.0,1.0,4.0
3.0,1.0,2.0,2.0,2.0,2.0,1.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,4.0,1.0,1.0,4.0,2.0,2.0,2.0,1.0,2.0,4.0,3.0,1.0,2.0,1.0
2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,1.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,1.0,4.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0
4.0,1.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,2.0,1.0,4.0,2.0,1.0,2.0,1.0,3.0,3.0,1.0,1.0,1.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0
2.0,2.0,2.0,1.0,1.0,2.0,1.0,1.0,1.0,2.0,4.0,2.0,2.0,2.0,1.0,4.0,2.0,2.0,2.0,1.0,1.0,2.0,1.0,2.0,1.0,1.0,2.0,2.0,1.0,2.0
1.0,1.0,2.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,4.0,1.0,2.0,2.0,4.0,2.0,4.0,4.0,2.0,2.0,4.0,1.0,3.0,2.0,4.0,3.0,2.0,2.0,2.0
2.0,2.0,1.0,2.0,2.0,2.0,1.0,4.0,2.0,1.0,4.0,1.0,4.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,3.0,2.0,4.0,4.0,1.0,2.0,2.0,1.0,2.0,2.0
4.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,4.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,4.0,2.0,4.0
2.0,4.0,1.0,2.0,2.0,2.0,1.0,2.0,4.0,4.0,1.0,4.0,2.0,4.0,1.0,4.0,1.0,3.0,1.0,4.0,2.0,1.0,2.0,1.0,2.0,2.0,2.0,2.0,4.0,2.0
1.0,2.0,2.0,3.0,2.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,1.0,2.0,4.0,1.0,4.0,1.0,4.0,2.0,4.0,1.0,2.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0
4.0,2.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,4.0,1.0,4.0,2.0,4.0,2.0,4.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,4.0,4.0,1.0,2.0,1.0,4.0
2.0,1.0,2.0,2.0,4.0,1.0,2.0,2.0,2.0,4.0,4.0,1.0,4.0,4.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,4.0,3.0,2.0,2.0,1.0,1.0,4.0
1.0,2.0,4.0,1.0,4.0,2.0,2.0,2.0,1.0,2.0,2.0,1.0,3.0,3.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,2.0,2.0
1.0,1.0,4.0,2.0,4.0,4.0,4.0,2.0,2.0,4.0,2.0,4.0,4.0,2.0,1.0,1.0,2.0,2.0,1.0,1.0,1.0,1.0,2.0,1.0,2.0,1.0,4.0,2.0,1.0,2.0
4.0,2.0,4.0,2.0,2.0,3.0,3.0,2.0,4.0,3.0,2.0,4.0,2.0,2.0,2.0,2.0,4.0,3.0,2.0,1.0,4.0,1.0,3.0,2.0,4.0,2.0,1.0,4.0,2.0,2.0
2023-12-08 19:08:42,025 - pyswarms.single.global_best - INFO - Optimize for 100 iters with {'c1': 0.5, 'c2': 0.3, 'w': 0.9, 'k': 3, 'p': 2}
2023-12-08 19:08:42,055 - pyswarms.single.global_best - INFO - Optimization finished | best cost: 16.89331204358824, best pos: [-0.20657694 -1.67142459]
2023-12-08 19:12:57,642 - pyswarms.single.global_best - INFO - Optimize for 100 iters with {'c1': 0.5, 'c2': 0.3, 'w': 0.9, 'k': 3, 'p': 2}
2023-12-08 19:12:57,668 - pyswarms.single.global_best - INFO - Optimization finished | best cost: 31.816129723241335, best pos: [1.84784183 1.87663107]
2023-12-08 19:13:47,923 - pyswarms.single.global_best - INFO - Optimize for 100 iters with {'c1': 0.5, 'c2': 0.3, 'w': 0.9, 'k': 3, 'p': 2}
2023-12-08 19:13:47,950 - pyswarms.single.global_best - INFO - Optimization finished | best cost: 56.773199869733325, best pos: [3.23664274 0.52956792]
import math
import random
import warnings
import tool
import Users
import cvxpy as cp
import numpy as np
import constants as C
def cal_b_u(users,uavs,uav_index,uav_to_user,r_c,p_alloc,B_max,R_min,u=1.05):
users_index = uav_to_user[uav_index]
n=len(users_index) # 变量数量
# 定义变量
x = cp.Variable(n, pos=True) # 非负变量
c=[]# 目标函数系数
for i in users_index:
p=p_alloc[i]
snr = tool.cal_snr_f(uavs[uav_index], users[i], p)
factor=math.log2(1 + snr)
c.append(factor)
c = np.array(c)
# print(c)
# 定义目标函数
objective = cp.Maximize(c @ x)
constant_limit = B_max # 约束条件中的常数上限
# 定义约束条件
constraints = [cp.sum(x) <= constant_limit]
min_cons=[]
# u=1.05# 1.05
for i in range(len(users_index)):
index=users_index[i]
p = p_alloc[index]
snr = tool.cal_snr_f(uavs[uav_index], users[index], p)
lower_limit = R_min*(r_c[index])*u/math.log2(1 + snr)
lower_limit=round(lower_limit, 4)
# print(lower_limit)
min_cons.append(lower_limit)
constraints.append(x[i] >= lower_limit)
# 构建问题并求解
problem = cp.Problem(objective, constraints)
problem.solve()
# 输出求解结果
# print("带宽分配后速率最大值:", problem.value)
# print("带宽最优解:", x.value)
# rate=[]
# for i in range(len(users_index)):
# rate.append(c[i]*x.value[i])
# print("速率:",rate)
b_alloc = {}
if problem.status == cp.OPTIMAL:
b_alloc_list=x.value
for i in range(len(users_index)):
b_alloc[users_index[i]]=b_alloc_list[i]
return b_alloc, problem.value
else:
# todo:没有最优解的情况
sum_weight = 0
sum_rate=0
for i in users_index:
sum_weight += r_c[i]
for i in users_index:
# b_alloc[i] = C.B_max * r_c[i] / sum_weight
b_alloc[i]=C.B_max/len(users_index)
cur_rate = tool.cal_rate(b_alloc[i], p_alloc[i], uavs[uav_index], users[i])
sum_rate += cur_rate
return b_alloc,sum_rate
# lower_cons={}
# for i in range(len(users_index)):
# lower_cons[min_cons[i]]=users_index[i]
# sorted_list=sorted(min_cons)
# sum_b=0
# cur_index=len(sorted_list)
# for i in range(len(sorted_list)):
# if sorted_list[i]+sum_b<=B_max:
# sum_b+=sorted_list[i]
# index=lower_cons[sorted_list[i]]
# b_alloc[index]=sorted_list[i]
# else:
# cur_index=i
# break
# num_b=0
# rest_b=B_max-sum_b
# for i in range(cur_index,len(sorted_list)):
# num_b+=sorted_list[i]
# for i in range(cur_index, len(sorted_list)):
# index=lower_cons[sorted_list[i]]
# b_alloc[index]=rest_b*sorted_list[i]/num_b
def cal_b_maxmin(users,uavs,uav_index,uav_to_user,r_c,p_alloc,B_max,R_min):
users_index = uav_to_user[uav_index]
n=len(users_index) # 变量数量
# 定义变量
x = cp.Variable(n, nonneg=True) # 非负变量
min_rate=cp.Variable()
c=[]# 目标函数系数
constant_limit = B_max # 约束条件中的常数上限
# 定义约束条件
constraints = [cp.sum(x) <= constant_limit]
for i in range(len(users_index)):
index=users_index[i]
p=p_alloc[index]
snr = tool.cal_snr_f(uavs[uav_index], users[index], p)
factor=math.log2(1 + snr)
constraints.append(min_rate<=cp.multiply(x[i],factor))
c.append(factor)
c = np.array(c)
print(c)
# 定义目标函数
objective = cp.Maximize(min_rate)
min_cons=[]
for i in range(len(users_index)):
index=users_index[i]
p = p_alloc[index]
snr = tool.cal_snr_f(uavs[uav_index], users[index], p)
lower_limit = R_min*r_c[index]/math.log2(1 + snr)
# lower_limit=round(lower_limit, 2)
print(lower_limit)
min_cons.append(lower_limit)
constraints.append(x[i] >= lower_limit)
# 构建问题并求解
problem = cp.Problem(objective, constraints)
problem.solve()
# 输出求解结果
# print("带宽分配后最大最小速率为:", problem.value)
# print("带宽最优解:", x.value)
rate=[]
for i in range(len(users_index)):
rate.append(c[i]*x.value[i])
# print("速率:", rate)
b_alloc = {}
if problem.status != cp.INFEASIBLE:
b_alloc_list=x.value
for i in range(len(users_index)):
b_alloc[users_index[i]]=b_alloc_list[i]
else:
# todo:没有最优解的情况,将所需带宽从小到大排序,依次分配,直到剩下的带宽不够分配,然后将剩余带宽按所需比例分配其他人
lower_cons={}
for i in range(len(users_index)):
lower_cons[min_cons[i]]=users_index[i]
sorted_list=sorted(min_cons)
sum_b=0
cur_index=len(sorted_list)
for i in range(len(sorted_list)):
if sorted_list[i]+sum_b<=B_max:
sum_b+=sorted_list[i]
index=lower_cons[sorted_list[i]]
b_alloc[index]=sorted_list[i]
else:
cur_index=i
break
num_b=0
rest_b=B_max-sum_b
for i in range(cur_index,len(sorted_list)):
num_b+=sorted_list[i]
for i in range(cur_index, len(sorted_list)):
index=lower_cons[sorted_list[i]]
b_alloc[index]=rest_b*sorted_list[i]/num_b
return b_alloc,problem.value
def cal_p_by_CVX_u(users,uavs,uav_index,uav_to_user,r_c,b_alloc,P_rest,R_min,snr_thre,u=1.05):
users_index = uav_to_user[uav_index]
# 定义变量和常数
n = len(users_index) # 变量数量
a = [] # 目标函数系数
for i in users_index:
a.append(b_alloc[i])
a=np.array(a)
constant_limit = P_rest # 约束条件中的常数上限
c=[]
for i in users_index:
loss = tool.forest_path_loss(uavs[uav_index], users[i])
factor=(10 ** (-loss / 10))/((10 ** (C.noise / 10))/1000)
c.append(factor)
c=np.array(c)
# 定义变量
x = cp.Variable(n, pos=True) # 正数变量
# 定义目标函数
log_terms = [cp.log(1+c[i]*x[i])/np.log(2) for i in range(n)] # log 函数每项
objective = cp.Maximize(a @ log_terms)
# u=1.05
# 定义约束条件
constraints = [cp.sum(x) <= constant_limit]
for i in range(len(users_index)):
index=users_index[i]
loss = tool.forest_path_loss(uavs[uav_index],users[index])
lower_limit=10**(snr_thre/10)*((10 ** (C.noise / 10))/1000) / (10 ** (-loss / 10))
constraints.append(x[i] >= lower_limit)
number = R_min * (r_c[index])*u/ b_alloc[index]
noise_power = (10 ** (C.noise / 10)) / 1000
lower_limit2=(math.pow(2,number)-1)*noise_power/10 ** (-loss / 10)
constraints.append(x[i] >= lower_limit2)
# 构建问题并求解
problem = cp.Problem(objective, constraints)
problem.solve()
p_alloc={}
if problem.status == cp.OPTIMAL:
# 输出求解结果
# print("功率分配后最大值:", problem.value)
# print("功率最优解:", x.value)
p_alloc_list = x.value
for i in range(len(users_index)):
p_alloc[users_index[i]] = p_alloc_list[i]
return p_alloc,problem.value
else:
sum_weight = 0
sum_rate=0
for i in users_index:
sum_weight += r_c[i]
for i in users_index:
# p_alloc[i] = P_rest * r_c[i] / sum_weight
p_alloc[i]=P_rest/len(users_index)
cur_rate = tool.cal_rate(b_alloc[i], p_alloc[i], uavs[uav_index], users[i])
sum_rate+=cur_rate
return p_alloc,sum_rate
# p_alloc=cal_p(users,uavs,uav_index,uav_to_user,r_c,b_alloc,P_rest,R_min,snr_thre)
# print(p_alloc)
def cal_p(users,uavs,uav_index,uav_to_user,r_c,b_alloc,P_rest,R_min,snr_thre):
users_index = uav_to_user[uav_index]
# 人数
n = len(users_index)
p_alloc={}
num=0
for i in users_index:
loss = tool.forest_path_loss(uavs[uav_index], users[i])
noise_power = (10 ** (C.noise / 10)) / 1000
num+=noise_power/10 ** (-loss / 10)
sum_p=0
cur_index=0
for i in users_index:
# lamda=n*b_alloc[i]/((P_rest+num)*math.log(2))
loss = tool.forest_path_loss(uavs[uav_index], users[i])
noise_power = (10 ** (C.noise / 10)) / 1000
p1=(P_rest+num)/n-noise_power/10 ** (-loss / 10)
p2=tool.get_p_by_snr_f(snr_thre,uavs[uav_index],users[i],C.noise)
number=R_min*r_c[i]/b_alloc[i]
p3=(math.pow(2,number)-1)*noise_power/10 ** (-loss / 10)
max_p=max(max(p1,p2),p3)
p_alloc[i]=max_p
sum_p+=max_p
if p1>p3:
cur_index=i
print(p1,p2,p3)
print(sum_p)
if sum_p-P_rest>0:
p_alloc[cur_index]-=sum_p-P_rest
print(p_alloc)
return p_alloc
def resource_alloc_u(users,uavs,r_c,p_connection,uav_to_user):
with warnings.catch_warnings():
# 忽略特定类型的警告
warnings.filterwarnings("ignore", message="Solution may be inaccurate.", category=UserWarning)
best=float('-inf')
p_rest=tool.get_rest_p(users,uavs,p_connection)
# p_alloc={}
# b_alloc={}
#平分功率,带宽
p_all = []
b_all = []
best_all = []
rate=[]
for i in range(len(uavs)):
p_alloc={}
b_alloc={}
sub=1000
for j in uav_to_user[i]:
b_alloc[j] = C.B_max / len(uav_to_user[i])
p_alloc[j] = p_rest[i] / 4
while sub>1:
# b_alloc, cur_objective = cal_b(users, uavs, i, uav_to_user, r_c, p_alloc, C.B_max, C.R_min)
p_alloc,best=cal_p_by_CVX_u(users, uavs, i, uav_to_user, r_c, b_alloc, p_rest[i], C.R_min, C.snr_thre,1.05)
b_alloc, cur_objective = cal_b_u(users, uavs, i, uav_to_user, r_c, p_alloc, C.B_max, C.R_min,1.05)
sub=abs(best-cur_objective)
# best=max(best,cur_objective)
for j in uav_to_user[i]:
cur_rate = tool.cal_rate(b_alloc[j], p_alloc[j], uavs[i], users[j])
rate.append(cur_rate)
p_all.append(p_alloc)
b_all.append(b_alloc)
best_all.append(best)
# print("功率:",p_all)
# print("带宽:",b_all)
# print("所有速率:",best_all)
return p_all,b_all,rate
def resource_alloc(users,uavs,r_c,p_connection,uav_to_user):
with warnings.catch_warnings():
# 忽略特定类型的警告
warnings.filterwarnings("ignore", message="Solution may be inaccurate.", category=UserWarning)
best=float('-inf')
p_rest=tool.get_rest_p(users,uavs,p_connection)
# p_alloc={}
# b_alloc={}
#平分功率,带宽
p_all = []
b_all = []
best_all = []
rate=[]
for i in range(len(uavs)):
p_alloc={}
b_alloc={}
sub=1000
for j in uav_to_user[i]:
b_alloc[j] = C.B_max / len(uav_to_user[i])
p_alloc[j] = p_rest[i] / 4
while sub>1:
# b_alloc, cur_objective = cal_b(users, uavs, i, uav_to_user, r_c, p_alloc, C.B_max, C.R_min)
p_alloc,best=cal_p_by_CVX_u(users, uavs, i, uav_to_user, r_c, b_alloc, p_rest[i], C.R_min, C.snr_thre,1)
b_alloc, cur_objective = cal_b_u(users, uavs, i, uav_to_user, r_c, p_alloc, C.B_max, C.R_min,1)
sub=abs(best-cur_objective)
# best=max(best,cur_objective)
for j in uav_to_user[i]:
cur_rate = tool.cal_rate(b_alloc[j], p_alloc[j], uavs[i], users[j])
rate.append(cur_rate)
p_all.append(p_alloc)
b_all.append(b_alloc)
best_all.append(best)
# print("功率:",p_all)
# print("带宽:",b_all)
# print("所有速率:",best_all)
return p_all,b_all,rate
def resource_alloc_proportion(users,uavs,r_c,p_connection,uav_to_user):
best = float('-inf')
p_rest = tool.get_rest_p(users, uavs, p_connection)
p_all=[]
b_all=[]
sum_weight=[0 for i in range(len(uavs))]
rate=[]
for i in range(len(uavs)):
for j in uav_to_user[i]:
sum_weight[i] += r_c[j]
for i in range(len(uavs)):
p_alloc = {}
b_alloc = {}
for j in uav_to_user[i]:
p_alloc[j] = p_rest[i]*r_c[j] /sum_weight[i]
b_alloc[j]=C.B_max*r_c[j] /sum_weight[i]
cur_rate=tool.cal_rate(b_alloc[j],p_alloc[j],uavs[i],users[j])
rate.append(cur_rate)
p_all.append(p_alloc)
b_all.append(b_alloc)
# print(p_alloc,b_alloc)
return p_all,b_all,rate
def resource_alloc_avg(users,uavs,r_c,p_connection,uav_to_user):
best = float('-inf')
p_rest = tool.get_rest_p(users, uavs, p_connection)
p_all=[]
b_all=[]
sum_weight=[0 for i in range(len(uavs))]
rate=[]
for i in range(len(uavs)):
for j in uav_to_user[i]:
sum_weight[i] += r_c[j]
for i in range(len(uavs)):
p_alloc = {}
b_alloc = {}
for j in uav_to_user[i]:
p_alloc[j] = p_rest[i]/len(uav_to_user[i])
b_alloc[j]=C.B_max/len(uav_to_user[i])
cur_rate=tool.cal_rate(b_alloc[j],p_alloc[j],uavs[i],users[j])
rate.append(cur_rate)
p_all.append(p_alloc)
b_all.append(b_alloc)
# print(p_alloc,b_alloc)
return p_all,b_all,rate
#非凸求解不了
def resource_CVX(users,uavs,uav_index,uav_to_user,r_c,B_max,P_rest,R_min,snr_thre):
users_index = uav_to_user[uav_index]
# 人数
n = len(users_index)
b = cp.Variable(n,pos=True) # 正数变量)
p = cp.Variable(n,pos=True)
c = []
log_terms = 0 # 将 log_terms 初始化为 0
for i in range(len(users_index)):
index=users_index[i]
loss = tool.forest_path_loss(uavs[uav_index], users[index])
factor = (10 ** (-loss / 10)) / ((10 ** (C.noise / 10)) / 1000)
c.append(factor)
log_terms += b[i]*cp.log(1 + factor * p[i]) / np.log(2)
c = np.array(c)
# log_terms = [cp.log(1 + c[i] * p[i]) / np.log(2) for i in range(n)] # log 函数每项
# objective = cp.Maximize(cp.sum(cp.multiply(b,log_terms)))
# log_terms = [cp.log(1 + c[i] * p[i]) / np.log(2) for i in range(n)] # log 函数每项
objective = cp.Maximize(log_terms)
constraints = [cp.sum(p) <= P_rest,cp.sum(b) <= B_max]
for i in range(len(users_index)):
index = users_index[i]
loss = tool.forest_path_loss(uavs[uav_index], users[index])
lower_limit = 10 ** (snr_thre / 10) * ((10 ** (C.noise / 10)) / 1000) / (10 ** (-loss / 10))
constraints.append(p[i] >= lower_limit)
# number = R_min * r_c[index] / b[i]
noise_power = (10 ** (C.noise / 10)) / 1000
# lower_limit2 = (math.pow(2, R_min * r_c[index] / b[i]) - 1) * noise_power / 10 ** (-loss / 10)
factor = (10 ** (-loss / 10)) / ((10 ** (C.noise / 10)) / 1000)
constraints.append( b[i]*cp.log(1 + factor * p[i]) / np.log(2)>=R_min * r_c[index] )
# constraints.append(p[i] >= (math.pow(2, R_min * r_c[index] / b[i]) - 1) * noise_power / 10 ** (-loss / 10))
# snr = tool.cal_snr_f(uavs[uav_index], users[index], p[i])
# lower_limit = R_min * r_c[index] / math.log2(1 + p[i]*(10 ** (-loss / 10))/noise_power)
# lower_limit=round(lower_limit, 2)
# constraints.append(b[i] >= R_min * r_c[index] / math.log2(1 + p[i]*(10 ** (-loss / 10))/noise_power))
problem = cp.Problem(objective, constraints)
problem.solve(verbose=True)
return
if __name__ == '__main__':
users = Users.getUsers("./data4.csv")
uavs = tool.getUavInitialPos(7, users)
c_connection = tool.get_c_association(users, uavs, math.ceil(len(users) / len(uavs)))
p_connection = tool.get_p_association(users, uavs, c_connection, math.ceil(len(users) * 2 / len(uavs)))
uav_to_user=tool.get_uav_to_user(c_connection, uavs)
print(uav_to_user)
p_alloc ={}
r_c = {}
r=1
for i in range(len(uavs)):
for j in uav_to_user[i]:
p_alloc[j]=0.09/4
r_c[j]=2
r=r+1
print(r_c)
p_rest = tool.get_rest_p(users, uavs, p_connection)
# cal_b_maxmin(users, uavs, 0, uav_to_user, r_c, p_alloc, C.B_max, C.R_min)
# cal_b(users, uavs, 0, uav_to_user, r_c, p_alloc, C.B_max, C.R_min)
# resource_alloc_avg(users, uavs, r_c, p_connection, uav_to_user)
resource_alloc(users, uavs, r_c, p_connection, uav_to_user)
# resource_CVX(users,uavs,0,uav_to_user,r_c,C.B_max,p_rest[0],C.R_min,C.snr_thre)
# B_max=10/4 #10M
# R_min=0.2
# p_rest = tool.get_rest_p(users, uavs, p_connection)
# print(p_rest)
# b_alloc=cal_b(users,uavs,0,uav_to_user,r_c,p_alloc,B_max,R_min)
# print(b_alloc)
# p_alloc=cal_p_by_CVX(users,uavs,0,uav_to_user,r_c,b_alloc,p_rest[0],R_min,0)
# b_alloc = cal_b(users, uavs, 0, uav_to_user, r_c, p_alloc, B_max, R_min)
# p_alloc = cal_p_by_CVX(users, uavs, 0, uav_to_user, r_c, b_alloc, p_rest[0], R_min, 0)
This source diff could not be displayed because it is too large. You can view the blob instead.
#归一化pso
import math
import time
from itertools import combinations
import numpy as np
from matplotlib import pyplot as plt
import Users
from pso import PSO
from improvedPSO import CPSO
import tool
import GDOP
import ObjectiveFuction as OF
import constants as C
import dynamicProcess as dynamic
plt.style.use('seaborn-whitegrid')
# 设置字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
#slot1为长时间尺度,slot2短时间尺度
def whole_process(users,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
fitness=[]
df_c=dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
e=0
for i in range(0,10*slot1,slot2):
users_loc = dynamic.gauss_markov_model(users, C.v * slot2, C.max_range, )
users = users_loc
if i%C.r_change_slot==0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
if i % slot1 != 0:
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f,e,rate,gdop=OF.real_objective(pre_uavs, uavs, users, r_p, p_all, b_all, c_association, p_association,slot2)
print(f,rate,gdop)
print("悬停时隙能耗:", e)
fitness.append(f)
else:#资源重分配,无人机重部署
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
pso.re_init(pre_uavs,users,r_c,r_p,c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
f,e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users, r_p, p_all, b_all, c_association, p_association,slot2)
print("飞行时隙能耗:",e)
pre_uavs=global_pos
uavs=global_pos
fitness.append(f)
# fitness.append(global_best[0])
print(fitness)
def whole_process_new(U,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
users=U[0]
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
fitness=[]
df_c=dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c,r_p, p_all, b_all, c_association, p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
fitness.append(f)
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
e=0
j=1
r_s=[]
g_s=[]
r_s.append(r)
g_s.append(g)
for i in range(10,3*C.r_change_slot,slot2):
users= U[j]
j+=1
if i%C.r_change_slot==0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
if i % slot1 != 0:
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
# c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
f,e,rate,gdop=OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association, p_association,slot2)
r,g=OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
print(f,rate,gdop)
print("满足率",r,g)
print("悬停时隙能耗:", e)
fitness.append(f)
else:#资源重分配,无人机重部署
# c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
pso.re_init(pre_uavs,users,r_c,r_p,c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
print("pso:",global_best)
c_association, p_association, p_all, b_all = OF.objective_resource(global_pos, users, r_c)
r, g = OF.cal_satisfaction(global_pos, users, p_all, b_all, r_c, r_p, c_association, p_association)
print("满足率", r, g)
r_s.append(r)
g_s.append(g)
f,e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users, r_c,r_p, p_all, b_all, c_association, p_association,slot2)
if f>global_best[0]:
fitness.append(f)
else:
fitness.append(global_best[0])
print("实际:",f)
print("飞行时隙能耗:",e)
pre_uavs=global_pos
uavs=global_pos
# fitness.append(f)
# fitness.append(global_best[0])
print("proposed:",fitness)
print(r_s)
print(g_s)
return fitness
def whole_process_kmeans(U,k,slot1,slot2):
users = U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
fitness = []
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association, p_association,
slot2)
fitness.append(f)
j = 1
for i in range(0, 3 * C.r_change_slot, slot2):
users = U[j]
j += 1
if i % C.r_change_slot == 0 and i != 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
if i % slot1 != 0:
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
# c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
print(f, rate, gdop)
print("悬停时隙能耗:", e)
fitness.append(f)
else: # 资源重分配,无人机重部署
uavs = tool.getUavInitialPos(k, users)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
fitness.append(f)
print("实际:", f)
print("飞行时隙能耗:", e)
pre_uavs = uavs
print(fitness)
def fixed_position_fixed_resource(U,k,slot1,slot2):
users = U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
fitness = []
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association, p_association,
slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
fitness.append(f)
j = 1
r_s = []
g_s = []
r_s.append(r)
g_s.append(g)
for i in range(0, 3 * C.r_change_slot, slot2):
users = U[j]
j += 1
if i % C.r_change_slot == 0 and i != 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
fitness.append(f)
print(fitness)
return fitness
def whole_process_pso(users,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
fitness=[]
df_c=dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
pso = PSO(pre_uavs, users, r_c, r_p, k, )
e=0
for i in range(0,10*slot1,slot2):
users_loc = dynamic.gauss_markov_model(users, C.v * slot2, C.max_range, )
users = users_loc
if i%C.r_change_slot==0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
if i % slot1 != 0:
f,e,rate,gdop=OF.real_objective(pre_uavs, uavs, users, r_p, p_all, b_all, c_association, p_association,slot2)
print(f,rate,gdop)
print("悬停时隙能耗:", e)
fitness.append(f)
else:#资源重分配,无人机重部署
pso.re_init(pre_uavs,users,r_c,r_p,c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
f,e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users, r_p, p_all, b_all, c_association, p_association,slot2)
print("飞行时隙能耗:",e)
pre_uavs=global_pos
uavs=global_pos
fitness.append(f)
# fitness.append(global_best[0])
print(fitness)
def run_whole_process():
users= Users.getUsers("./data.csv")
slot1=30
slot2=10
U=dynamic.generate_users_pos(users,slot2,30)
# whole_process(users,4,slot1,slot2)
fitness=[]
f_sum = []
k=5
for j in range(k):
for i in range(10,70,10):
f=whole_process_new(U, 4, i, slot2)
fitness.append(f)
f_sum.append(fitness)
print(fitness)
print(f_sum)
# whole_process_kmeans(U,4,i,slot2)
# f1_sum=[0 for i in range(19)]
# f2_sum = [0 for i in range(19)]
# f3_sum = [0 for i in range(19)]
# f4_sum = [0 for i in range(19)]
# k=3
# for i in range(k):
# f1=whole_process_new(U, 4, slot1, slot2)
# f2=fixed_position_dynamic_resource2(U, 4, slot1, slot2)
# f3=fixed_resource_dynamic_position2(U,4,slot1,slot2)
# f4=same_dynamic_resource_dynamic_position2(U,4,slot1,slot2)
# f1_sum=[f1_sum[j]+f1[j] for j in range(len(f1))]
# f2_sum = [f2_sum[j] + f2[j] for j in range(len(f1))]
# f3_sum = [f3_sum[j] + f3[j] for j in range(len(f1))]
# f4_sum = [f4_sum[j] + f4[j] for j in range(len(f1))]
# f1_avg=[f1_sum[i]/k for i in range(len(f1_sum))]
# f2_avg = [f2_sum[i] / k for i in range(len(f1_sum))]
# f3_avg = [f3_sum[i] / k for i in range(len(f1_sum))]
# f4_avg = [f4_sum[i] / k for i in range(len(f1_sum))]
# print(f1_avg)
# print(f2_avg)
# print(f3_avg)
# print(f4_avg)
# fixed_position_fixed_resource(U, 4, slot1, slot2)
#只优化资源
def fixed_position_dynamic_resource(users,k,slot1,slot2):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c,df_p,index)
fitness = []
for i in range(0, 10 * slot1, slot2):
users_loc = dynamic.gauss_markov_model(users, C.v * slot2, C.max_range, )
users = users_loc
if i % C.r_change_slot == 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f,e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_p, p_all, b_all, c_association, p_association,slot2)
print(f, e,rate, gdop)
fitness.append(f)
print(fitness)
def fixed_position_dynamic_resource2(U,k,slot1,slot2):
users=U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c,df_p,index)
fitness = []
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association, p_association, slot2)
print(f, e, rate, gdop)
fitness.append(f)
j=1
r_s,g_s=[],[]
for i in range(0, 3 * C.r_change_slot, slot2):
users = U[j]
j=j+1
if i % C.r_change_slot == 0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f,e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association, p_association,slot2)
print(f, e,rate, gdop)
fitness.append(f)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
print("fixed_position_dynamic_resource:",fitness)
print("fixed_position_dynamic_resource:", r_s,g_s)
return fitness
#只优化位置
def fixed_resource_dynamic_position(users,k,slot1,slot2):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
fitness = []
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
for i in range(0, 10 * slot1, slot2):
users_loc = dynamic.gauss_markov_model(users, C.v * slot2, C.max_range, )
users = users_loc
if i % C.r_change_slot == 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
# if index==1:
# c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
if i % slot1 == 0:
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
f, e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
print(f, e, rate, gdop)
fitness.append(f)
pre_uavs = global_pos
uavs = global_pos
else:
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
print(f, e, rate, gdop)
fitness.append(f)
print(fitness)
return fitness
def fixed_resource_dynamic_position2(U,k,slot1,slot2):
users=U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
fitness = []
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
print(f, e, rate, gdop)
fitness.append(f)
j=1
r_s,g_s=[],[]
for i in range(0, 3 * C.r_change_slot, slot2):
users = U[j]
j=j+1
if i % C.r_change_slot == 0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
# if index==1:
# c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
if i % slot1 == 0:
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
f, e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(global_pos, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
print(f, e, rate, gdop)
fitness.append(f)
pre_uavs = global_pos
uavs = global_pos
else:
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
print(f, e, rate, gdop)
fitness.append(f)
print("fixed_resource_dynamic_position",fitness)
print("fixed_resource_dynamic_position:", r_s, g_s)
return fitness
#同时优化资源和位置
def same_dynamic_resource_dynamic_position(users,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
fitness = []
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
e = 0
for i in range(0, 10 * slot1, slot2):
users_loc = dynamic.gauss_markov_model(users, C.v * slot2, C.max_range, )
users = users_loc
if i % C.r_change_slot == 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
if i % slot1 == 0:
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
f, e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
print("当前时隙能耗:", e)
pre_uavs = global_pos
uavs = global_pos
fitness.append(f)
else: #计算
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
print(f, e, rate, gdop)
fitness.append(f)
# fitness.append(global_best[0])
print(fitness)
return fitness
def same_dynamic_resource_dynamic_position2(U,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
users=U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
fitness = []
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
fitness.append(f)
e = 0
j=1
r_s,g_s=[],[]
for i in range(0, 3 * C.r_change_slot, slot2):
users = U[j]
j=j+1
if i % C.r_change_slot == 0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
if i % slot2 == 0:
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective,)
f, e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(global_pos, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
print("当前时隙能耗:", e)
pre_uavs = global_pos
uavs = global_pos
fitness.append(f)
else: #计算
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
print(f, e, rate, gdop)
fitness.append(f)
# fitness.append(global_best[0])
print("统一尺度:",fitness)
print("统一尺度:",r_s,g_s)
return fitness
# run_whole_process()
def cal_avg():
result=[[[1328.1765246507357, 1503.4819127657738, 1413.0043866027665, 1463.0694754945252, 1411.3332686120364,
1430.8494924488095, 1348.4585284268035, 1425.5665531789396, 1434.6103288936818, 1382.0470220409627,
1400.9531567236882, 1430.8877968272081, 1388.6185194154302, 1349.9589680879892, 1331.6482975811632,
1349.4196364208437, 1333.4082035862293, 1289.1716043437505],
[1328.1765246507357, 1353.1879576378208, 1405.8565440529696, 1432.7524257593964, 1401.1414708835648,
1413.2404297641222, 1383.0244353104806, 1424.8984233930191, 1431.198682113639, 1377.8356032938168,
1396.959114367267, 1431.17968510067, 1386.0419445035495, 1356.377703925818, 1332.1232554431833,
1352.6415842615386, 1334.979935409752, 1287.8872570069313],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1461.5691341367276, 1411.0399445665012,
1428.6282956069683, 1342.4394201899177, 1410.6593127134165, 1421.27785518321, 1379.0053611335575,
1400.2550306243324, 1433.9203792901133, 1356.75918484904, 1345.2969702372804, 1335.91205104966,
1353.492373837457, 1338.6041420862807, 1291.1214993205556],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1397.2181548623369,
1416.1632823180864, 1381.329183610079, 1423.0177897257574, 1381.024457636659, 1314.0230128358758,
1329.5899423905234, 1388.9476610421257, 1338.3554621772444, 1327.6922803222226, 1313.4015072363025,
1355.1396654592534, 1334.929881133014, 1288.7404759786446],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1239.6349292315638, 1256.4686678242904, 1277.2435737396827, 1267.0466827108758, 1178.9368661962508,
1368.468264013462, 1423.5411331544783, 1242.4019341077947, 1226.9254448575948, 1186.9326588398535,
1344.001558702772, 1337.9391635327902, 1297.4028580414574],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.2120232884542, 1431.8449807730888, 1431.3580503007593, 1378.1452369441306,
1396.4141506156877, 1433.377670872926, 1384.1169572273377, 1359.900905300984, 1330.6370094444353,
1353.823654014219, 1336.9776868893764, 1288.787931542987],
[1328.1765246507357, 1462.1032302319172, 1220.7983757506436, 1250.8351027133883, 1407.6119127563513,
1428.0915257023041, 1326.2581462780947, 1429.3390687732622, 1430.3834005472518, 1350.323846827929,
1384.6852854906783, 1388.5883879436703, 1384.9288942132264, 1363.9051313106954, 1333.3026983930981,
1356.3990159011914, 1336.8379103270627, 1253.635910753905],
[1328.1765246507357, 1353.1879576378208, 1391.94935171302, 1419.4723595055307, 1436.012266121132,
1448.4136632819252, 1346.110107123306, 1411.6812049560685, 1441.2949816305224, 1380.5627492161482,
1312.6260756214342, 1359.85895865934, 1380.3851780875336, 1356.023191076924, 1330.8989844393104,
1351.9296714736968, 1356.4851064483519, 1337.4758375470306],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1460.7498660143006, 1410.0728187816906,
1427.4464699502457, 1338.1539823621792, 1373.4882526392807, 1377.483347538101, 1373.6246453797514,
1387.3376104301349, 1441.5264866455693, 1348.6983324094676, 1338.5720560333045, 1324.1236454249363,
1354.1914050001853, 1338.8665448937927, 1291.2684553450981],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1290.7792571204702,
1214.308347749437, 1200.58340380531, 1239.501463648965, 1428.4077716261145, 1377.987085647185,
1398.1278396468706, 1428.7798719957766, 1385.7469740316235, 1356.5052284818378, 1330.6706853931034,
1353.4385628020025, 1335.2583787011524, 1288.6298545399088],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1442.8167958144866, 1406.2259749595107, 1428.1080839534975, 1426.0580976301176, 1381.5838277366659,
1397.6065029785466, 1430.6366358870098, 1387.3287325595181, 1359.7125256576942, 1333.3789756932902,
1355.1829245789684, 1339.515619602179, 1291.7515379563479],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1381132403171, 1432.010926615392, 1431.3321798901468, 1378.0565228773867,
1396.81940623514, 1432.7982708122322, 1377.8612793152831, 1350.6348893911354, 1327.8024309518744,
1345.099570863568, 1328.029161164731, 1280.9350822776496],
[1328.1765246507357, 1504.1073057068995, 1219.5661435925442, 1460.274343713098, 1436.3592446035104,
1425.1034928610165, 1339.2784050231967, 1443.2730535440444, 1425.0924476853634, 1363.5785187957338,
1341.4800219444169, 1423.9137275869386, 1349.7704669791651, 1360.7630386223702, 1333.425113996663,
1366.2030511798673, 1337.4231380704002, 1291.6640507163672],
[1328.1765246507357, 1353.1879576378208, 1410.579915824099, 1462.9235155522852, 1394.8132884136066,
1414.5613788698495, 1392.1522068490503, 1431.5057538173428, 1440.2238046243085, 1387.293910964124,
1399.5857248683053, 1435.6166727422476, 1388.969821621961, 1364.2475752956364, 1332.0464144720595,
1354.9038046415044, 1339.1743300404082, 1291.630256209334],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.4159965010651, 1411.3548799046819,
1425.7224684005503, 1391.377051941948, 1431.8159723489114, 1431.278025139241, 1358.8212920663784,
1380.2436201750243, 1425.1958017919642, 1384.3256466756068, 1359.07917364794, 1332.9247098888873,
1353.1637744754123, 1336.07627725299, 1290.0476381211815],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1393.4337378530465,
1409.835132447911, 1391.1722552886845, 1417.0328256395617, 1432.3487735073522, 1378.2772749194908,
1396.6008401570577, 1433.1155975041377, 1390.5914406805628, 1362.6765110445174, 1334.5762051476459,
1361.4369514102002, 1336.6893145856227, 1288.9669265353398],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1424.8510324458748, 1390.7715313987126, 1431.7204129721713, 1431.9081214684788, 1378.1928653857747,
1396.5681148308058, 1430.780621400254, 1384.5714015170224, 1359.6447860912401, 1330.3893264075632,
1353.4188754217143, 1336.859504893905, 1288.08174852749],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.375915240571, 1420.9624704974776, 1421.2395781820762, 1367.800240844252,
1399.9786499043562, 1424.3801787948573, 1387.408334861284, 1360.107103934737, 1330.7643039541172,
1355.5080991940283, 1337.1438609436389, 1290.3414189906262],
[1328.1765246507357, 1503.913864640719, 1413.8980639539386, 1468.00534814896, 1422.8104408104573,
1423.765114927117, 1324.9175310660078, 1435.7069206999379, 1433.6130926608998, 1381.3226169858867,
1356.3795348447263, 1431.3801618130071, 1386.6510817433498, 1361.9492867624042, 1332.7701837350623,
1350.1107156688993, 1333.0696822151624, 1329.2298025753437],
[1328.1765246507357, 1353.1879576378208, 1409.2744122762876, 1454.3125460261099, 1410.4565982165238,
1424.082433572339, 1391.4733702241447, 1430.879428730335, 1414.3890111884998, 1350.34520050958,
1394.841280189504, 1429.3744950534692, 1386.4838423235042, 1356.8345977131296, 1332.5345285357314,
1354.656448130794, 1336.017705107397, 1290.1994987112023],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1286.0162095769574, 1223.6306854721179,
1277.8869653640977, 1354.6916735211269, 1421.0978338505058, 1419.4423878951538, 1357.758685952835,
1387.6171511136472, 1429.1792659040157, 1327.5638800212087, 1323.1431279704393, 1316.45311752381,
1340.1900930468087, 1333.8143956170393, 1302.8716294862143],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1369.9885881316322,
1389.746107250975, 1370.1832958235645, 1402.7731717332395, 1430.2269756772712, 1376.3970040533245,
1396.0147842886943, 1431.3398512920298, 1376.3795115633775, 1354.4061186176452, 1322.125898247653,
1347.3190083197246, 1357.8289704460617, 1309.05475863672],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1425.0648190120878, 1390.8167346028026, 1432.1377945654822, 1431.7215282770155, 1377.5399714568885,
1380.911844832686, 1424.423408758382, 1296.815612973573, 1283.9798136146878, 1256.8194756407995,
1355.3359054061746, 1338.4699601111859, 1293.041446825808],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1670414052744, 1432.0300312924162, 1431.3542356778341, 1378.091812602148,
1396.8353951681145, 1432.8116506446752, 1385.8096029856881, 1357.7211709158132, 1330.4374574117403,
1353.7555347511545, 1337.7274048862123, 1288.7985560635561],
[1328.1765246507357, 1355.524217113136, 1412.9393304787225, 1465.2536583945196, 1410.697993614098,
1409.4334667878807, 1392.1943945343658, 1432.1373353197077, 1428.3902744802278, 1376.9823301026836,
1376.0674161952127, 1416.117550231582, 1383.412506204135, 1255.0784335917822, 1331.1853834984765,
1354.5528533816318, 1335.8822725180155, 1334.9239189752302],
[1328.1765246507357, 1353.1879576378208, 1410.814724976499, 1463.2075296132891, 1359.6374526982909,
1379.8017091774498, 1339.6702397963766, 1414.80823357494, 1417.2239029395234, 1361.4605045875321,
1396.318343095436, 1431.4467641883664, 1383.7222680136367, 1357.68401316966, 1330.5022749791037,
1354.0002885613083, 1335.781720673481, 1289.1835604091564],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.0227275098182, 1409.1231290530502,
1424.7112929163986, 1353.9694749430198, 1425.9473138683177, 1431.1149171600007, 1379.894377567314,
1399.26941534447, 1435.5745950310902, 1279.2743553908692, 1265.4957438307756, 1251.3268288661366,
1361.1714386001656, 1360.3714394835474, 1337.4519399978253],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1269.3936064664942,
1311.6416869961968, 1273.6585777553612, 1313.941461891031, 1432.7823407239148, 1380.7522541180585,
1399.1895890144515, 1431.7253108836628, 1384.9934068374707, 1359.608569164655, 1332.9293029520368,
1353.6079657716728, 1299.1185666067004, 1268.3723761743663],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1423.4143076476337, 1390.586686099597, 1430.8731140025316, 1431.3352484839065, 1377.530665193921,
1396.4032147703758, 1430.013055959338, 1385.216220842132, 1357.4682050836072, 1330.022274655173,
1353.691056324455, 1337.2310920781447, 1289.1970135479476],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1369.5460147787514, 1443.1311137429147, 1440.8509908426902, 1382.9197914159233,
1381.0026954392465, 1444.6890646393772, 1353.2513864631362, 1341.0551593686894, 1305.9609304041398,
1331.0007656836608, 1328.9668585129314, 1289.3981557047607]], [
[1328.1765246507357, 1503.4819127657738, 1413.0043866027665, 1463.0694754945252, 1411.3332686120364,
1430.8494924488095, 1348.4585284268035, 1425.5665531789396, 1434.6103288936818, 1382.0470220409627,
1400.9531567236882, 1430.8877968272081, 1388.6185194154302, 1349.9589680879892, 1331.6482975811632,
1349.4196364208437, 1333.4082035862293, 1289.1716043437505],
[1328.1765246507357, 1353.1879576378208, 1405.8565440529696, 1432.7524257593964, 1401.1414708835648,
1413.2404297641222, 1383.0244353104806, 1424.8984233930191, 1431.198682113639, 1377.8356032938168,
1396.959114367267, 1431.17968510067, 1386.0419445035495, 1356.377703925818, 1332.1232554431833,
1352.6415842615386, 1334.979935409752, 1287.8872570069313],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1461.5691341367276, 1411.0399445665012,
1428.6282956069683, 1342.4394201899177, 1410.6593127134165, 1421.27785518321, 1379.0053611335575,
1400.2550306243324, 1433.9203792901133, 1356.75918484904, 1345.2969702372804, 1335.91205104966,
1353.492373837457, 1338.6041420862807, 1291.1214993205556],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1397.2181548623369,
1416.1632823180864, 1381.329183610079, 1423.0177897257574, 1381.024457636659, 1314.0230128358758,
1329.5899423905234, 1388.9476610421257, 1338.3554621772444, 1327.6922803222226, 1313.4015072363025,
1355.1396654592534, 1334.929881133014, 1288.7404759786446],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1239.6349292315638, 1256.4686678242904, 1277.2435737396827, 1267.0466827108758, 1178.9368661962508,
1368.468264013462, 1423.5411331544783, 1242.4019341077947, 1226.9254448575948, 1186.9326588398535,
1344.001558702772, 1337.9391635327902, 1297.4028580414574],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.2120232884542, 1431.8449807730888, 1431.3580503007593, 1378.1452369441306,
1396.4141506156877, 1433.377670872926, 1384.1169572273377, 1359.900905300984, 1330.6370094444353,
1353.823654014219, 1336.9776868893764, 1288.787931542987],
[1328.1765246507357, 1462.1032302319172, 1220.7983757506436, 1250.8351027133883, 1407.6119127563513,
1428.0915257023041, 1326.2581462780947, 1429.3390687732622, 1430.3834005472518, 1350.323846827929,
1384.6852854906783, 1388.5883879436703, 1384.9288942132264, 1363.9051313106954, 1333.3026983930981,
1356.3990159011914, 1336.8379103270627, 1253.635910753905],
[1328.1765246507357, 1353.1879576378208, 1391.94935171302, 1419.4723595055307, 1436.012266121132,
1448.4136632819252, 1346.110107123306, 1411.6812049560685, 1441.2949816305224, 1380.5627492161482,
1312.6260756214342, 1359.85895865934, 1380.3851780875336, 1356.023191076924, 1330.8989844393104,
1351.9296714736968, 1356.4851064483519, 1337.4758375470306],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1460.7498660143006, 1410.0728187816906,
1427.4464699502457, 1338.1539823621792, 1373.4882526392807, 1377.483347538101, 1373.6246453797514,
1387.3376104301349, 1441.5264866455693, 1348.6983324094676, 1338.5720560333045, 1324.1236454249363,
1354.1914050001853, 1338.8665448937927, 1291.2684553450981],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1290.7792571204702,
1214.308347749437, 1200.58340380531, 1239.501463648965, 1428.4077716261145, 1377.987085647185,
1398.1278396468706, 1428.7798719957766, 1385.7469740316235, 1356.5052284818378, 1330.6706853931034,
1353.4385628020025, 1335.2583787011524, 1288.6298545399088],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1442.8167958144866, 1406.2259749595107, 1428.1080839534975, 1426.0580976301176, 1381.5838277366659,
1397.6065029785466, 1430.6366358870098, 1387.3287325595181, 1359.7125256576942, 1333.3789756932902,
1355.1829245789684, 1339.515619602179, 1291.7515379563479],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1381132403171, 1432.010926615392, 1431.3321798901468, 1378.0565228773867,
1396.81940623514, 1432.7982708122322, 1377.8612793152831, 1350.6348893911354, 1327.8024309518744,
1345.099570863568, 1328.029161164731, 1280.9350822776496],
[1328.1765246507357, 1504.1073057068995, 1219.5661435925442, 1460.274343713098, 1436.3592446035104,
1425.1034928610165, 1339.2784050231967, 1443.2730535440444, 1425.0924476853634, 1363.5785187957338,
1341.4800219444169, 1423.9137275869386, 1349.7704669791651, 1360.7630386223702, 1333.425113996663,
1366.2030511798673, 1337.4231380704002, 1291.6640507163672],
[1328.1765246507357, 1353.1879576378208, 1410.579915824099, 1462.9235155522852, 1394.8132884136066,
1414.5613788698495, 1392.1522068490503, 1431.5057538173428, 1440.2238046243085, 1387.293910964124,
1399.5857248683053, 1435.6166727422476, 1388.969821621961, 1364.2475752956364, 1332.0464144720595,
1354.9038046415044, 1339.1743300404082, 1291.630256209334],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.4159965010651, 1411.3548799046819,
1425.7224684005503, 1391.377051941948, 1431.8159723489114, 1431.278025139241, 1358.8212920663784,
1380.2436201750243, 1425.1958017919642, 1384.3256466756068, 1359.07917364794, 1332.9247098888873,
1353.1637744754123, 1336.07627725299, 1290.0476381211815],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1393.4337378530465,
1409.835132447911, 1391.1722552886845, 1417.0328256395617, 1432.3487735073522, 1378.2772749194908,
1396.6008401570577, 1433.1155975041377, 1390.5914406805628, 1362.6765110445174, 1334.5762051476459,
1361.4369514102002, 1336.6893145856227, 1288.9669265353398],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1424.8510324458748, 1390.7715313987126, 1431.7204129721713, 1431.9081214684788, 1378.1928653857747,
1396.5681148308058, 1430.780621400254, 1384.5714015170224, 1359.6447860912401, 1330.3893264075632,
1353.4188754217143, 1336.859504893905, 1288.08174852749],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.375915240571, 1420.9624704974776, 1421.2395781820762, 1367.800240844252,
1399.9786499043562, 1424.3801787948573, 1387.408334861284, 1360.107103934737, 1330.7643039541172,
1355.5080991940283, 1337.1438609436389, 1290.3414189906262],
[1328.1765246507357, 1503.913864640719, 1413.8980639539386, 1468.00534814896, 1422.8104408104573,
1423.765114927117, 1324.9175310660078, 1435.7069206999379, 1433.6130926608998, 1381.3226169858867,
1356.3795348447263, 1431.3801618130071, 1386.6510817433498, 1361.9492867624042, 1332.7701837350623,
1350.1107156688993, 1333.0696822151624, 1329.2298025753437],
[1328.1765246507357, 1353.1879576378208, 1409.2744122762876, 1454.3125460261099, 1410.4565982165238,
1424.082433572339, 1391.4733702241447, 1430.879428730335, 1414.3890111884998, 1350.34520050958,
1394.841280189504, 1429.3744950534692, 1386.4838423235042, 1356.8345977131296, 1332.5345285357314,
1354.656448130794, 1336.017705107397, 1290.1994987112023],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1286.0162095769574, 1223.6306854721179,
1277.8869653640977, 1354.6916735211269, 1421.0978338505058, 1419.4423878951538, 1357.758685952835,
1387.6171511136472, 1429.1792659040157, 1327.5638800212087, 1323.1431279704393, 1316.45311752381,
1340.1900930468087, 1333.8143956170393, 1302.8716294862143],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1369.9885881316322,
1389.746107250975, 1370.1832958235645, 1402.7731717332395, 1430.2269756772712, 1376.3970040533245,
1396.0147842886943, 1431.3398512920298, 1376.3795115633775, 1354.4061186176452, 1322.125898247653,
1347.3190083197246, 1357.8289704460617, 1309.05475863672],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1425.0648190120878, 1390.8167346028026, 1432.1377945654822, 1431.7215282770155, 1377.5399714568885,
1380.911844832686, 1424.423408758382, 1296.815612973573, 1283.9798136146878, 1256.8194756407995,
1355.3359054061746, 1338.4699601111859, 1293.041446825808],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1670414052744, 1432.0300312924162, 1431.3542356778341, 1378.091812602148,
1396.8353951681145, 1432.8116506446752, 1385.8096029856881, 1357.7211709158132, 1330.4374574117403,
1353.7555347511545, 1337.7274048862123, 1288.7985560635561],
[1328.1765246507357, 1355.524217113136, 1412.9393304787225, 1465.2536583945196, 1410.697993614098,
1409.4334667878807, 1392.1943945343658, 1432.1373353197077, 1428.3902744802278, 1376.9823301026836,
1376.0674161952127, 1416.117550231582, 1383.412506204135, 1255.0784335917822, 1331.1853834984765,
1354.5528533816318, 1335.8822725180155, 1334.9239189752302],
[1328.1765246507357, 1353.1879576378208, 1410.814724976499, 1463.2075296132891, 1359.6374526982909,
1379.8017091774498, 1339.6702397963766, 1414.80823357494, 1417.2239029395234, 1361.4605045875321,
1396.318343095436, 1431.4467641883664, 1383.7222680136367, 1357.68401316966, 1330.5022749791037,
1354.0002885613083, 1335.781720673481, 1289.1835604091564],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.0227275098182, 1409.1231290530502,
1424.7112929163986, 1353.9694749430198, 1425.9473138683177, 1431.1149171600007, 1379.894377567314,
1399.26941534447, 1435.5745950310902, 1279.2743553908692, 1265.4957438307756, 1251.3268288661366,
1361.1714386001656, 1360.3714394835474, 1337.4519399978253],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1269.3936064664942,
1311.6416869961968, 1273.6585777553612, 1313.941461891031, 1432.7823407239148, 1380.7522541180585,
1399.1895890144515, 1431.7253108836628, 1384.9934068374707, 1359.608569164655, 1332.9293029520368,
1353.6079657716728, 1299.1185666067004, 1268.3723761743663],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1423.4143076476337, 1390.586686099597, 1430.8731140025316, 1431.3352484839065, 1377.530665193921,
1396.4032147703758, 1430.013055959338, 1385.216220842132, 1357.4682050836072, 1330.022274655173,
1353.691056324455, 1337.2310920781447, 1289.1970135479476],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1369.5460147787514, 1443.1311137429147, 1440.8509908426902, 1382.9197914159233,
1381.0026954392465, 1444.6890646393772, 1353.2513864631362, 1341.0551593686894, 1305.9609304041398,
1331.0007656836608, 1328.9668585129314, 1289.3981557047607]], [
[1328.1765246507357, 1503.4819127657738, 1413.0043866027665, 1463.0694754945252, 1411.3332686120364,
1430.8494924488095, 1348.4585284268035, 1425.5665531789396, 1434.6103288936818, 1382.0470220409627,
1400.9531567236882, 1430.8877968272081, 1388.6185194154302, 1349.9589680879892, 1331.6482975811632,
1349.4196364208437, 1333.4082035862293, 1289.1716043437505],
[1328.1765246507357, 1353.1879576378208, 1405.8565440529696, 1432.7524257593964, 1401.1414708835648,
1413.2404297641222, 1383.0244353104806, 1424.8984233930191, 1431.198682113639, 1377.8356032938168,
1396.959114367267, 1431.17968510067, 1386.0419445035495, 1356.377703925818, 1332.1232554431833,
1352.6415842615386, 1334.979935409752, 1287.8872570069313],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1461.5691341367276, 1411.0399445665012,
1428.6282956069683, 1342.4394201899177, 1410.6593127134165, 1421.27785518321, 1379.0053611335575,
1400.2550306243324, 1433.9203792901133, 1356.75918484904, 1345.2969702372804, 1335.91205104966,
1353.492373837457, 1338.6041420862807, 1291.1214993205556],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1397.2181548623369,
1416.1632823180864, 1381.329183610079, 1423.0177897257574, 1381.024457636659, 1314.0230128358758,
1329.5899423905234, 1388.9476610421257, 1338.3554621772444, 1327.6922803222226, 1313.4015072363025,
1355.1396654592534, 1334.929881133014, 1288.7404759786446],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1239.6349292315638, 1256.4686678242904, 1277.2435737396827, 1267.0466827108758, 1178.9368661962508,
1368.468264013462, 1423.5411331544783, 1242.4019341077947, 1226.9254448575948, 1186.9326588398535,
1344.001558702772, 1337.9391635327902, 1297.4028580414574],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.2120232884542, 1431.8449807730888, 1431.3580503007593, 1378.1452369441306,
1396.4141506156877, 1433.377670872926, 1384.1169572273377, 1359.900905300984, 1330.6370094444353,
1353.823654014219, 1336.9776868893764, 1288.787931542987],
[1328.1765246507357, 1462.1032302319172, 1220.7983757506436, 1250.8351027133883, 1407.6119127563513,
1428.0915257023041, 1326.2581462780947, 1429.3390687732622, 1430.3834005472518, 1350.323846827929,
1384.6852854906783, 1388.5883879436703, 1384.9288942132264, 1363.9051313106954, 1333.3026983930981,
1356.3990159011914, 1336.8379103270627, 1253.635910753905],
[1328.1765246507357, 1353.1879576378208, 1391.94935171302, 1419.4723595055307, 1436.012266121132,
1448.4136632819252, 1346.110107123306, 1411.6812049560685, 1441.2949816305224, 1380.5627492161482,
1312.6260756214342, 1359.85895865934, 1380.3851780875336, 1356.023191076924, 1330.8989844393104,
1351.9296714736968, 1356.4851064483519, 1337.4758375470306],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1460.7498660143006, 1410.0728187816906,
1427.4464699502457, 1338.1539823621792, 1373.4882526392807, 1377.483347538101, 1373.6246453797514,
1387.3376104301349, 1441.5264866455693, 1348.6983324094676, 1338.5720560333045, 1324.1236454249363,
1354.1914050001853, 1338.8665448937927, 1291.2684553450981],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1290.7792571204702,
1214.308347749437, 1200.58340380531, 1239.501463648965, 1428.4077716261145, 1377.987085647185,
1398.1278396468706, 1428.7798719957766, 1385.7469740316235, 1356.5052284818378, 1330.6706853931034,
1353.4385628020025, 1335.2583787011524, 1288.6298545399088],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1442.8167958144866, 1406.2259749595107, 1428.1080839534975, 1426.0580976301176, 1381.5838277366659,
1397.6065029785466, 1430.6366358870098, 1387.3287325595181, 1359.7125256576942, 1333.3789756932902,
1355.1829245789684, 1339.515619602179, 1291.7515379563479],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1381132403171, 1432.010926615392, 1431.3321798901468, 1378.0565228773867,
1396.81940623514, 1432.7982708122322, 1377.8612793152831, 1350.6348893911354, 1327.8024309518744,
1345.099570863568, 1328.029161164731, 1280.9350822776496],
[1328.1765246507357, 1504.1073057068995, 1219.5661435925442, 1460.274343713098, 1436.3592446035104,
1425.1034928610165, 1339.2784050231967, 1443.2730535440444, 1425.0924476853634, 1363.5785187957338,
1341.4800219444169, 1423.9137275869386, 1349.7704669791651, 1360.7630386223702, 1333.425113996663,
1366.2030511798673, 1337.4231380704002, 1291.6640507163672],
[1328.1765246507357, 1353.1879576378208, 1410.579915824099, 1462.9235155522852, 1394.8132884136066,
1414.5613788698495, 1392.1522068490503, 1431.5057538173428, 1440.2238046243085, 1387.293910964124,
1399.5857248683053, 1435.6166727422476, 1388.969821621961, 1364.2475752956364, 1332.0464144720595,
1354.9038046415044, 1339.1743300404082, 1291.630256209334],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.4159965010651, 1411.3548799046819,
1425.7224684005503, 1391.377051941948, 1431.8159723489114, 1431.278025139241, 1358.8212920663784,
1380.2436201750243, 1425.1958017919642, 1384.3256466756068, 1359.07917364794, 1332.9247098888873,
1353.1637744754123, 1336.07627725299, 1290.0476381211815],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1393.4337378530465,
1409.835132447911, 1391.1722552886845, 1417.0328256395617, 1432.3487735073522, 1378.2772749194908,
1396.6008401570577, 1433.1155975041377, 1390.5914406805628, 1362.6765110445174, 1334.5762051476459,
1361.4369514102002, 1336.6893145856227, 1288.9669265353398],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1424.8510324458748, 1390.7715313987126, 1431.7204129721713, 1431.9081214684788, 1378.1928653857747,
1396.5681148308058, 1430.780621400254, 1384.5714015170224, 1359.6447860912401, 1330.3893264075632,
1353.4188754217143, 1336.859504893905, 1288.08174852749],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.375915240571, 1420.9624704974776, 1421.2395781820762, 1367.800240844252,
1399.9786499043562, 1424.3801787948573, 1387.408334861284, 1360.107103934737, 1330.7643039541172,
1355.5080991940283, 1337.1438609436389, 1290.3414189906262],
[1328.1765246507357, 1503.913864640719, 1413.8980639539386, 1468.00534814896, 1422.8104408104573,
1423.765114927117, 1324.9175310660078, 1435.7069206999379, 1433.6130926608998, 1381.3226169858867,
1356.3795348447263, 1431.3801618130071, 1386.6510817433498, 1361.9492867624042, 1332.7701837350623,
1350.1107156688993, 1333.0696822151624, 1329.2298025753437],
[1328.1765246507357, 1353.1879576378208, 1409.2744122762876, 1454.3125460261099, 1410.4565982165238,
1424.082433572339, 1391.4733702241447, 1430.879428730335, 1414.3890111884998, 1350.34520050958,
1394.841280189504, 1429.3744950534692, 1386.4838423235042, 1356.8345977131296, 1332.5345285357314,
1354.656448130794, 1336.017705107397, 1290.1994987112023],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1286.0162095769574, 1223.6306854721179,
1277.8869653640977, 1354.6916735211269, 1421.0978338505058, 1419.4423878951538, 1357.758685952835,
1387.6171511136472, 1429.1792659040157, 1327.5638800212087, 1323.1431279704393, 1316.45311752381,
1340.1900930468087, 1333.8143956170393, 1302.8716294862143],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1369.9885881316322,
1389.746107250975, 1370.1832958235645, 1402.7731717332395, 1430.2269756772712, 1376.3970040533245,
1396.0147842886943, 1431.3398512920298, 1376.3795115633775, 1354.4061186176452, 1322.125898247653,
1347.3190083197246, 1357.8289704460617, 1309.05475863672],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1425.0648190120878, 1390.8167346028026, 1432.1377945654822, 1431.7215282770155, 1377.5399714568885,
1380.911844832686, 1424.423408758382, 1296.815612973573, 1283.9798136146878, 1256.8194756407995,
1355.3359054061746, 1338.4699601111859, 1293.041446825808],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1670414052744, 1432.0300312924162, 1431.3542356778341, 1378.091812602148,
1396.8353951681145, 1432.8116506446752, 1385.8096029856881, 1357.7211709158132, 1330.4374574117403,
1353.7555347511545, 1337.7274048862123, 1288.7985560635561],
[1328.1765246507357, 1355.524217113136, 1412.9393304787225, 1465.2536583945196, 1410.697993614098,
1409.4334667878807, 1392.1943945343658, 1432.1373353197077, 1428.3902744802278, 1376.9823301026836,
1376.0674161952127, 1416.117550231582, 1383.412506204135, 1255.0784335917822, 1331.1853834984765,
1354.5528533816318, 1335.8822725180155, 1334.9239189752302],
[1328.1765246507357, 1353.1879576378208, 1410.814724976499, 1463.2075296132891, 1359.6374526982909,
1379.8017091774498, 1339.6702397963766, 1414.80823357494, 1417.2239029395234, 1361.4605045875321,
1396.318343095436, 1431.4467641883664, 1383.7222680136367, 1357.68401316966, 1330.5022749791037,
1354.0002885613083, 1335.781720673481, 1289.1835604091564],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.0227275098182, 1409.1231290530502,
1424.7112929163986, 1353.9694749430198, 1425.9473138683177, 1431.1149171600007, 1379.894377567314,
1399.26941534447, 1435.5745950310902, 1279.2743553908692, 1265.4957438307756, 1251.3268288661366,
1361.1714386001656, 1360.3714394835474, 1337.4519399978253],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1269.3936064664942,
1311.6416869961968, 1273.6585777553612, 1313.941461891031, 1432.7823407239148, 1380.7522541180585,
1399.1895890144515, 1431.7253108836628, 1384.9934068374707, 1359.608569164655, 1332.9293029520368,
1353.6079657716728, 1299.1185666067004, 1268.3723761743663],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1423.4143076476337, 1390.586686099597, 1430.8731140025316, 1431.3352484839065, 1377.530665193921,
1396.4032147703758, 1430.013055959338, 1385.216220842132, 1357.4682050836072, 1330.022274655173,
1353.691056324455, 1337.2310920781447, 1289.1970135479476],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1369.5460147787514, 1443.1311137429147, 1440.8509908426902, 1382.9197914159233,
1381.0026954392465, 1444.6890646393772, 1353.2513864631362, 1341.0551593686894, 1305.9609304041398,
1331.0007656836608, 1328.9668585129314, 1289.3981557047607]], [
[1328.1765246507357, 1503.4819127657738, 1413.0043866027665, 1463.0694754945252, 1411.3332686120364,
1430.8494924488095, 1348.4585284268035, 1425.5665531789396, 1434.6103288936818, 1382.0470220409627,
1400.9531567236882, 1430.8877968272081, 1388.6185194154302, 1349.9589680879892, 1331.6482975811632,
1349.4196364208437, 1333.4082035862293, 1289.1716043437505],
[1328.1765246507357, 1353.1879576378208, 1405.8565440529696, 1432.7524257593964, 1401.1414708835648,
1413.2404297641222, 1383.0244353104806, 1424.8984233930191, 1431.198682113639, 1377.8356032938168,
1396.959114367267, 1431.17968510067, 1386.0419445035495, 1356.377703925818, 1332.1232554431833,
1352.6415842615386, 1334.979935409752, 1287.8872570069313],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1461.5691341367276, 1411.0399445665012,
1428.6282956069683, 1342.4394201899177, 1410.6593127134165, 1421.27785518321, 1379.0053611335575,
1400.2550306243324, 1433.9203792901133, 1356.75918484904, 1345.2969702372804, 1335.91205104966,
1353.492373837457, 1338.6041420862807, 1291.1214993205556],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1397.2181548623369,
1416.1632823180864, 1381.329183610079, 1423.0177897257574, 1381.024457636659, 1314.0230128358758,
1329.5899423905234, 1388.9476610421257, 1338.3554621772444, 1327.6922803222226, 1313.4015072363025,
1355.1396654592534, 1334.929881133014, 1288.7404759786446],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1239.6349292315638, 1256.4686678242904, 1277.2435737396827, 1267.0466827108758, 1178.9368661962508,
1368.468264013462, 1423.5411331544783, 1242.4019341077947, 1226.9254448575948, 1186.9326588398535,
1344.001558702772, 1337.9391635327902, 1297.4028580414574],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.2120232884542, 1431.8449807730888, 1431.3580503007593, 1378.1452369441306,
1396.4141506156877, 1433.377670872926, 1384.1169572273377, 1359.900905300984, 1330.6370094444353,
1353.823654014219, 1336.9776868893764, 1288.787931542987],
[1328.1765246507357, 1462.1032302319172, 1220.7983757506436, 1250.8351027133883, 1407.6119127563513,
1428.0915257023041, 1326.2581462780947, 1429.3390687732622, 1430.3834005472518, 1350.323846827929,
1384.6852854906783, 1388.5883879436703, 1384.9288942132264, 1363.9051313106954, 1333.3026983930981,
1356.3990159011914, 1336.8379103270627, 1253.635910753905],
[1328.1765246507357, 1353.1879576378208, 1391.94935171302, 1419.4723595055307, 1436.012266121132,
1448.4136632819252, 1346.110107123306, 1411.6812049560685, 1441.2949816305224, 1380.5627492161482,
1312.6260756214342, 1359.85895865934, 1380.3851780875336, 1356.023191076924, 1330.8989844393104,
1351.9296714736968, 1356.4851064483519, 1337.4758375470306],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1460.7498660143006, 1410.0728187816906,
1427.4464699502457, 1338.1539823621792, 1373.4882526392807, 1377.483347538101, 1373.6246453797514,
1387.3376104301349, 1441.5264866455693, 1348.6983324094676, 1338.5720560333045, 1324.1236454249363,
1354.1914050001853, 1338.8665448937927, 1291.2684553450981],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1290.7792571204702,
1214.308347749437, 1200.58340380531, 1239.501463648965, 1428.4077716261145, 1377.987085647185,
1398.1278396468706, 1428.7798719957766, 1385.7469740316235, 1356.5052284818378, 1330.6706853931034,
1353.4385628020025, 1335.2583787011524, 1288.6298545399088],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1442.8167958144866, 1406.2259749595107, 1428.1080839534975, 1426.0580976301176, 1381.5838277366659,
1397.6065029785466, 1430.6366358870098, 1387.3287325595181, 1359.7125256576942, 1333.3789756932902,
1355.1829245789684, 1339.515619602179, 1291.7515379563479],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1381132403171, 1432.010926615392, 1431.3321798901468, 1378.0565228773867,
1396.81940623514, 1432.7982708122322, 1377.8612793152831, 1350.6348893911354, 1327.8024309518744,
1345.099570863568, 1328.029161164731, 1280.9350822776496],
[1328.1765246507357, 1504.1073057068995, 1219.5661435925442, 1460.274343713098, 1436.3592446035104,
1425.1034928610165, 1339.2784050231967, 1443.2730535440444, 1425.0924476853634, 1363.5785187957338,
1341.4800219444169, 1423.9137275869386, 1349.7704669791651, 1360.7630386223702, 1333.425113996663,
1366.2030511798673, 1337.4231380704002, 1291.6640507163672],
[1328.1765246507357, 1353.1879576378208, 1410.579915824099, 1462.9235155522852, 1394.8132884136066,
1414.5613788698495, 1392.1522068490503, 1431.5057538173428, 1440.2238046243085, 1387.293910964124,
1399.5857248683053, 1435.6166727422476, 1388.969821621961, 1364.2475752956364, 1332.0464144720595,
1354.9038046415044, 1339.1743300404082, 1291.630256209334],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.4159965010651, 1411.3548799046819,
1425.7224684005503, 1391.377051941948, 1431.8159723489114, 1431.278025139241, 1358.8212920663784,
1380.2436201750243, 1425.1958017919642, 1384.3256466756068, 1359.07917364794, 1332.9247098888873,
1353.1637744754123, 1336.07627725299, 1290.0476381211815],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1393.4337378530465,
1409.835132447911, 1391.1722552886845, 1417.0328256395617, 1432.3487735073522, 1378.2772749194908,
1396.6008401570577, 1433.1155975041377, 1390.5914406805628, 1362.6765110445174, 1334.5762051476459,
1361.4369514102002, 1336.6893145856227, 1288.9669265353398],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1424.8510324458748, 1390.7715313987126, 1431.7204129721713, 1431.9081214684788, 1378.1928653857747,
1396.5681148308058, 1430.780621400254, 1384.5714015170224, 1359.6447860912401, 1330.3893264075632,
1353.4188754217143, 1336.859504893905, 1288.08174852749],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.375915240571, 1420.9624704974776, 1421.2395781820762, 1367.800240844252,
1399.9786499043562, 1424.3801787948573, 1387.408334861284, 1360.107103934737, 1330.7643039541172,
1355.5080991940283, 1337.1438609436389, 1290.3414189906262],
[1328.1765246507357, 1503.913864640719, 1413.8980639539386, 1468.00534814896, 1422.8104408104573,
1423.765114927117, 1324.9175310660078, 1435.7069206999379, 1433.6130926608998, 1381.3226169858867,
1356.3795348447263, 1431.3801618130071, 1386.6510817433498, 1361.9492867624042, 1332.7701837350623,
1350.1107156688993, 1333.0696822151624, 1329.2298025753437],
[1328.1765246507357, 1353.1879576378208, 1409.2744122762876, 1454.3125460261099, 1410.4565982165238,
1424.082433572339, 1391.4733702241447, 1430.879428730335, 1414.3890111884998, 1350.34520050958,
1394.841280189504, 1429.3744950534692, 1386.4838423235042, 1356.8345977131296, 1332.5345285357314,
1354.656448130794, 1336.017705107397, 1290.1994987112023],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1286.0162095769574, 1223.6306854721179,
1277.8869653640977, 1354.6916735211269, 1421.0978338505058, 1419.4423878951538, 1357.758685952835,
1387.6171511136472, 1429.1792659040157, 1327.5638800212087, 1323.1431279704393, 1316.45311752381,
1340.1900930468087, 1333.8143956170393, 1302.8716294862143],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1369.9885881316322,
1389.746107250975, 1370.1832958235645, 1402.7731717332395, 1430.2269756772712, 1376.3970040533245,
1396.0147842886943, 1431.3398512920298, 1376.3795115633775, 1354.4061186176452, 1322.125898247653,
1347.3190083197246, 1357.8289704460617, 1309.05475863672],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1425.0648190120878, 1390.8167346028026, 1432.1377945654822, 1431.7215282770155, 1377.5399714568885,
1380.911844832686, 1424.423408758382, 1296.815612973573, 1283.9798136146878, 1256.8194756407995,
1355.3359054061746, 1338.4699601111859, 1293.041446825808],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1670414052744, 1432.0300312924162, 1431.3542356778341, 1378.091812602148,
1396.8353951681145, 1432.8116506446752, 1385.8096029856881, 1357.7211709158132, 1330.4374574117403,
1353.7555347511545, 1337.7274048862123, 1288.7985560635561],
[1328.1765246507357, 1355.524217113136, 1412.9393304787225, 1465.2536583945196, 1410.697993614098,
1409.4334667878807, 1392.1943945343658, 1432.1373353197077, 1428.3902744802278, 1376.9823301026836,
1376.0674161952127, 1416.117550231582, 1383.412506204135, 1255.0784335917822, 1331.1853834984765,
1354.5528533816318, 1335.8822725180155, 1334.9239189752302],
[1328.1765246507357, 1353.1879576378208, 1410.814724976499, 1463.2075296132891, 1359.6374526982909,
1379.8017091774498, 1339.6702397963766, 1414.80823357494, 1417.2239029395234, 1361.4605045875321,
1396.318343095436, 1431.4467641883664, 1383.7222680136367, 1357.68401316966, 1330.5022749791037,
1354.0002885613083, 1335.781720673481, 1289.1835604091564],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.0227275098182, 1409.1231290530502,
1424.7112929163986, 1353.9694749430198, 1425.9473138683177, 1431.1149171600007, 1379.894377567314,
1399.26941534447, 1435.5745950310902, 1279.2743553908692, 1265.4957438307756, 1251.3268288661366,
1361.1714386001656, 1360.3714394835474, 1337.4519399978253],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1269.3936064664942,
1311.6416869961968, 1273.6585777553612, 1313.941461891031, 1432.7823407239148, 1380.7522541180585,
1399.1895890144515, 1431.7253108836628, 1384.9934068374707, 1359.608569164655, 1332.9293029520368,
1353.6079657716728, 1299.1185666067004, 1268.3723761743663],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1423.4143076476337, 1390.586686099597, 1430.8731140025316, 1431.3352484839065, 1377.530665193921,
1396.4032147703758, 1430.013055959338, 1385.216220842132, 1357.4682050836072, 1330.022274655173,
1353.691056324455, 1337.2310920781447, 1289.1970135479476],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1369.5460147787514, 1443.1311137429147, 1440.8509908426902, 1382.9197914159233,
1381.0026954392465, 1444.6890646393772, 1353.2513864631362, 1341.0551593686894, 1305.9609304041398,
1331.0007656836608, 1328.9668585129314, 1289.3981557047607]], [
[1328.1765246507357, 1503.4819127657738, 1413.0043866027665, 1463.0694754945252, 1411.3332686120364,
1430.8494924488095, 1348.4585284268035, 1425.5665531789396, 1434.6103288936818, 1382.0470220409627,
1400.9531567236882, 1430.8877968272081, 1388.6185194154302, 1349.9589680879892, 1331.6482975811632,
1349.4196364208437, 1333.4082035862293, 1289.1716043437505],
[1328.1765246507357, 1353.1879576378208, 1405.8565440529696, 1432.7524257593964, 1401.1414708835648,
1413.2404297641222, 1383.0244353104806, 1424.8984233930191, 1431.198682113639, 1377.8356032938168,
1396.959114367267, 1431.17968510067, 1386.0419445035495, 1356.377703925818, 1332.1232554431833,
1352.6415842615386, 1334.979935409752, 1287.8872570069313],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1461.5691341367276, 1411.0399445665012,
1428.6282956069683, 1342.4394201899177, 1410.6593127134165, 1421.27785518321, 1379.0053611335575,
1400.2550306243324, 1433.9203792901133, 1356.75918484904, 1345.2969702372804, 1335.91205104966,
1353.492373837457, 1338.6041420862807, 1291.1214993205556],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1397.2181548623369,
1416.1632823180864, 1381.329183610079, 1423.0177897257574, 1381.024457636659, 1314.0230128358758,
1329.5899423905234, 1388.9476610421257, 1338.3554621772444, 1327.6922803222226, 1313.4015072363025,
1355.1396654592534, 1334.929881133014, 1288.7404759786446],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1239.6349292315638, 1256.4686678242904, 1277.2435737396827, 1267.0466827108758, 1178.9368661962508,
1368.468264013462, 1423.5411331544783, 1242.4019341077947, 1226.9254448575948, 1186.9326588398535,
1344.001558702772, 1337.9391635327902, 1297.4028580414574],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.2120232884542, 1431.8449807730888, 1431.3580503007593, 1378.1452369441306,
1396.4141506156877, 1433.377670872926, 1384.1169572273377, 1359.900905300984, 1330.6370094444353,
1353.823654014219, 1336.9776868893764, 1288.787931542987],
[1328.1765246507357, 1462.1032302319172, 1220.7983757506436, 1250.8351027133883, 1407.6119127563513,
1428.0915257023041, 1326.2581462780947, 1429.3390687732622, 1430.3834005472518, 1350.323846827929,
1384.6852854906783, 1388.5883879436703, 1384.9288942132264, 1363.9051313106954, 1333.3026983930981,
1356.3990159011914, 1336.8379103270627, 1253.635910753905],
[1328.1765246507357, 1353.1879576378208, 1391.94935171302, 1419.4723595055307, 1436.012266121132,
1448.4136632819252, 1346.110107123306, 1411.6812049560685, 1441.2949816305224, 1380.5627492161482,
1312.6260756214342, 1359.85895865934, 1380.3851780875336, 1356.023191076924, 1330.8989844393104,
1351.9296714736968, 1356.4851064483519, 1337.4758375470306],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1460.7498660143006, 1410.0728187816906,
1427.4464699502457, 1338.1539823621792, 1373.4882526392807, 1377.483347538101, 1373.6246453797514,
1387.3376104301349, 1441.5264866455693, 1348.6983324094676, 1338.5720560333045, 1324.1236454249363,
1354.1914050001853, 1338.8665448937927, 1291.2684553450981],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1290.7792571204702,
1214.308347749437, 1200.58340380531, 1239.501463648965, 1428.4077716261145, 1377.987085647185,
1398.1278396468706, 1428.7798719957766, 1385.7469740316235, 1356.5052284818378, 1330.6706853931034,
1353.4385628020025, 1335.2583787011524, 1288.6298545399088],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1442.8167958144866, 1406.2259749595107, 1428.1080839534975, 1426.0580976301176, 1381.5838277366659,
1397.6065029785466, 1430.6366358870098, 1387.3287325595181, 1359.7125256576942, 1333.3789756932902,
1355.1829245789684, 1339.515619602179, 1291.7515379563479],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1381132403171, 1432.010926615392, 1431.3321798901468, 1378.0565228773867,
1396.81940623514, 1432.7982708122322, 1377.8612793152831, 1350.6348893911354, 1327.8024309518744,
1345.099570863568, 1328.029161164731, 1280.9350822776496],
[1328.1765246507357, 1504.1073057068995, 1219.5661435925442, 1460.274343713098, 1436.3592446035104,
1425.1034928610165, 1339.2784050231967, 1443.2730535440444, 1425.0924476853634, 1363.5785187957338,
1341.4800219444169, 1423.9137275869386, 1349.7704669791651, 1360.7630386223702, 1333.425113996663,
1366.2030511798673, 1337.4231380704002, 1291.6640507163672],
[1328.1765246507357, 1353.1879576378208, 1410.579915824099, 1462.9235155522852, 1394.8132884136066,
1414.5613788698495, 1392.1522068490503, 1431.5057538173428, 1440.2238046243085, 1387.293910964124,
1399.5857248683053, 1435.6166727422476, 1388.969821621961, 1364.2475752956364, 1332.0464144720595,
1354.9038046415044, 1339.1743300404082, 1291.630256209334],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.4159965010651, 1411.3548799046819,
1425.7224684005503, 1391.377051941948, 1431.8159723489114, 1431.278025139241, 1358.8212920663784,
1380.2436201750243, 1425.1958017919642, 1384.3256466756068, 1359.07917364794, 1332.9247098888873,
1353.1637744754123, 1336.07627725299, 1290.0476381211815],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1393.4337378530465,
1409.835132447911, 1391.1722552886845, 1417.0328256395617, 1432.3487735073522, 1378.2772749194908,
1396.6008401570577, 1433.1155975041377, 1390.5914406805628, 1362.6765110445174, 1334.5762051476459,
1361.4369514102002, 1336.6893145856227, 1288.9669265353398],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1424.8510324458748, 1390.7715313987126, 1431.7204129721713, 1431.9081214684788, 1378.1928653857747,
1396.5681148308058, 1430.780621400254, 1384.5714015170224, 1359.6447860912401, 1330.3893264075632,
1353.4188754217143, 1336.859504893905, 1288.08174852749],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.375915240571, 1420.9624704974776, 1421.2395781820762, 1367.800240844252,
1399.9786499043562, 1424.3801787948573, 1387.408334861284, 1360.107103934737, 1330.7643039541172,
1355.5080991940283, 1337.1438609436389, 1290.3414189906262],
[1328.1765246507357, 1503.913864640719, 1413.8980639539386, 1468.00534814896, 1422.8104408104573,
1423.765114927117, 1324.9175310660078, 1435.7069206999379, 1433.6130926608998, 1381.3226169858867,
1356.3795348447263, 1431.3801618130071, 1386.6510817433498, 1361.9492867624042, 1332.7701837350623,
1350.1107156688993, 1333.0696822151624, 1329.2298025753437],
[1328.1765246507357, 1353.1879576378208, 1409.2744122762876, 1454.3125460261099, 1410.4565982165238,
1424.082433572339, 1391.4733702241447, 1430.879428730335, 1414.3890111884998, 1350.34520050958,
1394.841280189504, 1429.3744950534692, 1386.4838423235042, 1356.8345977131296, 1332.5345285357314,
1354.656448130794, 1336.017705107397, 1290.1994987112023],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1286.0162095769574, 1223.6306854721179,
1277.8869653640977, 1354.6916735211269, 1421.0978338505058, 1419.4423878951538, 1357.758685952835,
1387.6171511136472, 1429.1792659040157, 1327.5638800212087, 1323.1431279704393, 1316.45311752381,
1340.1900930468087, 1333.8143956170393, 1302.8716294862143],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1369.9885881316322,
1389.746107250975, 1370.1832958235645, 1402.7731717332395, 1430.2269756772712, 1376.3970040533245,
1396.0147842886943, 1431.3398512920298, 1376.3795115633775, 1354.4061186176452, 1322.125898247653,
1347.3190083197246, 1357.8289704460617, 1309.05475863672],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1425.0648190120878, 1390.8167346028026, 1432.1377945654822, 1431.7215282770155, 1377.5399714568885,
1380.911844832686, 1424.423408758382, 1296.815612973573, 1283.9798136146878, 1256.8194756407995,
1355.3359054061746, 1338.4699601111859, 1293.041446825808],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1388.1670414052744, 1432.0300312924162, 1431.3542356778341, 1378.091812602148,
1396.8353951681145, 1432.8116506446752, 1385.8096029856881, 1357.7211709158132, 1330.4374574117403,
1353.7555347511545, 1337.7274048862123, 1288.7985560635561],
[1328.1765246507357, 1355.524217113136, 1412.9393304787225, 1465.2536583945196, 1410.697993614098,
1409.4334667878807, 1392.1943945343658, 1432.1373353197077, 1428.3902744802278, 1376.9823301026836,
1376.0674161952127, 1416.117550231582, 1383.412506204135, 1255.0784335917822, 1331.1853834984765,
1354.5528533816318, 1335.8822725180155, 1334.9239189752302],
[1328.1765246507357, 1353.1879576378208, 1410.814724976499, 1463.2075296132891, 1359.6374526982909,
1379.8017091774498, 1339.6702397963766, 1414.80823357494, 1417.2239029395234, 1361.4605045875321,
1396.318343095436, 1431.4467641883664, 1383.7222680136367, 1357.68401316966, 1330.5022749791037,
1354.0002885613083, 1335.781720673481, 1289.1835604091564],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1458.0227275098182, 1409.1231290530502,
1424.7112929163986, 1353.9694749430198, 1425.9473138683177, 1431.1149171600007, 1379.894377567314,
1399.26941534447, 1435.5745950310902, 1279.2743553908692, 1265.4957438307756, 1251.3268288661366,
1361.1714386001656, 1360.3714394835474, 1337.4519399978253],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1269.3936064664942,
1311.6416869961968, 1273.6585777553612, 1313.941461891031, 1432.7823407239148, 1380.7522541180585,
1399.1895890144515, 1431.7253108836628, 1384.9934068374707, 1359.608569164655, 1332.9293029520368,
1353.6079657716728, 1299.1185666067004, 1268.3723761743663],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1423.4143076476337, 1390.586686099597, 1430.8731140025316, 1431.3352484839065, 1377.530665193921,
1396.4032147703758, 1430.013055959338, 1385.216220842132, 1357.4682050836072, 1330.022274655173,
1353.691056324455, 1337.2310920781447, 1289.1970135479476],
[1328.1765246507357, 1353.1879576378208, 1285.3124337035306, 1276.2738975531172, 1272.385208955977,
1311.5753634371717, 1369.5460147787514, 1443.1311137429147, 1440.8509908426902, 1382.9197914159233,
1381.0026954392465, 1444.6890646393772, 1353.2513864631362, 1341.0551593686894, 1305.9609304041398,
1331.0007656836608, 1328.9668585129314, 1289.3981557047607]]]
k=5
f1_sum=[0 for i in range(18)]
f2_sum = [0 for i in range(18)]
f3_sum = [0 for i in range(18)]
f4_sum = [0 for i in range(18)]
f5_sum = [0 for i in range(18)]
f6_sum = [0 for i in range(18)]
for i in range(k):
f1_sum=[f1_sum[j]+result[i][0][j] for j in range(len(result[i][0]))]
f2_sum = [f2_sum[j] + result[i][1][j] for j in range(len(result[i][1]))]
f3_sum = [f3_sum[j] + result[i][2][j] for j in range(len(result[i][2]))]
f4_sum = [f4_sum[j] + result[i][3][j] for j in range(len(result[i][3]))]
f5_sum = [f5_sum[j] + result[i][4][j] for j in range(len(result[i][4]))]
f6_sum = [f6_sum[j] + result[i][5][j] for j in range(len(result[i][5]))]
f1_sum=[f1_sum[j]/k for j in range(len(f1_sum))]
f2_sum = [f2_sum[j] / k for j in range(len(f1_sum))]
f3_sum = [f3_sum[j] / k for j in range(len(f1_sum))]
f4_sum = [f4_sum[j] / k for j in range(len(f1_sum))]
f5_sum = [f5_sum[j] / k for j in range(len(f1_sum))]
f6_sum = [f6_sum[j] / k for j in range(len(f1_sum))]
r=[]
r.append(f1_sum)
r.append(f2_sum)
r.append(f3_sum)
r.append(f4_sum)
r.append(f5_sum)
r.append(f6_sum)
print(r)
cal_avg()
\ No newline at end of file
#归一化pso
import math
import time
from itertools import combinations
import numpy as np
from matplotlib import pyplot as plt
import Users
import dynamicProcess
from pso import PSO
from improvedPSO import CPSO
import tool
import GDOP
import ObjectiveFuction as OF
import constants as C
import dynamicProcess as dynamic
plt.style.use('seaborn-whitegrid')
# 设置字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
def interpolate_points(point1, point2, num_points):
# 提取点的坐标
x1, y1 = point1
x2, y2 = point2
# 计算每个点之间的间距
dx = (x2 - x1) / (num_points + 1)
dy = (y2 - y1) / (num_points + 1)
# 生成等分点坐标
interpolated_points = []
for i in range(1, num_points + 1):
x = x1 + i * dx
y = y1 + i * dy
interpolated_points.append((x, y))
return interpolated_points
#每隔一段时间计算无人机位置
def cal_uav_pos(U,k,slot):
users=U[0]
pre_uavs = tool.getUavInitialPos(k, users)
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
num=70
t=200
pso = PSO(pre_uavs, users, r_c, r_p, k, num, t)
X, V = pso.initParticle(users)
best_pos_arr=[]
best_arr=[]
for i in range(0,len(U)-3,3):
users=U[i]
if i%6==0 and i!=0:
index+=1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource_avg(pre_uavs, users, r_c)
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
# pso.re_init(pre_uavs,)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective)
best_pos_arr.append(global_pos)
best_arr.append(global_best)
pre_uavs=global_pos
print(best_arr)
print(best_pos_arr)
best_pos_arr=np.array(best_pos_arr)
np.save('uavs_pos2.npy', best_pos_arr)
def get_uavs_from_file(U):
uavs = np.load('uavs_pos2.npy')
users = U[0]
pre_uavs = tool.getUavInitialPos(5, users)
# 打印加载的数组
# print("Loaded Data:")
# print(len(uavs))
# print(pre_uavs)
return uavs
def whole_process_new(U,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
users=U[0]
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
fitness=[]
df_c=dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
e=0
j=1
r_s=[]
g_s=[]
UAVS=get_uavs_from_file(U)
a=0
for i in range(10,3*C.r_change_slot,slot2):
if i%C.r_change_slot==0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
#每slot1时隙动一次位置
if i%slot1==0 and i!=0:
uavs=UAVS[a]
a+=1
users= U[j-1]#前一个时刻的位置
#根据前一个时刻的位置进行资源分配
c_association, p_association, p_all, b_all = OF.objective_resource_u(uavs, users, r_c)
#作用在这一时刻的用户位置上
users=U[j]
# interpolated_points = interpolate_points(users_pre,users, 10)
# print(interpolated_points)
f, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
if i%slot1==0 and i!=0:
print(i,rate,gdop)
break
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
# print(f)
fitness.append(f)
j+=1
print("proposed:",fitness)
print(r_s)
print(g_s)
return fitness
def whole_process(U,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
users=U[0]
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
fitness=[]
df_c=dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
e=0
j=1
r_s=[]
g_s=[]
UAVS=get_uavs_from_file(U)
a=0
for i in range(10,3*C.r_change_slot,slot2):
if i%C.r_change_slot==0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
#每slot1时隙动一次位置
if i%slot1==0 and i!=0:
uavs=UAVS[a]
a+=1
users= U[j-1]#前一个时刻的位置
#根据前一个时刻的位置进行资源分配
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
#作用在这一时刻的用户位置上
users=U[j]
f, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
fitness.append(f)
# print(f)
j+=1
print("proposed:",fitness)
print(r_s)
print(g_s)
return fitness
#统一尺度
def whole_process_unified(U,k,slot1,slot2):
# users= Users.getUsers("./data.csv")
users=U[0]
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
fitness=[]
df_c=dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
e=0
j=1
r_s=[]
g_s=[]
UAVS=get_uavs_from_file(U)
# objective_resource_avg
users = U[j - 1]
c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
a=0
for i in range(10,3*C.r_change_slot,slot2):
if i%C.r_change_slot==0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
#每slot1时隙动一次位置
# if i%slot1==0 and i!=0:
# uavs=UAVS[a]
# a+=1
users= U[j-1]#前一个时刻的位置
#根据前一个时刻的位置进行资源分配
c_association, p_association, p_all, b_all = OF.objective_resource_u(uavs, users, r_c)
#作用在这一时刻的用户位置上
users=U[j]
f, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
fitness.append(f)
# print(f)
j+=1
print("proposed:",fitness)
print(r_s)
print(g_s)
return fitness
def whole_process_kmeans(U,k,slot1,slot2):
users = U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
fitness = []
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
e = 0
j = 1
r_s = []
g_s = []
a = 0
for i in range(10, 3 * C.r_change_slot, slot2):
if i % C.r_change_slot == 0 and i != 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
# 每slot1时隙动一次位置
users = U[j - 1] # 前一个时刻的位置
# 根据前一个时刻的位置进行资源分配
c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
uavs= tool.getUavInitialPos(k, users)
# 作用在这一时刻的用户位置上
users = U[j]
f, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
fitness.append(f)
# print(f)
j += 1
print("proposed:", fitness)
print(r_s)
print(g_s)
return fitness
def fixed_position_fixed_resource(U,k,slot1,slot2):
users = U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
fitness = []
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association, p_association,
slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
fitness.append(f)
j = 1
r_s = []
g_s = []
r_s.append(r)
g_s.append(g)
for i in range(0, 3 * C.r_change_slot, slot2):
users = U[j]
j += 1
if i % C.r_change_slot == 0 and i != 0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
fitness.append(f)
print(fitness)
return fitness
def run_whole_process():
users= Users.getUsers("./data.csv")
slot1=30
slot2=10
U=dynamic.get_users_pos_from_file()
# whole_process(users,4,slot1,slot2)
fitness=[]
f_sum = []
k=5
for j in range(k):
for i in range(10,70,10):
f=whole_process_new(U, 4, i, slot2)
fitness.append(f)
f_sum.append(fitness)
print(fitness)
print(f_sum)
# whole_process_kmeans(U,4,i,slot2)
# f1_sum=[0 for i in range(19)]
# f2_sum = [0 for i in range(19)]
# f3_sum = [0 for i in range(19)]
# f4_sum = [0 for i in range(19)]
# k=3
# for i in range(k):
# f1=whole_process_new(U, 4, slot1, slot2)
# f2=fixed_position_dynamic_resource2(U, 4, slot1, slot2)
# f3=fixed_resource_dynamic_position2(U,4,slot1,slot2)
# f4=same_dynamic_resource_dynamic_position2(U,4,slot1,slot2)
# f1_sum=[f1_sum[j]+f1[j] for j in range(len(f1))]
# f2_sum = [f2_sum[j] + f2[j] for j in range(len(f1))]
# f3_sum = [f3_sum[j] + f3[j] for j in range(len(f1))]
# f4_sum = [f4_sum[j] + f4[j] for j in range(len(f1))]
# f1_avg=[f1_sum[i]/k for i in range(len(f1_sum))]
# f2_avg = [f2_sum[i] / k for i in range(len(f1_sum))]
# f3_avg = [f3_sum[i] / k for i in range(len(f1_sum))]
# f4_avg = [f4_sum[i] / k for i in range(len(f1_sum))]
# print(f1_avg)
# print(f2_avg)
# print(f3_avg)
# print(f4_avg)
# fixed_position_fixed_resource(U, 4, slot1, slot2)
def fixed_position_dynamic_resource2(U,k,slot1,slot2):
users=U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index=0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c,df_p,index)
fitness = []
j=1
r_s,g_s=[],[]
for i in range(0, 3 * C.r_change_slot, slot2):
if i % C.r_change_slot == 0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
users = U[j - 1] # 前一个时刻的位置
# 根据前一个时刻的位置进行资源分配
c_association, p_association, p_all, b_all = OF.objective_resource_u(uavs, users, r_c)
users=U[j]
f, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association, p_association,slot2)
print(f, rate, gdop)
fitness.append(f)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
j+=1
print("fixed_position_dynamic_resource:",fitness)
print("fixed_position_dynamic_resource:", r_s,g_s)
return fitness
def fixed_resource_dynamic_position2(U,k,slot1,slot2):
users=U[0]
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
df_c = dynamic.read_csv_to_df('r_c.csv')
df_p = dynamic.read_csv_to_df('r_p.csv')
index = 0
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
fitness = []
c_association, p_association, p_all, b_all = OF.objective_resource_u(uavs, users, r_c)
j=1
a=0
UAVS=get_uavs_from_file(U)
r_s,g_s=[],[]
for i in range(0, 3 * C.r_change_slot, slot2):
if i % C.r_change_slot == 0 and i!=0:
index = index + 1
r_c, r_p = dynamic.get_r_c_and_r_p(df_c, df_p, index)
if i % slot1 == 0 and i != 0:
uavs = UAVS[a]
a += 1
users = U[j - 1] # 前一个时刻的位置
# 根据前一个时刻的位置进行资源分配
# 作用在这一时刻的用户位置上
users = U[j]
j=j+1
f, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c, r_p, p_all, b_all, c_association,
p_association, slot2)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
r_s.append(r)
g_s.append(g)
fitness.append(f)
# print(f)
print("fixed_resource_dynamic_position",fitness)
print("fixed_resource_dynamic_position:", r_s, g_s)
return fitness
# run_whole_process()
if __name__ == '__main__':
U = dynamicProcess.get_users_pos_from_file()
U=U[:19]
# cal_uav_pos(U,5,10)
# get_uavs_from_file(U)
# whole_process(U, 5, 30, 10)
whole_process_new(U, 5, 30, 10)
# whole_process_unified(U, 5, 30, 10)
# whole_process(U, 5, 30, 10)
# whole_process_kmeans(U,5,30,10)
# fixed_position_dynamic_resource2(U,5,30,10)
# fixed_resource_dynamic_position2(U,5,30,10)
#归一化pso
import math
import time
from itertools import combinations
import numpy as np
from matplotlib import pyplot as plt
import Users
from pso import PSO
from improvedPSO import CPSO
import tool
import GDOP
import ObjectiveFuction as OF
import constants as C
import dynamicProcess as dynamic
plt.style.use('seaborn-whitegrid')
# 设置字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
def ipso_convex(users,k,r_c,r_p):
# users= Users.getUsers("./data.csv")
uavs=tool.getUavInitialPos(k,users)
pre_uavs=uavs
# r_c,r_p=dynamic.random_r(users)
c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
# c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
c_association, p_association, p_all, b_all = OF.objective_resource(global_pos, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users, r_c,r_p, p_all, b_all, c_association,
p_association, C.time_slot)
print("real-f",f)
r,g=OF.cal_satisfaction(global_pos,users,p_all,b_all,r_c,r_p, c_association,p_association)
print("pso_convex",global_best,r,g)
if f>global_best[0]:
return f,r,g
return global_best[0],r,g
def ipso_avg(users,k,r_c,r_p):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
pso = CPSO(pre_uavs, users, r_c, r_p, k, )
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
f, e, rate, gdop = OF.real_objective(pre_uavs, global_pos, users, r_c, r_p, p_all, b_all, c_association,
p_association, C.time_slot)
r, g = OF.cal_satisfaction(global_pos, users, p_all, b_all, r_c, r_p, c_association, p_association)
print("pso_avg",global_best,r,g)
if global_best[0]<0:
return f,r,g
else:
return global_best[0],r,g
def pso_convex(users,k,r_c,r_p):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
pso = PSO(pre_uavs, users, r_c, r_p, k, )
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
print(global_best)
def pso_avg(users,k,r_c,r_p):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
c_association, p_association, p_all, b_all = OF.objective_resource_avg(uavs, users, r_c)
pso = PSO(pre_uavs, users, r_c, r_p, k, )
pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
X, V = pso.initParticle(users)
global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
print(global_best)
def kmeans_convex(users,k,r_c,r_p):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
c_association, p_association, p_all, b_all = OF.objective_resource(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users, r_c,r_p, p_all, b_all, c_association,
p_association, C.time_slot)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
# pso = PSO(pre_uavs, users, r_c, r_p, k, )
# pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
# X, V = pso.initParticle(users)
# global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
print("km_convex",f,r,g)
return f,r,g
def kmeans_avg(users,k,r_c,r_p):
uavs = tool.getUavInitialPos(k, users)
pre_uavs = uavs
# r_c,r_p=dynamic.random_r(users)
c_association, p_association, p_all, b_all = OF.objective_resource_proportion(uavs, users, r_c)
f, e, rate, gdop = OF.real_objective(pre_uavs, uavs, users,r_c, r_p, p_all, b_all, c_association,
p_association, C.time_slot)
r, g = OF.cal_satisfaction(uavs, users, p_all, b_all, r_c, r_p, c_association, p_association)
# pso = PSO(pre_uavs, users, r_c, r_p, k, )
# pso.re_init(pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all)
# X, V = pso.initParticle(users)
# global_pos, global_best, result = pso.pso(X, V, OF.linear_w, OF.objective, )
print("km_avg",f,r,g)
return f,r,g
#
# users= Users.getUsers("./data.csv")
# df_c=dynamic.read_csv_to_df('r_c.csv')
# df_p = dynamic.read_csv_to_df('r_p.csv')
# index=0
# r_c,r_p=dynamic.get_r_c_and_r_p(df_c,df_p,index)
# # pso_convex(users,4,r_c,r_p)
# # pso_avg(users,4,r_c,r_p)
# kmeans_convex(users,4,r_c,r_p)
# kmeans_avg(users,4,r_c,r_p)
def compare():
k=4
r1,r2,r3,r4=[],[],[],[]
r_satisfaction,g_satisfaction=[[] for i in range(4)],[[] for i in range(4)]
num=17
sum1,sum2,sum3,sum4=0,0,0,0
time=10
for i in range(0,time):
users=Users.generate(num)
r_c,r_p=dynamic.random_r(users)
s=[0 for i in range(4)]
g = [0 for i in range(4)]
result1,s[0],g[0]=ipso_convex(users, k, r_c, r_p)
result2,s[1],g[1]=ipso_avg(users, k, r_c, r_p)
result3,s[2],g[2]=kmeans_convex(users, k, r_c, r_p)
result4,s[3],g[3]=kmeans_avg(users, k, r_c, r_p)
sum1 += result1
sum2 += result2
sum3 += result3
sum4 += result4
r1.append(result1)
r2.append(result2)
r3.append(result3)
r4.append(result4)
for i in range(4):
r_satisfaction[i].append(s[i])
g_satisfaction[i].append(g[i])
print(r1,r2,r3,r4)
print(r_satisfaction,g_satisfaction)
print(sum1/time,sum2 /time,sum3 / time,sum4 / time)
compare()
# [[0.8, 0.5714285714285714, 0.5555555555555556, 0.5454545454545454, 0.46153846153846156, 0.6, 0.5294117647058824, 0.42105263157894735], [1.0, 1.0, 1.0, 1.0, 0.8461538461538461, 0.8666666666666667, 0.8823529411764706, 0.7368421052631579], [1.0, 1.0, 1.0, 1.0, 0.9230769230769231, 1.0, 0.8823529411764706, 0.42105263157894735], [1.0, 1.0, 1.0, 0.9090909090909091, 0.9230769230769231, 0.9333333333333333, 0.8823529411764706, 0.8421052631578947]] [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.6666666666666666, 0.7272727272727273, 0.7692307692307693, 0.8, 0.8823529411764706, 0.8421052631578947], [1.0, 1.0, 0.6666666666666666, 0.7272727272727273, 0.7692307692307693, 0.8, 0.8823529411764706, 0.8421052631578947]]
class solution:
def __init__(self):
self.best = 0
self.bestIndividual=[]
self.convergence = []
self.optimizer=""
self.objfname=""
self.startTime=0
self.endTime=0
self.executionTime=0
self.lb=0
self.ub=0
self.dim=0
self.popnum=0
self.maxiers=0
\ No newline at end of file
import math
import Users
import numpy as np
import random
from pprint import pprint
import constants as C
import tool
import ObjectiveFuction as OF
class SPSO:
def __init__(self,pre_uavs,users,r_c,r_p,k,N=30):
#之后解析JSON,从JSON中读参数
self.N=N
self.k=k
self.pre_uavs=pre_uavs
self.users=users
self.d = 3 # 可行解维数
self.limit = [C.min_range,C.max_range] # 边界位置限制
self.vlimit = [-500, 500] # 边界速度限制
self.vlimit_h=[-10,10]
self.r_c = r_c
self.r_p=r_p
# self.height = 100
self.min_height = C.min_height
self.max_height = C.max_height
self.wmax = 0.9 # 惯性权重
self.wmin = 0.4
self.c1 = 1.496 # 自我学习因子
self.c2 = 1.496 # 群体学习因子
# self.c1 = 0.5 # 自我学习因子
# self.c2 = 0.5 # 群体学习因子
self.maxgen = 200
# self.users = Users.getUsers("./data.csv")
self.users = users
self.init_alloc()
# #todo:防止无人机位置碰撞
# def punish_function(self,uavs):
# # user_arr = [1, 2, 5]
# punish=0
# for i in range(len(uavs)):
# for j in range(i+1,len(uavs)):
# dis=self.cal_tool.getDistance(uavs[i],uavs[j])
# if dis<200:
# punish+=100
#
# return punish
def punish_f(self,uavs):
punish=0
max_dis=(C.time_slot-C.run_time)*C.speed
for i in range(len(uavs)):
dis=tool.calculate_3d_distance_uavs(uavs[i],self.pre_uavs[i])
if dis>max_dis:
punish=float('-inf')
return punish
def re_init(self, pre_uavs, users, r_c, r_p, c_association, p_association, p_all, b_all, ):
self.pre_uavs = pre_uavs
self.user = users
self.r_c = r_c
self.r_p = r_p
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(self.users)):
# r_c[i] = random.randint(1,4)
# return r_c
# 初始化粒子群,k是无人机数量
def initParticle(self, users):
X = []
# users=Users.generate(100)#用户位置
V = np.random.uniform(self.vlimit[0], self.vlimit[1], (self.N, self.k, 3))
V2 = np.random.uniform(self.vlimit_h[0], self.vlimit_h[1], (self.N, self.k, 3))
for i in range(self.N):
uavs=[]
for index in range(self.k):
x=np.random.randint(self.limit[0],self.limit[1])
y=np.random.randint(self.limit[0],self.limit[1])
z=50
uavs.append([x,y,z])
X.append(uavs)
X = np.array(X)
return X, V,
def init_alloc(self,):
c_association, p_association, p_all, b_all = OF.objective_resource_avg(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 initBest(self, X,):
p_pos = X.copy() # 每个个体的历史最佳位置
global_pos = np.zeros((self.k, 3)) # 种群的历史最佳位置5*3
p_best = np.full((self.N, 1), float('-inf')) # 每个个体的历史最佳适应度
global_best = float('-inf') # 种群历史最佳适应度
return p_pos, global_pos, p_best, global_best
def pso(self, X, V, update_w,get_fitness,):
# X, V, users = initParticlePos()
p_pos, global_pos, p_best, global_best = self.initBest(X)
result = np.zeros(self.maxgen)
fitness = np.zeros(self.N)
for iter in range(self.maxgen):
# fitness = self.getfitness(X, users, k,P) # 计算所有粒子适应度
for i in range(len(X)):
# punish = self.punish_f(X[i])
# if punish == float('-inf'):
# fitness[i] = punish
# else:
f, _, _ = get_fitness(self.pre_uavs, X[i], self.users, self.r_c, self.r_p, self.p_all, self.b_all,
self.c_association, self.p_association)
fitness[i] = f
# f,_,_=get_fitness(self.pre_uavs,X[i],self.users,self.r_c,self.r_p)
# f,_,_=get_fitness(self.pre_uavs, X[i], self.users, self.r_c,self.r_p, self.p_all, self.b_all, self.c_association,
# self.p_association)
# fitness[i]= f+self.punish_f(X[i])
for i in range(self.N):
if fitness[i] > p_best[i]:
p_best[i] = fitness[i] # 更新个体历史最佳适应度
p_pos[i] = X[i].copy() # 更新个体历史最佳位置(取值)
if max(p_best) > global_best:
global_best = max(p_best) # 更新群体历史最佳适应度
max_index = p_best.argmax()
global_pos = X[max_index].copy() # 更新群体历史最佳位置
# 权重更新
# w = self.wmax - iter * (self.wmax - self.wmin) / self.maxgen
# w = (self.wmax +self.wmin)/2
w=update_w(self.wmin,self.wmax,iter,self.maxgen,iter,fitness)
for i in range(self.N):
V[i] = V[i] * w + self.c1 * random.random() * (p_pos[i] - X[i]) + self.c2 * random.random() * (
global_pos - X[i])
# V2[i] = V2[i] * w + self.c1 * random.random() * (p_pos[i] - X[i]) + self.c2 * random.random() * (
# global_pos - X[i])
# print(V[i])
for j in range(len(V[i])):
for p in range(len(V[i][j])):
if V[i][j][p] > self.vlimit[1]:
V[i][j][p] = self.vlimit[1]
# V[i][j][p] = self.vlimit[0]+np.random.rand(1)*(self.vlimit[1]-self.vlimit[0])
elif V[i][j][p] < self.vlimit[0]:
V[i][j][p] = self.vlimit[0]
# if V2[i][j][p] > self.vlimit_h[1]:
# V2[i][j][p] = self.vlimit_h[1]
# # V[i][j][p] = self.vlimit[0]+np.random.rand(1)*(self.vlimit[1]-self.vlimit[0])
# elif V2[i][j][p] < self.vlimit_h[0]:
# V2[i][j][p] = self.vlimit_h[0]
# print(V[i])
# 位置更新
X = X + V
# 边界位置处理
for i in range(self.N):
for j in range(len(X[i])):
for p in range(2):
if X[i][j][p] > self.limit[1]:
X[i][j][p] = self.limit[1]
elif X[i][j][p] < self.limit[0]:
X[i][j][p] = self.limit[0]
X[i][j][2] = self.min_height
# if X[i][j][2] > self.max_height:
# X[i][j][2] = self.max_height
# elif X[i][j][2] < self.min_height:
# X[i][j][2] = self.min_height
result[iter] = global_best
print(iter,global_pos,global_best)
# print(global_best)
# print(global_pos)
return global_pos,global_best,result
if __name__ == '__main__':
uavs=[[868.34535881,315.18340086,50. ],
[292.96443022,729.7612657,77.75450997],
[732.25467955,927.62861821,50. ],
[303.40107629,240.31208079,150. ]]
# 示例
# print(0.012 / 8 * 1.225 * 0.05 * 0.79 * 400 ** 3 * 0.5 ** 3)
# print((1+0.1)*100**1.5/math.sqrt(2*1.225*0.79))
best=[[335,772,67], [382,739,75], [1758,1683,137], [885,762,133], [403,1196,94], [1049,358,88]]
import math
import scipy.integrate
import numpy as np
from sklearn.cluster import KMeans
import GDOP
from itertools import combinations
import copy
import Users
# from Match import Match
import km
import constants as C
def calculate_3d_distance(a, b):
return math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2) + math.pow(a[2] - 0, 2))
def calculate_3d_distance_uavs(a, b):
return math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2) + math.pow(a[2] - b[2], 2))
# 计算3d距离
def calculate_2d_distance(a, b):
return math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2))
def cal_dis_for_user(uavs,user):
dis=[]
for uav in uavs:
d=calculate_3d_distance(uav,user)
dis.append(d)
print(dis)
# 计算森林信道路径损耗
def forest_path_loss(uav, user):
dis = calculate_3d_distance(uav, user)
# alpha = 3.5
alpha = 3
A = 0.25
C = 0.39
E = 0.25
G = 0
B = 1
H = 0.05
f_c = 2 * 10 ** 9
c = 1 * 10 ** 8
path_loss = 10 * alpha * math.log10(dis)
theta = math.asin(uav[2] / dis)
theta = math.degrees(theta)
dis1 = dis # 无人机和用户间树叶的距离
slant = A * math.pow(f_c / 1e6, C) * math.pow(dis1, E) * math.pow(theta + G, H)
fspl = 20 * math.log10(4 * math.pi * 1 * f_c / c)
L_K_N = slant + fspl + path_loss
# print(L_K_N)
# L_K_N=expect(L_K_N)
return L_K_N
def forest_path_loss_dis(dis):
# alpha = 3.5
alpha = 3
A = 0.25
C = 0.39
E = 0.25
G = 0
B = 1
H = 0.05
f_c = 2 * 10 ** 9
c = 1 * 10 ** 8
path_loss = 10 * alpha * math.log10(dis)
theta = math.asin(50 / dis)
theta = math.degrees(theta)
dis1 = dis # 无人机和用户间树叶的距离
slant = A * math.pow(f_c / 1e6, C) * math.pow(dis1, E) * math.pow(theta + G, H)
fspl = 20 * math.log10(4 * math.pi * 1 * f_c / c)
L_K_N = slant + fspl + path_loss
return L_K_N
def expect_L(l1):
sigma = 3
R_u = lambda x1: ((10 ** (-(l1 + x1) / 10))) * 1 / (math.sqrt(2 * math.pi) * sigma) * math.exp(
-(x1 ** 2) / (2 * sigma ** 2))
R2, err = scipy.integrate.quad(R_u, -float("100"), float("100"))
return R2
def expect(l1):
sigma = 3
R_u = lambda x1: (l1+x1) / (math.sqrt(2 * math.pi) * sigma) * math.exp(
-(x1 ** 2) / (2 * sigma ** 2))
R2, err = scipy.integrate.quad(R_u, -float("100"), float("100"))
# print("阴影衰落:", R2)
return R2
def path_loss_dis(dis,h):
a = 9.6
b = 0.28
los = 1
nlos = 20
freePathLoss = 20 * math.log10(dis) + (20 * math.log10(2000000000)) + 20 * math.log10(4 * (math.pi) / 3 / 100000000)
angle = math.asin(h / dis)
angle = angle / math.pi * 180
plos = 1 / (1 + a * math.exp(-b * (angle - a)))
pnlos = 1 - plos
pl = plos * los + pnlos * nlos + freePathLoss
return pl
def free_path_loss(dis):
freePathLoss = 20 * math.log10(dis) + (20 * math.log10(2000000000)) + 20 * math.log10(4 * (math.pi) / 3 / 100000000)
return freePathLoss
# 计算snr
def cal_snr(uav, user, p):
# loss = forest_path_loss(uav, user)
dis=calculate_3d_distance(uav,user)
loss=path_loss_dis(dis,uav[2])
noise_power = (10 ** (C.N0 / 10)) / 1000
snr = p * (10 ** (-loss / 10)) / noise_power
return 10 * math.log10(snr)
def cal_snr2(uav, user, p):
dis = calculate_3d_distance(uav, user)
loss = path_loss_dis(dis, uav[2])
noise_power = (10 ** (C.N0 / 10)) / 1000
snr = p * (10 ** (-loss / 10)) / noise_power
return snr
def cal_snr_forest(uav, user, p):
# loss = forest_path_loss(uav, user)
# dis=calculate_3d_distance(uav,user)
loss=forest_path_loss(uav,user)
noise_power = (10 ** (C.noise / 10)) / 1000
snr = p * (10 ** (-loss / 10)) / noise_power
return 10 * math.log10(snr)
def cal_snr_f(uav, user, p):
dis = calculate_3d_distance(uav, user)
loss = forest_path_loss(uav, user)
noise_power = (10 ** (C.noise / 10)) / 1000
snr = p * (10 ** (-loss / 10)) / noise_power
# snr=p*loss/noise_power
return snr
def path_loss(uav,user):
dis=calculate_3d_distance(uav,user)
h=uav[2]
a = 9.6
b = 0.28
los = 1
nlos = 20
freePathLoss = 20 * math.log10(dis) + (20 * math.log10(2000000000)) + 20 * math.log10(4 * (math.pi) / 3 / 100000000)
angle = math.asin(h / dis)
angle = angle / math.pi * 180
plos = 1 / (1 + a * math.exp(-b * (angle - a)))
pnlos = 1 - plos
pl = plos * los + pnlos * nlos + freePathLoss
return pl
def cal_u(R,d,h):
dis1=math.sqrt(R**2+h**2)
dis2=math.sqrt((R+d)**2+h**2)
loss1=forest_path_loss_dis(dis1)
loss2=forest_path_loss_dis(dis2)
noise_power = (10 ** (C.noise / 10)) / 1000
sum_u=0
snr1 = C.pmax * C.pmax * (10 ** (-loss1 / 10)) / noise_power
snr2 = C.pmax* C.pmax * (10 ** (-loss2 / 10)) / noise_power
u = math.log(1 + snr1) / math.log(1 + snr2)
# for i in range(1,1001):
# snr1 =i/1000*C.pmax * (10 ** (-loss1 / 10)) / noise_power
# snr2=i/1001*C.pmax * (10 ** (-loss2 / 10)) / noise_power
# u=math.log(1+snr1)/math.log(1+snr2)
# sum_u+=u
# u=sum_u/1000
print(u)
return u
def cal_max_radius(Rmin):
log=Rmin/C.B_max
print(log)
c = 1 * 10 ** 8
noise_power = (10 ** (C.noise / 10)) / 1000
h=(10**log-1)*noise_power/C.pmax
L=-10*math.log10(h)
r=900
H=50
dis=math.sqrt(r**2+H**2)
l=forest_path_loss_dis(dis)
# fspl = 20 * math.log10(4 * math.pi * 1 * C.f_c / c)
# r=10**(L-fspl)/30
print(l)
return r
#计算速率
def cal_rate(b,p,uav,user):
snr=cal_snr_f(uav,user,p)
date_rate = b* math.log2(1 + snr)
return date_rate
# 计算数据传输速率
def cal_data_rate(snr, bandwidth):
date_rate = bandwidth * math.log2(1 + snr)
return date_rate
def dbmToW(p):
return pow(10, p / 10) / 1000
#获得每个用户的定位无人机组
def get_user_loc_uav(users,p_association):
user_loc_uav={}
for i in range(len(users)):
user_loc_uav[i]=[]
for i in range(len(p_association)):
for j in range(len(p_association[i])):
if p_association[i][j]==1:
user_loc_uav[j].append(i)
return user_loc_uav
def getUavInitialPos(k, users):
model = KMeans(n_clusters=k, # 聚类簇数
random_state=1, # 决定质心初始化的随机数生成,使用int使随机性具有确定性。
max_iter=300, # 执行一次k-means算法所进行的最大迭代数,默认300
).fit(users)
center = model.cluster_centers_
uavs = []
for item in center:
# height = random.randint(100, 800)
height = 50
position = [int(item[0]), int(item[1]), height]
uavs.append(position)
# print(center)
return uavs
import skfuzzy as fuzz
def fuzzy_c_means_clustering(points, n_clusters, m=2, error=0.005, max_iter=1000, seed=None):
data = np.array(points)
# 运行模糊均值聚类
cntr, _, _, _, _, _, _ = fuzz.cluster.cmeans(
data.T, n_clusters, m, error, max_iter, seed=seed)
return cntr
def getUavInitialPos_fcm(k, users):
center=fuzzy_c_means_clustering(users,k)
uavs=[]
for item in center:
# height = random.randint(100, 800)
height = 50
position = [int(item[0]), int(item[1]), height]
uavs.append(position)
# print(center)
return uavs
def get_c_association(users,uavs_pos,serveMax):
user_num = len(users)
uavs = [k for k in range(len(uavs_pos))]
uav_num = len(uavs)
# print(distance_sum)
weight = np.zeros((user_num, uav_num), dtype=np.float16)
graph = []
for i in range(user_num):
for j in uavs:
# weight[i][j]=-self.distance_c[i][j]/(distance_sum[i]-self.distance_c[i][j])
weight[i][j] = -calculate_3d_distance(uavs_pos[j],users[i])
dic = {}
for i in range(user_num):
for j in uavs:
for number in range(serveMax):
graph.append((i, j + 100 * number, weight[i][j]))
dic[j + 100 * number] = j
connection = km.run_kuhn_munkres(graph)
c_connection = {}
for connect in connection:
c_connection[connect[0]] = dic[connect[1]]
# print(c_connection)
return c_connection
def get_uav_to_user(c_connection,uavs):
uav_to_user={}
for i in range(len(uavs)):
uav_to_user[i]=[]
for i in c_connection:
uav_to_user[c_connection[i]].append(i)
return uav_to_user
# 选择好通信的无人机后,确定其他两架无人机与该无人机对用户获得最优的gdop值
def get_p_association(users,uavs,c_connection,service_num):
p_connection={}
for i in c_connection:
p_connection[i]=[]
if len(uavs)==3:
for i in range(len(users)):
uavs_all=[i for i in range(len(uavs))]
uavs_all.remove(c_connection[i])
p_connection[i]=[uavs_all[0],uavs_all[1]]
else:
uavs_initial = [i for i in range(len(uavs))]
uav_group_all = list(combinations(uavs_initial, 3))
uav_serive_num = [service_num for i in range(len(uav_group_all))]
uav_group_dic={}
for i in range(len(uav_group_all)):
uav_group_dic[uav_group_all[i]]=i
# uav_serive_num=[service_num for i in range(len(uavs))]
for i in range(len(users)):
#获得所有信道数量大于0的无人机编号
# uav_need=[i for i in range(len(uavs)) if uav_serive_num[i]>0]
uav_need = [i for i in range(len(uav_group_all)) if uav_serive_num[i] > 0]
uav_groups = [uav_group_all[i] for i in uav_need]#所有可用的uav_group
#移除通信的无人机
uav_group=[]
uav_dic={}
count=0
for group in uav_groups:
if c_connection[i] in group:
tmp=[group[0],group[1],group[2]]
tmp.remove(c_connection[i])
uav_group.append(tmp)
uav_dic[count]=group#找到group对饮的下标
count+=1
# uav_need.remove(c_connection[i])
# uav_group=list(combinations(uav_need, 2))
gdop_min = float('inf')
index = 0
for j in range(len(uav_group)):
uavs_pos = [uavs[c_connection[i]], uavs[uav_group[j][0]],uavs[uav_group[j][1]]]
gdop_current = GDOP.calculate_gdop(uavs_pos, copy.copy(users[i]))
if gdop_current < gdop_min:
gdop_min = gdop_current
index = j
# print(gdop_min)
p_connection[i].extend([uav_group[index][0], uav_group[index][1]])
uav_serive_num[uav_group_dic[uav_dic[index]]]-=1
# print(p_connection)
return p_connection
# def cal_max_rate():
def get_p_by_snr(snr,uav,user,noise):
dis = calculate_3d_distance(uav, user)
pl= path_loss_dis(dis, uav[2])
# pl=path_loss_dis(uav,user)
noise=dbmToW(noise)
p=(10**(snr/10))*noise/10**(-pl/10)
# print(p)
return p
def get_p_by_snr_f(snr,uav,user,noise):
dis = calculate_3d_distance(uav, user)
pl= forest_path_loss(uav, user)
# pl=path_loss_dis(uav,user)
noise=dbmToW(noise)
p=(10**(snr/10))*noise/10**(-pl/10)
# print(p)
return p
def get_rest_p(users,uavs,p_connection,snr_thre=C.snr_thre,noise=C.N0,pmax=C.pmax):
p_rest=[pmax for i in range(len(uavs))]
for user_index in p_connection:
uav_group=p_connection[user_index]
for uav_index in uav_group:
p_need=get_p_by_snr(snr_thre,uavs[uav_index],users[user_index],noise)
p_rest[uav_index] -= p_need
if p_rest[uav_index]<=0:
p_rest[uav_index]=0
return p_rest
def get_rest_p_f(users,uavs,p_connection,snr_thre=0,noise=C.N0,):
p_rest=[C.pmax for i in range(len(uavs))]
for user_index in p_connection:
uav_group=p_connection[user_index]
for uav_index in uav_group:
p_need=get_p_by_snr(snr_thre,uavs[uav_index],users[user_index],noise)
p_rest[uav_index]-=p_need
return p_rest
def get_dis(i,uavs_pos,users,uav_to_user):
dis=[]
for k in uav_to_user[i]:
dis.append(calculate_3d_distance(uavs_pos[i],users[k]))
return dis
def init_p(uavs_pos,users):
c_association=get_c_association(users,uavs_pos,math.ceil(len(users)/len(uavs_pos)))
uav_to_user=get_uav_to_user(c_association,uavs_pos)
# print(uav_to_user)
p_association = get_p_association(users, uavs_pos, c_association, len(users) * 2)
p_rest=get_rest_p(users,uavs_pos,p_association)
# print(p_rest)
p_alloc=[]
for i in range(len(uavs_pos)):
#归一化生成 功率
dis=get_dis(i,uavs_pos,users,uav_to_user)
# p=[random.randint(1,len(uav_to_user[i])) for i in range(len(uav_to_user[i]))]
p_new=[0 for i in range(len(users))]
for j in range(len(uav_to_user[i])):
p_new[uav_to_user[i][j]]=dis[j]/sum(dis)*p_rest[i]
# p_new.append(p[j]/sum(p)*p_rest[i])
p_alloc.append(p_new)
# p_alloc.append(np.random.uniform(0, p_rest[i] / len(uav_to_user[i]), (len(uav_to_user[i]))))
return p_alloc
def cal_fly_energy(dis,speed):
e1=C.P0*(1+3*speed**2/C.U**2)
e2=C.P1*math.sqrt(math.sqrt(1+speed**4/4*C.vr**4)-speed**2/2*C.vr**2)
e3=0.3*1.225*0.05*0.79*speed**3
e=C.P_0 * (1 + (3 * speed**2) / (C.U_tip**2)) + C.P_i * (np.sqrt(1+(speed**4/(4*(C.v_0**4))))-speed**2/(2*(C.v_0**2)))**0.5 + (0.5 * C.d_0 * C.rho * C.sigma * C.A * speed**3)
# +(0.5 * d_0 * rho * sigma * A * V**3)
# return (e1+e2+e3)*dis/speed
return e*dis/speed
if __name__ == '__main__':
users=Users.getUsers("./data.csv")
uavs=getUavInitialPos(4,users)
r=cal_max_radius(0.3)
u=cal_u(r,10,50)#1.13#1.21
# c_connection=get_c_association(users,uavs,math.ceil(len(users)/len(uavs)))
# p_connection=get_p_association(users,uavs,c_connection,math.ceil(len(users)*2/len(uavs)))
# print(c_connection)
# print(p_connection)
# print(get_uav_to_user(c_connection,uavs))
# print(cal_snr(uavs[0],users[0],0.003))
# print(get_p_by_snr(20,uavs[0],users[0],C.N0))
# print(get_p_by_snr_f(0, uavs[0], users[0], C.noise))
# print(cal_rate(0.19,0.005,uavs[0],users[0]))
# print(cal_snr_forest(uavs[0],users[0],0.003))
# print((10 ** (C.N0 / 10)) / 1000)
# print(get_rest_p(users,uavs,p_connection))
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
<option value="N806" />
<option value="N803" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/featureRepository.iml" filepath="$PROJECT_DIR$/.idea/featureRepository.iml" />
</modules>
</component>
</project>
\ No newline at end of file
import os
import glob
import math
import openpyxl
from pprint import pprint
import torch
import torch.nn as nn
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
from torch.cuda.amp import autocast as autocast
from torch.cuda.amp import GradScaler
import torch.utils.data as data
# ranger
from ranger import Ranger
from cvae_base import CVAE
class GRU_attention(nn.Module):
def __init__(self, input_size=10, hidden_layer_size=50, num_layers=1):
super().__init__()
self.hidden_layer_size = hidden_layer_size
self.num_layers = num_layers
self.gru = nn.GRU(input_size, hidden_layer_size,num_layers, batch_first=True)
self.fc1 = nn.Linear(hidden_layer_size, 30)
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=(5, 1), stride=(1, 1), padding=(2, 0))
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(5, 1), stride=(1, 1), padding=(2, 0))
self.conv3 = nn.Conv2d(in_channels=32, out_channels=1, kernel_size=(5, 1), stride=(1, 1), padding=(2, 0))
self.fc2 = nn.Linear(200*10, 30)
self.relu = nn.ReLU()
encoder_layer_sizes = [6, 256, 128]
latent_size = 32
decoder_layer_sizes = [128, 256, 3]
conditional = True
num_labels = 3
# 初始化模型
self.cvae = CVAE(encoder_layer_sizes, latent_size, decoder_layer_sizes, conditional, num_labels)
def forward(self, input_seq, labels):
h_0 = torch.zeros(self.num_layers, input_seq.size(0), self.hidden_layer_size).to(input_seq.device)
output, _= self.gru(input_seq, h_0)#[16,200,50]
output =self.fc1(output[:, -1, :])
#print(output.shape)#16,30
output = output.view(-1,10,3)
#print(output.shape)#16,10,3
cnn_input = input_seq[:, :, :]
#print(cnn_input.shape)#16,200,10
out2 = cnn_input.unsqueeze(1) # 增加一个维度,以匹配卷积层的输入 (batch, channels, height, width)
#print(out2.shape)#16,1,200,10
out2 = self.relu(self.conv1(out2)) # 16 * 1 * 10 *
#print(out2.shape)#16,16,200,10
out2 = self.relu(self.conv2(out2)) # 32 * 1 * 10 * 10
#print(out2.shape)#16,32,200,10
out2 = self.conv3(out2) # 1 * 1 * 10 * 10
#print(out2.shape)#16,1,200,10
out2 = out2.view(-1, 200*10) # -1表示自动计算该维度的大小
#print(out2.shape)#16,2000
out2 = self.fc2(out2)
#print(out2.shape)#16,30
out2 = out2.view(-1,10,3)#16,10,3
out = torch.cat((output,out2),dim=2) # [batch size, 10, 6]
# print(out.shape)#16,10,20
H_yy, means,log_var, z = self.cvae(out, labels) # [batch size, 10, 3]
# print(labels.shape)
# recon_y = acc_to_abs(H_yy, cnn_input)
return H_yy, means,log_var, z
# 将加速度转换为绝对坐标
def acc_to_abs(acc,obs,delta=1):
acc = acc.permute(2,1,0)
pred = torch.empty_like(acc)
pred[0] = 2*obs[-1] - obs[0] + acc[0]
pred[1] = 2*pred[0] - obs[-1] + acc[1]
for i in range(2,acc.shape[0]):
pred[i] = 2*pred[i-1] - pred[i-2] + acc[i]
return pred.permute(2,1,0)
# 计算均方根误差
def rmse(y1,y2):
criterion = nn.MSELoss()
# return loss
return torch.sqrt(criterion(y1, y2))
def mae(y1, y2):
criterion = nn.L1Loss()
loss = criterion(y1, y2)
return loss
def loss_func(recon_y,y,mean,log_var):
traj_loss = mae(recon_y,y)
KLD = -0.5 * torch.sum(1 + log_var - mean.pow(2) - log_var.exp())
return traj_loss + KLD, traj_loss
def rmse_loss(y_pred, y_true):
return torch.sqrt(torch.mean((y_pred - y_true) ** 2))
class Mydataset(data.Dataset):
def __init__(self, in_len, out_len, scaler_seq, scaler_label):
folder_path = "total1"
# folder_path = "/home/zzh/test_data"
excel_files = glob.glob(os.path.join(folder_path, '*.xlsx'), recursive=True)
all_train_seq, all_train_label = list(), list()
for file in excel_files:
workbook = openpyxl.load_workbook(file)
sheet = workbook.active
num_rows = sheet.max_row
start_index = int(num_rows * 0.15) + 1 # 因为openpyxl的行和列索引从1开始
end_index = int(num_rows * 0.95)
tarEli, tar_x, tar_y, tar_z, position_change = [], [], [], [], []
v,v_change,r,eli_change,h_change= [], [], [], [], []
for row in sheet.iter_rows(min_row=start_index, max_row=end_index, values_only=True):
tarEli.append(row[1])
tar_x.append(row[2])
tar_y.append(row[3])
tar_z.append(row[4])
position_change.append(row[5])
v.append(row[6])
v_change.append(row[7])
r.append(row[8])
eli_change.append(row[9])
h_change.append(row[10])
tarEli = pd.Series(tarEli)
tar_x = pd.Series(tar_x)
tar_y = pd.Series(tar_y)
tar_z = pd.Series(tar_z)
position_change = pd.Series(position_change)
v = pd.Series(v)
v_change = pd.Series(v_change)
r = pd.Series(r)
eli_change = pd.Series(eli_change)
h_change = pd.Series(h_change)
L = len(tarEli)
for i in range(0, L - in_len - out_len, 30):
data_tarEli = tarEli[i:i + in_len]
data_tar_x = tar_x[i:i + in_len]
data_tar_y = tar_y[i:i + in_len]
data_tar_z = tar_z[i:i + in_len]
data_position_change = position_change[i:i + in_len]
data_v = v[i:i + in_len]
data_v_change = v_change[i:i + in_len]
data_r = r[i:i + in_len]
data_eli_change = eli_change[i:i + in_len]
data_h_change = h_change[i:i + in_len]
train_seq = list(zip(data_tarEli,data_tar_x,data_tar_y,data_tar_z,data_position_change,data_v,data_v_change,data_r,data_eli_change,data_h_change))
tar_x_train_label = tar_x[i + in_len:i + in_len + out_len]
tar_y_train_label = tar_y[i + in_len:i + in_len + out_len]
tar_z_train_label = tar_z[i + in_len:i + in_len + out_len]
train_label = list(zip(tar_x_train_label,tar_y_train_label,tar_z_train_label))
all_train_seq.append(train_seq)
all_train_label.append(train_label)
# all_train_seq 是一个三维数组,shape为 (num_samples, num_rows, num_cols)
# 将所有训练数据拼接在一起
concatenated_data = np.concatenate(all_train_seq, axis=0) # 在第一个轴上进行拼接
normalized_data = scaler_seq.fit_transform(concatenated_data)
# 将归一化后的数据拆分回原来的样本
start_index = 0
self.normalized_all_seq = []
for train_data in all_train_seq:
num_samples = len(train_data)
end_index = start_index + num_samples
self.normalized_all_seq.append(normalized_data[start_index:end_index, :])
start_index = end_index
# 将归一化后的数据存储在一个新的数组中,形状与 all_train_data 相同
self.normalized_all_train_seq = np.array(self.normalized_all_seq)
concatenated_data = np.concatenate(all_train_label, axis=0) # 在第一个轴上进行拼接
normalized_data = scaler_label.fit_transform(concatenated_data)
# 将归一化后的数据拆分回原来的样本
start_index = 0
self.normalized_all_label = []
for train_label in all_train_label:
num_samples = len(train_label)
end_index = start_index + num_samples
self.normalized_all_label.append(normalized_data[start_index:end_index, :])
start_index = end_index
# 将归一化后的数据存储在一个新的数组中,形状与 all_train_data 相同
self.normalized_all_train_label = np.array(self.normalized_all_label)
def __getitem__(self, index):
input_data = self.normalized_all_train_seq[index]
target = self.normalized_all_train_label[index]
return input_data, target
def __len__(self):
return len(self.normalized_all_train_seq)
def evaluate(model, test_loader, device):
model.eval() # 设置模型为评估模式
total_loss = 0.0
with torch.no_grad(): # 在此模式下,所有计算都不会跟踪梯度
for inputs, labels in test_loader:
inputs, labels = inputs.to(torch.float32).to(device), labels.to(torch.float32).to(device)
y_pred,m,v,_ = model(inputs,labels)
y_pred_cpu = y_pred.cpu().detach().numpy()
y_pred = y_pred_cpu.reshape(-1, 3)
# print(y_pred.shape)
y_pred1 = scaler_label.inverse_transform(y_pred)
# print(y_pred.shape)
labels_cpu = labels.cpu().detach().numpy()
labels = labels_cpu.reshape(-1, 3)
# print(labels.shape)
labels1 = scaler_label.inverse_transform(labels)
# print(labels.shape)
# single_loss, single_real_loss = loss_func(y_pred, labels,m,v)
y_pred = torch.tensor(y_pred1)
#print(y_pred.shape)
labels = torch.tensor(labels1)
#print(labels.shape)
y_pred = y_pred.to(torch.float32).to(device)
labels = labels.to(torch.float32).to(device)
#print("逆归一化后的预测数据",y_pred)
#print("逆归一化后的原数据",labels)
loss =rmse_loss(y_pred,labels)
total_loss += loss.item()
return labels1, y_pred1, total_loss / len(test_loader)
if __name__ == '__main__':
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(device)
# 归一化
scaler_seq, scaler_label = MinMaxScaler(feature_range=(-1, 1)), MinMaxScaler(feature_range=(-1, 1))
datasets = Mydataset(200, 10, scaler_seq, scaler_label)
print(len(datasets))
test_size = int(len(datasets) * 0.3)
train_size = len(datasets) - test_size
train_dataset, test_dataset = data.random_split(datasets, [train_size, test_size])
print(type(train_dataset), len(train_dataset))
print(type(test_dataset), len(test_dataset))
batch_size = 16
train_dataloader = data.DataLoader(train_dataset, batch_size=batch_size, num_workers=2, shuffle=True)
test_dataloader = data.DataLoader(test_dataset, batch_size=batch_size, num_workers=1, shuffle=True)
model = GRU_attention().to(device)
print(model)
loss_function = nn.L1Loss()
# optimizer = torch.optim.Adam(model.parameters(), lr=0.00008)
optimizer = Ranger(model.parameters(), lr = 0.0002)
print(
"enhance data + GRU + CNN + LR = 0.0002 + MAEE + batch_size = 16 + in_len = 200 + out_len = 10 + ranger")
epochs = 1000
scaler2 = GradScaler()
for epoch in range(epochs):
model.train() # 确保模型处于训练模式
running_loss = 0.0
running_num = 0
for batch in train_dataloader:
inputs, labels = batch
inputs = inputs.to(torch.float16).to(device)
labels = labels.to(torch.float16).to(device)
optimizer.zero_grad()
with autocast():
y_pred,m,v,_ = model(inputs,labels)
single_loss = loss_function(y_pred, labels)
scaler2.scale(single_loss).backward()
scaler2.step(optimizer)
scaler2.update()
optimizer.zero_grad() # 重置梯度
running_loss += single_loss.item()
running_num += 1
if epoch % 10 == 0:
# 在每个epoch结束后计算平均训练损失
avg_train_loss = running_loss / running_num
print(f'Epoch {epoch+1}/{epochs}, Train Loss: {avg_train_loss:.8f}')
# if epoch % 100 == 0:
# 在每个epoch结束后在测试集上评估模型
labels1,y_pred1,test_loss = evaluate(model, test_dataloader, device)
# print("lables:",labels)
# print("y_pred:",y_pred)
print(f'Epoch {epoch+1}/{epochs}, Test Loss: {test_loss:.8f}')
#torch.save(model.state_dict(), 'model_CNN_GRU_CVAE.pt')
\ No newline at end of file
#include "GeodeticTool.h"
#include <Geodetics/GeodeticTransform.h>
#include <QtCore/QRegExp>
namespace F1911
{
GeodeticTool::GeodeticTool(QWidget* parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(ui.toLocalENUButton, &QPushButton::clicked, this, &GeodeticTool::toLocalENUButtonClick);
connect(ui.toGeodeticButton, &QPushButton::clicked, this, &GeodeticTool::toGeodeticButtonClick);
}
GeodeticTool::~GeodeticTool()
{
disconnect(ui.toGeodeticButton, &QPushButton::clicked, this, &GeodeticTool::toGeodeticButtonClick);
disconnect(ui.toLocalENUButton, &QPushButton::clicked, this, &GeodeticTool::toLocalENUButtonClick);
}
bool GeodeticTool::parseNumber(const QLineEdit* edit, double& value)
{
bool ok;
value = edit->text().toDouble(&ok);
return ok;
}
void GeodeticTool::setNumber(QLineEdit* edit, double value)
{
auto text = QString::number(value, 'f', 12);
text.remove(QRegExp("0+$")); // 移除所有尾部的“0”
text.remove(QRegExp("\\.$")); // 如果最后一个字符是“.”,移除它
edit->setText(text);
}
void GeodeticTool::toLocalENUButtonClick()
{
double longitude, latitude, altitude;
if (parseNumber(ui.longitudeEdit, longitude) &&
parseNumber(ui.latitudeEdit, latitude) &&
parseNumber(ui.altitudeEdit, altitude))
{
double east, north, up;
Geodetics::GeodeticTransform::get().geodeticToLocal(
east, north, up, longitude, latitude, altitude);
setNumber(ui.localEastEdit, east);
setNumber(ui.localNorthEdit, north);
setNumber(ui.localUpEdit, up);
}
}
void GeodeticTool::toGeodeticButtonClick()
{
double east, north, up;
if (parseNumber(ui.localEastEdit, east) &&
parseNumber(ui.localNorthEdit, north) &&
parseNumber(ui.localUpEdit, up))
{
double longitude, latitude, altitude;
Geodetics::GeodeticTransform::get().localToGeodetic(
longitude, latitude, altitude, east, north, up);
setNumber(ui.longitudeEdit, longitude);
setNumber(ui.latitudeEdit, latitude);
setNumber(ui.altitudeEdit, altitude);
}
}
}
set(CMAKE_INCLUDE_CURRENT_DIR ON)
file(GLOB_RECURSE SOURCES src/*.cpp src/*.h)
file(GLOB_RECURSE HEADERS include/*.h)
add_library(Geodetics SHARED ${SOURCES} ${HEADERS})
target_include_directories(Geodetics
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${GDAL_ROOT}
)
target_compile_definitions(Geodetics PRIVATE GEODETICS_LIB)
target_link_directories(Geodetics PRIVATE ${GDAL_ROOT}/lib/${BUILD_TYPE})
target_link_libraries(Geodetics PRIVATE ${GDAL_LIB_NAME}.lib)
add_custom_command(TARGET Geodetics POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:Geodetics> ${CLIENTS_BIN_DIR}
#COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_PDB_FILE:Geodetics> ${CLIENTS_BIN_DIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_LINKER_FILE:Geodetics> ${CLIENTS_LIB_DIR}
)
install(TARGETS Geodetics RUNTIME DESTINATION "Geodetics/${CMAKE_INSTALL_BINDIR}")
install(FILES ${GDAL_ROOT}/lib/${BUILD_TYPE}/gdal17.dll DESTINATION "Geodetics/${CMAKE_INSTALL_BINDIR}")
install(FILES ${GDAL_ROOT}/lib/${BUILD_TYPE}/proj.dll DESTINATION "Geodetics/${CMAKE_INSTALL_BINDIR}")
install(TARGETS Geodetics LIBRARY DESTINATION "Geodetics/${CMAKE_INSTALL_LIBDIR}")
install(DIRECTORY include DESTINATION "Geodetics")
#pragma once
#include "GeodeticsBase.h"
namespace F1911::Geodetics
{
class GeodeticTransformInternal;
class GEODETICS_API GeodeticTransform final
{
// Instance ----------------------------------------------------------------------------------------------------
public:
static GeodeticTransform& get()
{
static GeodeticTransform t;
return t;
}
GeodeticTransform(const GeodeticTransform& other) = delete;
GeodeticTransform& operator=(const GeodeticTransform& other) = delete;
GeodeticTransform(GeodeticTransform&& other) = delete;
GeodeticTransform& operator=(GeodeticTransform&& other) = delete;
private:
GeodeticTransform();
~GeodeticTransform();
GeodeticTransformInternal* _i;
// Transforms --------------------------------------------------------------------------------------------------
public:
double eastOffset = -643615.753, northOffset = -4400490.578, upOffset = 50;
bool localToGeodetic(double& longitude, double& latitude,
double& altitude, double east, double north, double up) const;
bool geodeticToLocal(double& east, double& north, double& up,
double longitude, double latitude, double altitude) const;
};
}
#pragma once
#if defined(GEODETICS_LIB)
# define GEODETICS_API __declspec(dllexport)
#else
# define GEODETICS_API __declspec(dllimport)
#endif
#include "Geodetics/GeodeticTransform.h"
#include <string> // 如果不在gdal库之前包含此头文件则gdal库会出现编译错误。
#include <gdal/ogr_spatialref.h>
#include <gdal/ogrsf_frmts.h>
#include <gdal/gdal_alg.h>
namespace F1911::Geodetics
{
const char* const WGS84_WKT(
"GEOGCS[\"Geographic Coordinate System\",DATUM[\"D_WGS84\",\
SPHEROID[\"WGS84\",6378137,298.257223560493]],PRIMEM[\"Greenwich\",0],\
UNIT[\"Degree\",0.017453292519943295]]");
const char* const XIAN80_WKT(
"PROJCS[\"UTM_Zone_51_Northern_Hemisphere\",GEOGCS[\"GCS_XIAN 1980\",\
DATUM[\"D_XIAN 1980\",SPHEROID[\"Xian_1980\",6378140,298.2569978029111]],\
PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],\
PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],\
PARAMETER[\"central_meridian\",123],PARAMETER[\"scale_factor\",0.9996],\
PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]");
class GeodeticTransformInternal final
{
public:
GeodeticTransformInternal()
{
OGRRegisterAll();
wgs84Reference = OGRSpatialReference(WGS84_WKT);
xianReference = OGRSpatialReference(XIAN80_WKT);
localToGeodetic = OGRCreateCoordinateTransformation(&xianReference, &wgs84Reference);
geodeticToLocal = OGRCreateCoordinateTransformation(&wgs84Reference, &xianReference);
}
~GeodeticTransformInternal()
{
OGRCoordinateTransformation::DestroyCT(geodeticToLocal);
OGRCoordinateTransformation::DestroyCT(localToGeodetic);
OGRCleanupAll();
}
OGRSpatialReference xianReference;
OGRSpatialReference wgs84Reference;
OGRCoordinateTransformation* geodeticToLocal = nullptr;
OGRCoordinateTransformation* localToGeodetic = nullptr;
};
GeodeticTransform::GeodeticTransform()
{
_i = new GeodeticTransformInternal();
}
GeodeticTransform::~GeodeticTransform()
{
delete _i;
_i = nullptr;
}
bool GeodeticTransform::localToGeodetic(
double& longitude, double& latitude, double& altitude, double east, double north, double up) const
{
longitude = east - eastOffset;
latitude = north - northOffset;
altitude = up - upOffset;
return _i->localToGeodetic->Transform(1, &longitude, &latitude, &altitude);
}
bool GeodeticTransform::geodeticToLocal(
double& east, double& north, double& up, double longitude, double latitude, double altitude) const
{
east = longitude;
north = latitude;
up = altitude;
auto ret = _i->geodeticToLocal->Transform(1, &east, &north, &up);
east += eastOffset;
north += northOffset;
up += upOffset;
return ret;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<id>1</id>
<title>Python for beginners</title>
<author>Lisa Smith</author>
<price>19.99</price>
<devices>
<tracks>
<track>
<id>12</id>
<ord>1</ord>
<tarRng>66096.3437111</tarRng>
<tarAzi>0.471221</tarAzi>
<tarEli>-0.012623</tarEli>
</track>
<track>
<id>13</id>
<ord>1</ord>
<tarRng>66096.343750</tarRng>
<tarAzi>0.471221</tarAzi>
<tarEli>-0.012623</tarEli>
</track>
</tracks>
</devices>
</book>
<book>
<id>2</id>
<title>Python tips and tricks</title>
<author>Joel Williams</author>
<price>24.99</price>
<devices>
<tracks>
<track>
<id>14</id>
<ord>1</ord>
<tarRng>66096.3437222</tarRng>
<tarAzi>0.471221</tarAzi>
<tarEli>-0.012623</tarEli>
</track>
<track>
<id>15</id>
<ord>1</ord>
<tarRng>6609</tarRng>
<tarAzi>0.471221</tarAzi>
<tarEli>-0.012623</tarEli>
</track>
</tracks>
</devices>
</book>
</books>
\ No newline at end of file
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from tqdm import tqdm
import tensorflow as tf
import os
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_all=pd.DataFrame()
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# print(file_path)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data_all = pd.concat([data_all, data], axis=0, ignore_index=True) # 将文件内容合并到data_all中
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
dataset=data_all.values
scaler.fit(dataset) ## 生成规则
dataset = scaler.transform(dataset) ## 将规则应用于训练集
import numpy as np
def trajectory_split(data,window,offset):
child_trajectory= []
tr1=[]
for i in range(0,len(data)-window-1,offset):
if (i + window)<len(data) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
if id1==id2 and id1==0:
tr1.append(dataset[i:(i+window),:])
if id1==id2:
a = dataset[i:(i+window),:-1]
# a = dataset[i:(i+window),1:4]
child_trajectory.append(a)
return np.array(child_trajectory),np.array(tr1)
trajectorys,tr1=trajectory_split(dataset,300,300)
print(trajectorys.shape)
# In[8]:
def cal_fd(l1,l2):
dis=l1-l2
dis_abs=np.abs(dis)
mean = dis_abs.mean(axis=0) # 计算完之后array的长度等于列数
return sum(mean)/len(mean)
# In[10]:
def cal_fd_full(trajectorys):
fd=np.zeros((len(trajectorys), len(trajectorys)))
for i in range(len(trajectorys)):
for j in range(i+1,len(trajectorys)):
x=trajectorys[i]
y=trajectorys[j]
fd[i][j]=cal_fd(x,y)
fd_full=np.zeros((len(trajectorys), len(trajectorys)))
for i in range(len(trajectorys)):
for j in range(len(trajectorys)):
if i==j:
fd_full[i][j]=0
elif i<j:
fd_full[i][j]=fd[i][j]
else:
fd_full[i][j]=fd[j][i]
return fd_full
def get_center(cluster):
if len(cluster)<=2:
return cluster[0]
fd=cal_fd_full(cluster)
dis=np.sum(fd,axis=0)
min_index = np.argmin(dis)
return cluster[min_index]
def get_all_center(clusters):
centers=[]
for i in range(len(clusters)):
center=get_center(clusters[i])
centers.append(center)
return centers
#n1,n2为轨迹簇中轨迹的数目
def cal_ward(n1,n2,center1,center2):
fd=cal_fd(center1,center2)
ward=n1*n2*fd/(n1+n2)
return ward
def cal_all_ward(clusters,centers):
ward_arr=np.zeros((len(clusters), len(clusters)))
for i in range(len(clusters)):
for j in range(i+1,len(clusters)):
ward_arr[i][j]=cal_ward(len(clusters[i]),len(clusters[j]),centers[i],centers[j])
ward_arr_full=np.zeros((len(clusters), len(clusters)))
for i in range(len(ward_arr)):
for j in range(len(ward_arr)):
if i>=j:
ward_arr_full[i][j]=float('inf')
else:
ward_arr_full[i][j]=ward_arr[i][j]
return ward_arr_full
# In[ ]:
def clustering(trajectorys,k):
clusters = [[point] for point in trajectorys]
count=len(clusters)
print(count)
index=0
dis_arr=[]
d_arr=[]
while len(clusters)>k:
#计算每个簇的中心轨迹
if count==len(clusters):
centers=[point for point in trajectorys]
else:
centers=get_all_center(clusters)
#计算每个轨迹簇的ward距离
ward_all=cal_all_ward(clusters,centers)
#合并ward距离最小的两个轨迹簇,使轨迹簇的数目减一
min_index = np.unravel_index(np.argmin(ward_all), ward_all.shape)
min_dis=ward_all[min_index[0]][[min_index[1]]]
# print(min_dis)
if index==0:
dis=min_dis[0]
index+=1
d=min_dis[0]-dis
print(d)
dis_arr.append(min_dis[0])
d_arr.append(d)
dis=min_dis[0]
clusters[min_index[0]].extend(clusters[min_index[1]])
clusters.pop(min_index[1])
return clusters,dis_arr,d_arr
clusters,dis_arr,d_arr=clustering(trajectorys,6599)
for cluster in clusters:
print(len(clusters))
# In[ ]:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from tqdm import tqdm
import os
import numpy as np
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
data_train,data_test
# In[28]:
from sklearn.preprocessing import MinMaxScaler
train=data_train.values
test=data_test.values
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
data_tr,data_te
# In[33]:
# combined_array = np.vstack((train, test))
combined_array = np.vstack((data_tr, data_te))
dataset1=combined_array[:, :3]
dataset1.shape
# In[34]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import calinski_harabasz_score
from sklearn.metrics import davies_bouldin_score
def k_means_cluster(k,data):
X = data
# X, _ = make_blobs(n_samples=300, centers=4, random_state=42, n_features=3)
# X.shape
#使用 k均值算法进行聚类
kmeans = KMeans(n_clusters=k, random_state=42)
kmeans.fit(X)
# 获取聚类结果和中心点
labels = kmeans.labels_
centers = kmeans.cluster_centers_
db_index_1 = davies_bouldin_score(X, labels)
print("Davies-Bouldin Index for Clustering 1:", db_index_1)
print(centers)
return centers,labels
# 可视化聚类结果
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=labels,cmap='viridis', s=2, marker='.')
# # ax.scatter(centers[:, 0], centers[:, 1], centers[:, 2], c='red', marker='X', s=200, label='Cluster Centers')
# ax.set_title('K-Means Clustering of 3D Trajectory Points')
# ax.set_xlabel('X-axis')
# ax.set_ylabel('Y-axis')
# ax.set_zlabel('Z-axis')
# plt.legend()
# plt.show()
centers,labels=k_means_cluster(2,dataset1)
centers
# In[39]:
len(labels)
#给数据集加上labels
new_col=labels[:, np.newaxis]
dataset2=np.hstack((combined_array, new_col))
dataset3=np.copy(dataset2)
dataset3[:, -1], dataset3[:, -2] = dataset2[:, -2], dataset2[:, -1]
#拆分数组变成加了标签的训练和测试集
train_new = dataset3[:1844129, :]
test_new = dataset3[1844129:, :]
train_new.shape,test_new.shape
# In[41]:
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
# In[44]:
# train_X,train_Y=create_dataset(data_tr,200,100,100)
# test_X,test_Y=create_dataset(data_te,200,100,100)
train_X,train_Y=create_dataset(train_new,200,100,100)
test_X,test_Y=create_dataset(test_new,200,100,100)
train_X.shape,train_Y.shape,test_X.shape,test_Y.shape
# In[ ]:
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
import time
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(70, input_shape=(200, 12))) # LSTM层
# model.add(LSTM(units=100)) # LSTM层,50个神经元
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
model.add(Dense(300,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.2))
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_absolute_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=300, batch_size=72, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/lstm_model_feature2.h5')
# tf.keras.backend.clear_session()
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
import os
from tqdm import tqdm
#只用特征来聚类,按照每条轨迹之间的距离来聚类
folder_path = "E:/replay/1对1/process_data/5" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_all=pd.DataFrame()
dataY_all=[]
count=0
index="5."
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
if count>30:
break
count+=1
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[2:,9:]
data['id']=index+str(count)
data_all = pd.concat([data_all, data], axis=0, ignore_index=True) # 将文件内容合并到data_all中
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
dataset=data_all.values
scaler.fit(dataset) ## 生成规则
dataset = scaler.transform(dataset) ## 将规则应用于训练集
import numpy as np
def trajectory_split(data,window,offset):
child_trajectory= []
for i in range(0,len(data)-window-1,offset):
if (i + window)<len(data) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
if id1==id2:
a = dataset[i:(i+window),:-1]
# a = dataset[i:(i+window),1:4]
child_trajectory.append(a)
return np.array(child_trajectory)
trajectorys=trajectory_split(dataset,200,200)
def cal_fd(l1,l2):
dis=l1-l2
dis_abs=np.abs(dis)
mean = dis_abs.mean(axis=0) # 计算完之后array的长度等于列数
return sum(mean)/len(mean)
m=cal_fd(trajectorys[0],trajectorys[1])
def cal_fd_full(trajectorys):
fd=np.zeros((len(trajectorys), len(trajectorys)))
for i in range(len(trajectorys)):
for j in range(i+1,len(trajectorys)):
x=trajectorys[i]
y=trajectorys[j]
fd[i][j]=cal_fd(x,y)
fd_full=np.zeros((len(trajectorys), len(trajectorys)))
for i in range(len(trajectorys)):
for j in range(len(trajectorys)):
if i==j:
fd_full[i][j]=0
elif i<j:
fd_full[i][j]=fd[i][j]
else:
fd_full[i][j]=fd[j][i]
return fd_full
fd_full=cal_fd_full(trajectorys)
dis=np.sum(fd_full,axis=1)
def get_center(cluster):
if len(cluster)<=2:
return cluster[0]
fd=cal_fd_full(cluster)
dis=np.sum(fd,axis=0)
min_index = np.argmin(dis)
return cluster[min_index]
def get_all_center(clusters):
centers=[]
for i in range(len(clusters)):
center=get_center(clusters[i])
centers.append(center)
return centers
#n1,n2为轨迹簇中轨迹的数目
def cal_ward(n1,n2,center1,center2):
fd=cal_fd(center1,center2)
ward=n1*n2*fd/(n1+n2)
return ward
def cal_all_ward(clusters,centers):
ward_arr=np.zeros((len(clusters), len(clusters)))
for i in range(len(clusters)):
for j in range(i+1,len(clusters)):
ward_arr[i][j]=cal_ward(len(clusters[i]),len(clusters[j]),centers[i],centers[j])
ward_arr_full=np.zeros((len(clusters), len(clusters)))
for i in range(len(ward_arr)):
for j in range(len(ward_arr)):
if i>=j:
ward_arr_full[i][j]=float('inf')
else:
ward_arr_full[i][j]=ward_arr[i][j]
return ward_arr_full
# arr = np.array([[3, 1, 4], [1, 5, 9], [2, 6, 5]])
# min_index = np.unravel_index(np.argmin(arr), arr.shape)
def clustering(trajectorys,k):
clusters = [[point] for point in trajectorys]
count=len(clusters)
index=0
while len(clusters)>k:
#计算每个簇的中心轨迹
if count==len(clusters):
centers=[point for point in trajectorys]
else:
centers=get_all_center(clusters)
#计算每个轨迹簇的ward距离
ward_all=cal_all_ward(clusters,centers)
#合并ward距离最小的两个轨迹簇,使轨迹簇的数目减一
min_index = np.unravel_index(np.argmin(ward_all), ward_all.shape)
min_dis=ward_all[min_index[0]][[min_index[1]]]
print(min_dis)
if index==0:
dis=min_dis[0]
index+=1
d=dis-min_dis
if d>0.1:
break
dis=min_dis[0]
clusters[min_index[0]].extend(clusters[min_index[1]])
clusters.pop(min_index[1])
# print(len(clusters))
return clusters
clusters=clustering(trajectorys,5)
print(len(clusters))
import matplotlib.pyplot as plt
# 画出真实数据和预测数据
fig = plt.figure()
ax = fig.gca(projection='3d')
for k in range(len(clusters)):
x, y, z = [], [], []
for i in range(len(clusters[k])):
for j in range(len(clusters[k][i])):
x.append(clusters[k][i][j][1])
y.append(clusters[k][i][j][2])
z.append(clusters[k][i][j][3])
label = "cluster" + str(k)
ax.scatter(x, y, z, s=2, label=label)
plt.legend()
fig2 = plt.figure()
ax2 = fig2.gca(projection='3d')
x2,y2,z2=[],[],[]
for k in range(len(trajectorys)):
for i in range(len(trajectorys[k])):
x2.append(trajectorys[k][i][1])
y2.append(trajectorys[k][i][2])
z2.append(trajectorys[k][i][3])
ax2.scatter(x2, y2, z2, s=2)
plt.show()
\ No newline at end of file
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
import os
from tqdm import tqdm
#只用特征来聚类,按照每条轨迹之间的距离来聚类
folder_path = "/home/lxm/dataset/1vs1/5" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_all=pd.DataFrame()
dataY_all=[]
count=0
index="5."
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
if count>30:
break
count+=1
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[2:,9:]
data['id']=index+str(count)
data_all = pd.concat([data_all, data], axis=0, ignore_index=True) # 将文件内容合并到data_all中
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
dataset=data_all.values
scaler.fit(dataset) ## 生成规则
dataset = scaler.transform(dataset) ## 将规则应用于训练集
import numpy as np
def trajectory_split(data,window,offset):
child_trajectory= []
tr1=[]
for i in range(0,len(data)-window-1,offset):
if (i + window)<len(data) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
if id1==id2 and id1==0:
tr1.append(dataset[i:(i+window),:])
if id1==id2:
a = dataset[i:(i+window),:-1]
# a = dataset[i:(i+window),1:4]
child_trajectory.append(a)
return np.array(child_trajectory),np.array(tr1)
trajectorys,tr1=trajectory_split(dataset,200,200)
def cal_fd(l1,l2):
dis=l1-l2
dis_abs=np.abs(dis)
mean = dis_abs.mean(axis=0) # 计算完之后array的长度等于列数
return sum(mean)/len(mean)
m=cal_fd(trajectorys[0],trajectorys[1])
def cal_fd_full(trajectorys):
fd=np.zeros((len(trajectorys), len(trajectorys)))
for i in range(len(trajectorys)):
for j in range(i+1,len(trajectorys)):
x=trajectorys[i]
y=trajectorys[j]
fd[i][j]=cal_fd(x,y)
fd_full=np.zeros((len(trajectorys), len(trajectorys)))
for i in range(len(trajectorys)):
for j in range(len(trajectorys)):
if i==j:
fd_full[i][j]=0
elif i<j:
fd_full[i][j]=fd[i][j]
else:
fd_full[i][j]=fd[j][i]
return fd_full
fd_full=cal_fd_full(trajectorys)
dis=np.sum(fd_full,axis=1)
def get_center(cluster):
if len(cluster)<=2:
return cluster[0]
fd=cal_fd_full(cluster)
dis=np.sum(fd,axis=0)
min_index = np.argmin(dis)
return cluster[min_index]
def get_all_center(clusters):
centers=[]
for i in range(len(clusters)):
center=get_center(clusters[i])
centers.append(center)
return centers
#n1,n2为轨迹簇中轨迹的数目
def cal_ward(n1,n2,center1,center2):
fd=cal_fd(center1,center2)
ward=n1*n2*fd/(n1+n2)
return ward
def cal_all_ward(clusters,centers):
ward_arr=np.zeros((len(clusters), len(clusters)))
for i in range(len(clusters)):
for j in range(i+1,len(clusters)):
ward_arr[i][j]=cal_ward(len(clusters[i]),len(clusters[j]),centers[i],centers[j])
ward_arr_full=np.zeros((len(clusters), len(clusters)))
for i in range(len(ward_arr)):
for j in range(len(ward_arr)):
if i>=j:
ward_arr_full[i][j]=float('inf')
else:
ward_arr_full[i][j]=ward_arr[i][j]
return ward_arr_full
def clustering(trajectorys,k):
clusters = [[point] for point in trajectorys]
count=len(clusters)
index=0
dis_arr=[]
d_arr=[]
while len(clusters)>k:
#计算每个簇的中心轨迹
if count==len(clusters):
centers=[point for point in trajectorys]
else:
centers=get_all_center(clusters)
#计算每个轨迹簇的ward距离
ward_all=cal_all_ward(clusters,centers)
#合并ward距离最小的两个轨迹簇,使轨迹簇的数目减一
min_index = np.unravel_index(np.argmin(ward_all), ward_all.shape)
min_dis=ward_all[min_index[0]][[min_index[1]]]
# print(min_dis)
if index==0:
dis=min_dis[0]
index+=1
d=min_dis[0]-dis
print(d)
dis_arr.append(min_dis[0])
d_arr.append(d)
dis=min_dis[0]
clusters[min_index[0]].extend(clusters[min_index[1]])
clusters.pop(min_index[1])
return clusters,dis_arr,d_arr
# clusters_,dis_arr,d_arr=clustering(trajectorys,1)
# len(clusters_)
#
# import matplotlib.pyplot as plt
# l=[i+1 for i in range(len(dis_arr))]
# l.reverse()
# plt.plot(l, dis_arr, marker='.', linestyle='-', label='Line 1')
# # 设置 x 轴刻度间隔为 5
# plt.xticks(np.arange(0, 330, 20))
# plt.xlabel('Cluster Num')
# plt.ylabel('Minimum Ward Distance')
# plt.show()
def adaptive_clustering(trajectorys):
clusters = [[point] for point in trajectorys]
count=len(clusters)
index=0
while len(clusters)>1:
#计算每个簇的中心轨迹
if count==len(clusters):
centers=[point for point in trajectorys]
else:
centers=get_all_center(clusters)
#计算每个轨迹簇的ward距离
ward_all=cal_all_ward(clusters,centers)
#合并ward距离最小的两个轨迹簇,使轨迹簇的数目减一
min_index = np.unravel_index(np.argmin(ward_all), ward_all.shape)
min_dis=ward_all[min_index[0]][[min_index[1]]]
# print(min_dis)
if index==0:
dis=min_dis[0]
index+=1
d=min_dis[0]-dis
print(d)
if d>0.1:
break
dis=min_dis[0]
clusters[min_index[0]].extend(clusters[min_index[1]])
clusters.pop(min_index[1])
return clusters
clusters=adaptive_clustering(trajectorys)
import matplotlib.pyplot as plt
#画出真实数据和预测数据
fig = plt.figure()
ax = fig.gca(projection='3d')
for k in range(len(clusters)):
x,y,z=[],[],[]
for i in range(len(clusters[k])):
for j in range(len(clusters[k][i])):
x.append(clusters[k][i][j][1])
y.append(clusters[k][i][j][2])
z.append(clusters[k][i][j][3])
label="cluster"+str(k)
ax.scatter(x, y, z, s=2,label=label)
plt.legend()
plt.show()
fig2 = plt.figure()
ax2 = fig2.gca(projection='3d')
x2,y2,z2=[],[],[]
for k in range(len(trajectorys)):
for i in range(len(trajectorys[k])):
x2.append(trajectorys[k][i][1])
y2.append(trajectorys[k][i][2])
z2.append(trajectorys[k][i][3])
ax2.scatter(x2, y2, z2, s=2)
plt.show()
from tqdm import tqdm
import concurrent.futures
import math
import os
from csv import reader
import pandas as pd
import position_transfer
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
def process(file_path,file_name):
filename = file_name.split(".")[0]
print(filename)
df = pd.read_csv(file_path)
for index,row in df.iterrows():
position_change=row['position_change']
if position_change==0:
if index < len(df) - 1 and index>=1:
df.loc[index,'tar_x']=(df.loc[index+1,'tar_x']+df.loc[index-1,'tar_x'])/2
df.loc[index, 'position_change'] = (df.loc[index + 1, 'position_change'] + df.loc[
index - 1, 'position_change']) / 2
df.loc[index, 'tar_y'] = (df.loc[index + 1, 'tar_y'] + df.loc[index - 1, 'tar_y']) / 2
df.loc[index, 'tar_z'] = (df.loc[index + 1, 'tar_z'] + df.loc[index - 1, 'tar_z']) / 2
df.loc[index, 'v'] = (df.loc[index + 1, 'v'] + df.loc[index - 1, 'v']) / 2
df.loc[index, 'v_change'] = (df.loc[index + 1, 'v_change'] + df.loc[index - 1, 'v_change']) / 2
df.loc[index, 'r'] = (df.loc[index + 1, 'r'] + df.loc[index - 1, 'r']) / 2
df.loc[index, 'eli_change'] = (df.loc[index + 1, 'eli_change'] + df.loc[index - 1, 'eli_change']) / 2
df.loc[index, 'h_change'] = (df.loc[index + 1, 'h_change'] + df.loc[index - 1, 'h_change']) / 2
else:
df = df.drop(index)
df.to_csv('E:/replay/1对1/process_data/5/'+filename+'.csv', index=False)
return filename + 'finish'
def processFiles():
folder_path = "E:/replay/1对1/data/5" # 替换为你的文件夹路径
# folder_path = "E:/replay/demo"
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
results = []
count = 1
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# 解析XML文件
result = executor.submit(process, file_path, file_name)
results.append(result)
for future in concurrent.futures.as_completed(results):
print(count)
print(future.result())
count += 1
##数据预处理 load dataset,需要处理0值,0值为异常值,
def data_preprocess():
folder_path = "E:/replay/1对1/process_data/1" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
results = []
count = 1
data_all = pd.DataFrame()
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df_temp = pd.read_csv(file_path) # 读取csv文件到dataframe中
df_temp = df_temp.iloc[2:, :] # 不要前两行
data_all = pd.concat([data_all, df_temp], axis=0, ignore_index=True) # 将文件内容合并到data_all中
if __name__ == '__main__':
folder_path = "E:/replay/1对1/data/1/"
file_path=folder_path + "default - 20230601-133944.csv"
# process(file_path,"default - 20230601-133944.csv")
processFiles()
# df = pd.read_csv(file_path)
# df = df[['number', 'longitude', 'latitude', 'altitude', 'yaw', 'pitch', 'roll',
# 'tarRng', 'tarAzi', 'tarEli','tar_x','tar_y','tar_z','position_change','v',
# 'v_change','r','eli_change','h_change']]
# df.to_csv(file_path, index=False)
# process(file_path1,file_name1)
# cal_features(file_path, file_name)
# processFiles()
# cal_features_for_files()
# change_colum_for_files()
# 显示图形
# plt.show()
import xml.etree.ElementTree as ET
import os
import pandas as pd
from tqdm import tqdm
# folder_path = "E:/" # 替换为你的文件夹路径
#
# # 获取文件夹中的所有文件
# file_list = os.listdir(folder_path)
tree = ET.parse('book.xml')
#我们使用tree.getroot()将解析器中的根元素提取出来,并将其存储在命名为“root”的变量中。
root = tree.getroot()
#我们创建了一个空的DataFrame,包含四个列:id、title、author和price。
df = pd.DataFrame(columns=['id', 'title', 'author', 'price'])
# for file_name in file_list:
# if file_name.endswith(".xml"):
# file_path = os.path.join(folder_path, file_name)
#
# # 解析XML文件
# tree = ET.parse(file_path)
# root = tree.getroot()
for book in root:
if book.tag=='book':
id = book.find('id').text
title = book.find('title').text
author = book.find('author').text
price = book.find('price').text
devices=book.find('devices')
tracks=devices.find('tracks')
print(devices)
print(tracks)
track=tracks.find('track')
tarRng=track.find('tarRng').text
df = df.append(pd.Series([id, title, author, price,tarRng], index=['id', 'title', 'author', 'price','tarRng']), ignore_index=True)
# for book in root.findall("book"):
# id = book.find('id').text
# title = book.find('title').text
# author = book.find('author').text
# price = book.find('price').text
# df = df.append(pd.Series([id, title, author, price], index=['id', 'title', 'author', 'price']), ignore_index=True)
# df.to_excel('books.xlsx', index=False)
filename="default - 20230601-133944.replay"
filename=filename.split(".")[0]
print(filename)
\ No newline at end of file
import os
import xml.etree.ElementTree as ET
import pandas as pd
folder_path = "C:/xxx/Desktop/2022" # 替换为你的文件夹路径
# 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
# 创建一个空的DataFrame来存储所有XML文件的数据
all_data = pd.DataFrame()
# 循环处理每个文件
for file_name in file_list:
if file_name.endswith(".xml"):
file_path = os.path.join(folder_path, file_name)
# 解析XML文件
tree = ET.parse(file_path)
root = tree.getroot()
# 提取XML数据并转换为DataFrame
xml_data = {}
for element in root.iter():
xml_data[element.tag] = element.text
df = pd.DataFrame(xml_data, index=[0])
# 将DataFrame添加到总的数据集中
all_data = pd.concat([all_data, df], ignore_index=True)
# 将数据保存为Excel文件
excel_file_path = "C:/xxx/Desktop/2022/file.xlsx" # 替换为你的输出文件路径,如:/path/to/output/file.xlsx
all_data.to_excel(excel_file_path, index=False)
print("转换完成!Excel文件已保存。")
\ No newline at end of file
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
# In[33]:
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
train_X,train_Y=create_dataset(data_tr,200,100,100)
test_X,test_Y=create_dataset(data_te,200,100,100)
# In[70]:
from keras.models import load_model
# load model from single file
model1 = load_model('/home/lxm/model/lstm_model3.h5')
yhat = model1.predict(test_X)
# In[83]:
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error
temp = test_X.reshape(test_X.shape[0]*test_X.shape[1], test_X.shape[2])
temp=temp[:373700,2:]
iny_yhat=yhat.reshape(yhat.shape[0]*yhat.shape[1],yhat.shape[2])
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp), axis=1)
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(int(inv_y.shape[0]/100),100,3)
#真实数据
tempy=test_Y.reshape(test_Y.shape[0]*test_Y.shape[1], test_Y.shape[2])
iny_temp= concatenate((tempy, temp), axis=1)#水平方向合并,为了适配scaler
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:,0:3]
iny_real_reshape=iny_real.reshape(int(iny_real.shape[0]/100),100,3)
# # # calculate RMSE
rmse = sqrt(mean_squared_error(iny_real_reshape[3],inv_y_reshape[3]))
print('Test RMSE: %.3f' % rmse)
# In[78]:
import matplotlib.pyplot as plt
#画出真实数据和预测数据
predict_x,predict_y,predict_z=[],[],[]
true_x,true_y,true_z=[],[],[]
for i in range(len(inv_y_reshape[1])):
predict_x.append(inv_y_reshape[1][i][0])
predict_y.append(inv_y_reshape[1][i][1])
predict_z.append(inv_y_reshape[1][i][2])
true_x.append(iny_real_reshape[1][i][0])
true_y.append(iny_real_reshape[1][i][1])
true_z.append(iny_real_reshape[1][i][2])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(true_x, true_y, true_z, s=2,label='true')
ax.scatter(predict_x, predict_y, predict_z, s=2,label='prediction')
plt.legend()
plt.show()
# In[80]:
# In[ ]:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
data_train.shape,data_test.shape
# In[2]:
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
def create_dataset1(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),:-1])
return np.array(dataX), np.array(dataY)
def create_dataset2(dataset,window,offset,predict_length):
dataX, dataY = [], []
placeholder=[]
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),0:3]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
placeholder.append(dataset[i + window:(i + window+predict_length),3:])
return np.array(dataX), np.array(dataY),np.array(placeholder)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
data_tr,data_te
train_X,train_Y=create_dataset(data_tr,200,100,100)
test_X,test_Y=create_dataset(data_te,200,100,100)
train_X1,train_Y1=create_dataset1(data_tr,200,100,100)
test_X1,test_Y1=create_dataset1(data_te,200,100,100)
train_X2,train_Y2,p=create_dataset2(data_tr,200,100,100)
test_X2,test_Y2,placeholder=create_dataset2(data_te,200,100,100)
train_X2.shape,train_Y2.shape,test_X2.shape,test_Y2.shape
# In[69]:
from keras.models import load_model
# load model from single file
model1 = load_model('/home/lxm/model/lstm_model3.h5')
yhat = model1.predict(test_X)
# In[132]:
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error,mean_absolute_error
def reverse(yhat,test_X,test_Y):
temp = test_X.reshape(test_X.shape[0]*test_X.shape[1], test_X.shape[2])
temp=temp[:373700,2:]
iny_yhat=yhat.reshape(yhat.shape[0]*yhat.shape[1],yhat.shape[2])
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp), axis=1)
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(int(inv_y.shape[0]/100),100,3)
inv_y_reshape.shape
#真实数据
tempy=test_Y.reshape(test_Y.shape[0]*test_Y.shape[1], test_Y.shape[2])
iny_temp= concatenate((tempy, temp), axis=1)#水平方向合并,为了适配scaler
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:,0:3]
iny_real_reshape=iny_real.reshape(int(iny_real.shape[0]/100),100,3)
iny_real_reshape
# # # calculate RMSE
mae = sqrt(mean_absolute_error(iny_real,inv_y))
print('Test mae: %.3f' % mae)
return inv_y_reshape,iny_real_reshape
inv_y_reshape,iny_real_reshape=reverse(yhat,test_X,test_Y)
# In[3]:
#连续预测
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error,mean_absolute_error
from keras.models import load_model
model=load_model('/home/lxm/model/lstm_model4.h5')
model2 = load_model('/home/lxm/model/lstm_model_compare1.h5')
predict=model.predict(test_X1)
# predict.shape
predict2=model2.predict(test_X2)
predict2.shape
# In[4]:
def reverse2(predict,test_X1,test_Y1,text_X):
temp = test_X.reshape(test_X.shape[0]*test_X.shape[1], test_X.shape[2])
length=len(predict)
temp1=temp[:length*100,2:]
temp2=temp[:3737*100,2:]
iny_yhat=predict.reshape(predict.shape[0]*predict.shape[1],predict.shape[2])
print(iny_yhat.shape)
print(temp1.shape)
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp1), axis=1)
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(length,100,3)
inv_y_reshape.shape
#真实数据
tempy=test_Y.reshape(test_Y.shape[0]*test_Y.shape[1], test_Y.shape[2])
iny_temp= concatenate((tempy, temp2), axis=1)
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:(length)*100,0:3]
iny_real_reshape=iny_real.reshape(length,100,3)
print(iny_real_reshape.shape)
# # # calculate RMSE
mae = sqrt(mean_absolute_error(iny_real,inv_y))
print('Test MAE: %.3f' % mae)
return inv_y_reshape,iny_real_reshape
inv_y_reshape3,iny_real_reshape3=reverse2(predict2,test_X2,test_Y2,test_X)
# In[87]:
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error,mean_absolute_error
temp = test_X1.reshape(test_X1.shape[0]*test_X1.shape[1], test_X1.shape[2])
temp1=temp[:373700,-1:]
temp2=temp[:373700,2:]
iny_yhat=predict.reshape(predict.shape[0]*predict.shape[1],predict.shape[2])
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp1), axis=1)
iny.shape
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(int(inv_y.shape[0]/100),100,3)
inv_y_reshape.shape
#真实数据
tempy=test_Y1.reshape(test_Y1.shape[0]*test_Y1.shape[1], test_Y1.shape[2])
iny_temp= concatenate((tempy, temp1), axis=1)#水平方向合并,为了适配scaler
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:,0:3]
iny_real_reshape=iny_real.reshape(int(iny_real.shape[0]/100),100,3)
iny_real_reshape
# # # calculate RMSE
mae = sqrt(mean_absolute_error(iny_real,inv_y))
print('Test mae: %.3f' % mae)
# In[8]:
def predict_continuous(test_X):
test_tr=test_X[0:1]
# p=model.predict(test_tr)
# p.shape
tr=[]
split_tr=np.vsplit(test_tr[0], 2)
# split_tr[1].shape
tr.append(split_tr[1])
num=5 #连续预测次数
for i in range(num):
predict_y=model.predict(test_tr)
tr.append(predict_y[0])
temp=tr[-2]
test_tr=np.vstack((temp,predict_y[0]))
test_tr=np.array([test_tr])
tr=np.array(tr[1:])
return tr
def predict_continuous_compare(test_X):
test_tr=test_X[0:1]
# p=model.predict(test_tr)
# p.shape
tr=[]
split_tr=np.vsplit(test_tr[0], 2)
# split_tr[1].shape
tr.append(split_tr[1])
num=5 #连续预测次数
for i in range(num):
predict_y=model2.predict(test_tr)
tr.append(predict_y[0])
temp=tr[-2]
test_tr=np.vstack((temp,predict_y[0]))
test_tr=np.array([test_tr])
tr=np.array(tr[1:])
return tr
tr=predict_continuous(test_X1)
tr1=predict_continuous_compare(test_X2)
# In[9]:
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error,mean_absolute_error
def reverse1(predict,test_X,test_Y):
temp = test_X1.reshape(test_X.shape[0]*test_X.shape[1], test_X.shape[2])
length=len(predict)
temp1=temp[:length*100,-1:]
temp2=temp[:3737*100,-1:]
iny_yhat=predict.reshape(predict.shape[0]*predict.shape[1],predict.shape[2])
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp1), axis=1)
iny.shape
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(length,100,3)
print(inv_y_reshape.shape)
#真实数据
tempy=test_Y1.reshape(test_Y.shape[0]*test_Y.shape[1], test_Y.shape[2])
# print(tempy.shape)
iny_temp= concatenate((tempy, temp2), axis=1)#水平方向合并,为了适配scaler
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:(length)*100,0:3]
iny_real_reshape=iny_real.reshape(length,100,3)
print(iny_real_reshape.shape)
# # # calculate RMSE
mae = sqrt(mean_absolute_error(iny_real,inv_y))
print('Test mae: %.3f' % mae)
return inv_y_reshape,iny_real_reshape
inv_y_reshape1,iny_real_reshape1=reverse1(tr,test_X1,test_Y1)
inv_y_reshape4,iny_real_reshape4=reverse2(tr1,test_X2,test_Y2,test_X)
# inv_y_reshape2,iny_real_reshape2=reverse1(predict,test_X1,test_Y1)
# inv_y_reshape,iny_real_reshape=reverse(predict,test_X1,test_Y1)
# In[197]:
import matplotlib.pyplot as plt
def draw(inv_y_reshape,iny_real_reshape):
#画出真实数据和预测数据
predict_x,predict_y,predict_z=[],[],[]
predict_x2,predict_y2,predict_z2=[],[],[]
true_x,true_y,true_z=[],[],[]
for k in range(5):
for i in range(len(inv_y_reshape[k])):
predict_x.append(inv_y_reshape[k][i][0])
predict_y.append(inv_y_reshape[k][i][1])
predict_z.append(inv_y_reshape[k][i][2])
true_x.append(iny_real_reshape[k][i][0])
true_y.append(iny_real_reshape[k][i][1])
true_z.append(iny_real_reshape[k][i][2])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(predict_x, predict_y, predict_z, s=2,label='prediction')
ax.scatter(true_x, true_y, true_z, s=2,label='true')
plt.legend()
plt.show()
# In[198]:
draw(inv_y_reshape1,iny_real_reshape1)
# In[13]:
# In[202]:
draw(inv_y_reshape4,iny_real_reshape4)
# In[ ]:
# 打开TXT文件
import matplotlib.pyplot as plt # 导入 Matplotlib 工具包
import numpy as np
plt.style.use('seaborn-whitegrid')
import matplotlib as mpl
plt.rcParams['font.family'] = 'Times New Roman'
mpl.rcParams['axes.labelsize'] = 14
mpl.rcParams['legend.fontsize'] = 12
# 设置字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
def drawResultAndIter(line):
labels1=["train","test"]
f, ax = plt.subplots(1, 1)
for i in range(len(line)):
plt.plot(line[i],label=labels1[i])
# plt.plot(r2,label=labels1[1])
# plt.axhline(y=60, color='r', linestyle='--', label='Horizontal Line at y=60')
plt.legend()
ax.set_xlabel('iteration')
ax.set_ylabel('mse')
plt.show()
def draw_mae():
f, ax = plt.subplots(1, 1)
x=[i for i in range(1,6)]
r1=[13.212,23.561,31.479,37.121,40.163]
r2=[10.979,14.929,16.194,17.517,21.643]
r1 = [174.212, 529, 961, 1369, 1600]
r2 = [100.979, 196, 256, 289, 441]
d=[(r1[i]-r2[i])/r1[i] for i in range(len(r1))]
print(sum(d)/len(d))
plt.plot(x,r1, label="traditional LSTM",marker="o")
plt.plot(x,r2, label="proposed LSTM",marker="^")
ax.set_xlabel('number of prediction times')
ax.set_ylabel('MAE(m)')
plt.xticks(np.arange(1, 6, 1))
plt.legend()
plt.show()
def draw_num_mae():
# 60 0.0078 0.0090 18.347
# 70 0.0056 0.0052 12.885
# 80 0.0058 0.0080 16.715
# 90 0.0077 0.0079 16.813
# 100 0.0059 0.0057 13.206
# 110 0.0059 0.0060 14.344
# 120 0.0175 0.0126 19.897
f, ax = plt.subplots(1, 1)
x=[i for i in range(60,130,10)]
y1=[0.0078,0.0056,0.0058,0.0077,0.0059,0.0060,0.0175]
y2=[18.347,12.885,16.715,16.813,13.206,14.344,19.897]
plt.plot(x, y1, label="train MAE", marker="o")
plt.plot(x, y2, label="real MAE", marker="^")
ax.set_xlabel('number of hidden nodes')
ax.set_ylabel('MAE(m)')
# plt.xticks(np.arange(1, 6, 1))
plt.legend()
plt.show()
if __name__ == '__main__':
draw_mae()
# draw_num_mae()
# with open("loss.txt", "r", encoding="utf-8") as f:
# text = f.readlines()
# with open("val_loss.txt", "r", encoding="utf-8") as f:
# text2 = f.readlines()
# l=[]
# l1 = [float(line.strip("\n")) for line in text]
# l2=[float(line.strip("\n")) for line in text2]
# l.append(l1)
# l.append(l2)
#
# drawResultAndIter(l)
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
data_train,data_test
# In[2]:
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
placeholder=[]
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),0:3]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
placeholder.append(dataset[i + window:(i + window+predict_length),3:])
return np.array(dataX), np.array(dataY),np.array(placeholder)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
data_tr,data_te
train_X,train_Y,p=create_dataset(data_tr,200,100,100)
test_X,test_Y,placeholder=create_dataset(data_te,200,100,100)
train_X.shape,train_Y.shape,test_X.shape,test_Y.shape
placeholder.shape
# In[21]:
from keras.models import load_model
# load model from single file
model1 = load_model('/home/lxm/model/lstm_model_compare.h5')
yhat = model1.predict(test_X)
yhat.shape
# In[40]:
# In[11]:
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error,mean_absolute_error
temp = placeholder.reshape(placeholder.shape[0]*placeholder.shape[1], placeholder.shape[2])
iny_yhat=yhat.reshape(yhat.shape[0]*yhat.shape[1],yhat.shape[2])
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp), axis=1)
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(int(inv_y.shape[0]/100),100,3)
inv_y_reshape.shape
# In[26]:
#真实数据
tempy=test_Y.reshape(test_Y.shape[0]*test_Y.shape[1], test_Y.shape[2])
iny_temp= concatenate((tempy, temp), axis=1)
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:,0:3]
iny_real_reshape=iny_real.reshape(int(iny_real.shape[0]/100),100,3)
print(iny_real_reshape.shape)
# # # calculate RMSE
rmse = sqrt(mean_absolute_error(inv_y[5],iny_real[5]))
print('Test MAE: %.3f' % rmse)
# In[42]:
import matplotlib.pyplot as plt
#画出真实数据和预测数据
predict_x,predict_y,predict_z=[],[],[]
true_x,true_y,true_z=[],[],[]
for k in range(10):
for i in range(len(inv_y_reshape[k])):
predict_x.append(inv_y_reshape[k][i][0])
predict_y.append(inv_y_reshape[k][i][1])
predict_z.append(inv_y_reshape[k][i][2])
true_x.append(iny_real_reshape[k][i][0])
true_y.append(iny_real_reshape[k][i][1])
true_z.append(iny_real_reshape[k][i][2])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(true_x, true_y, true_z, s=2,label='true')
ax.scatter(predict_x, predict_y, predict_z, s=2,label='prediction')
plt.legend()
plt.show()
# In[ ]:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
data_train,data_test
# In[20]:
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
data_tr,data_te
train_X,train_Y=create_dataset(data_tr,200,100,100)
test_X,test_Y=create_dataset(data_te,200,100,100)
train_X.shape,train_Y.shape,test_X.shape,test_Y.shape
# In[19]:
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset2(dataset,window,offset,predict_length):
dataX, dataY = [], []
placeholder=[]
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),0:3]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
placeholder.append(dataset[i + window:(i + window+predict_length),3:])
return np.array(dataX), np.array(dataY),np.array(placeholder)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
data_tr,data_te
train_X2,train_Y2,p=create_dataset2(data_tr,200,100,100)
test_X2,test_Y2,placeholder=create_dataset2(data_te,200,100,100)
train_X2.shape,train_Y2.shape,test_X2.shape,test_Y2.shape
# placeholder.shape
# In[21]:
from keras.models import load_model
# load model from single file
model1 = load_model('/home/lxm/model/lstm_model3.h5')
# model2=load_model('/home/lxm/model/lstm_model_compare.h5')
yhat = model1.predict(test_X)
# yhat2=model2.predict(test_X2)
yhat
# In[16]:
from numpy import concatenate
from numpy import sqrt
from sklearn.metrics import mean_squared_error,mean_absolute_error
temp = test_X.reshape(test_X.shape[0]*test_X.shape[1], test_X.shape[2])
temp=temp[:373700,2:]
iny_yhat=yhat.reshape(yhat.shape[0]*yhat.shape[1],yhat.shape[2])
#预测数据逆缩放 invert scaling for forecast
iny = concatenate((iny_yhat, temp), axis=1)
inverse_y = scaler.inverse_transform(iny)
inv_y = inverse_y[:, 0:3]
# inv_yhat = np.array(inv_yhat)
inv_y_reshape=inv_y.reshape(int(inv_y.shape[0]/100),100,3)
inv_y_reshape.shape
#真实数据
tempy=test_Y.reshape(test_Y.shape[0]*test_Y.shape[1], test_Y.shape[2])
iny_temp= concatenate((tempy, temp), axis=1)#水平方向合并,为了适配scaler
iny_temp1=scaler.inverse_transform(iny_temp)
iny_real=iny_temp1[:,0:3]
iny_real_reshape=iny_real.reshape(int(iny_real.shape[0]/100),100,3)
iny_real_reshape
# # # calculate RMSE
mae = sqrt(mean_absolute_error(iny_real,inv_y))
print('Test mae: %.3f' % mae)
# In[22]:
import matplotlib.pyplot as plt
#画出真实数据和预测数据
predict_x,predict_y,predict_z=[],[],[]
true_x,true_y,true_z=[],[],[]
for k in range(30):
for i in range(len(inv_y_reshape[k])):
predict_x.append(inv_y_reshape[k][i][0])
predict_y.append(inv_y_reshape[k][i][1])
predict_z.append(inv_y_reshape[k][i][2])
true_x.append(iny_real_reshape[k][i][0])
true_y.append(iny_real_reshape[k][i][1])
true_z.append(iny_real_reshape[k][i][2])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(predict_x, predict_y, predict_z, s=2,label='prediction')
ax.scatter(true_x, true_y, true_z, s=2,label='true')
plt.legend()
plt.show()
# In[ ]:
# In[ ]:
from tqdm import tqdm
import concurrent.futures
import math
import os
from csv import reader
import pandas as pd
import position_transfer
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
# 第一个文件的第一个有效帧,不用这个
# < longitude > 124.671000 < / longitude >
# < latitude > 39.902700 < / latitude >
# < altitude > 44.743948 < / altitude >
#第一行
start_long=124.517535
start_lati=39.947593
start_altitude=0
def cal_objective_position(x,y,z,tarRng,tarAzi,tarEli):
tar_x = x + tarRng * math.sin(tarAzi) * math.cos(tarEli)
tar_y = y + tarRng * math.cos(tarAzi) * math.cos(tarEli)
tar_z = z + tarRng* math.sin(tarEli)
return tar_x,tar_y,tar_z
def process(file_path,file_name):
filename = file_name.split(".")[0]
df = pd.read_excel(file_path)
df['tar_x']=''
df['tar_y']=''
df['tar_z']=''
# df.to_csv('example.csv', index=False)
for index,row in df.iterrows():
longitude=row['longitude']
latitude=row['latitude']
altitude=row['altitude']
tarRng=row['tarRng']
tarEli=row['tarEli']
tarAzi=row['tarAzi']
result=position_transfer.gps_to_xyz(latitude,longitude,altitude,start_lati,start_long,start_altitude)
x,y,z=cal_objective_position(result[0],result[1],result[2],tarRng,tarAzi,tarEli)
# print(x,y,z)
# x_arr.append(x)
# y_arr.append(y)
# z_arr.append(z)
# return x_arr,y_arr,z_arr
df.loc[index, 'tar_x'] = x
df.loc[index, 'tar_y'] = y
df.loc[index, 'tar_z'] = z
df.to_csv('E:/replay/1对1/data/1/'+filename+'.csv', index=False)
return filename + 'finish'
def processFiles():
folder_path = "E:/replay/1对1/original_data/5" # 替换为你的文件夹路径
# folder_path = "E:/replay/demo"
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
results = []
count = 1
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".xlsx"):
file_path = os.path.join(folder_path, file_name)
# 解析XML文件
result = executor.submit(process, file_path, file_name)
results.append(result)
for future in concurrent.futures.as_completed(results):
print(count)
print(future.result())
count += 1
def cal_features(file_path,file_name):
filename = file_name.split(".")[0]
df = pd.read_csv(file_path)
df['position_change'] = ''
df['v'] = ''
df['v_change'] = ''
df['r']=''
df['eli_change']=''
df['h_change']=''
# df.drop('e_change',axis=1,inplace=True)
for index, row in df.iterrows():
if index > 0:
x = row['tar_x']
y = row['tar_y']
z = row['tar_z']
e=row['tarEli']
x_pre=df.loc[index-1, 'tar_x']
y_pre=df.loc[index-1, 'tar_y']
z_pre=df.loc[index-1, 'tar_z']
e_pre=df.loc[index-1, 'tarEli']
position_change=math.sqrt((x_pre-x)**2+(y_pre-y)**2+(z_pre-z)**2)
h_change=z-z_pre
e_change=e-e_pre
speed=position_change/0.1
df.loc[index, 'position_change'] = position_change
df.loc[index,'v']=speed
df.loc[index, 'h_change'] = h_change
df.loc[index, 'eli_change'] = e_change
speed_change=0
if index!=1:
speed_change=speed-df.loc[index-1,'v']
df.loc[index,'v_change']=speed_change
if x-x_pre!=0:
r=math.atan((y-y_pre)/(x-x_pre))/0.1
else:
r=0
df.loc[index, 'r'] = r
df.to_csv('E:/replay/1对1/data/1/'+filename+'.csv', index=False)
return filename + 'finish'
def cal_features_for_files():
folder_path = "E:/replay/1对1/data/5" # 替换为你的文件夹路径
# folder_path = "E:/replay/demo"
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
results = []
count = 1
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# 解析XML文件
result = executor.submit(cal_features, file_path, file_name)
results.append(result)
for future in concurrent.futures.as_completed(results):
print(count)
print(future.result())
count += 1
def draw():
# 设置图例字号
folder_path = "E:/replay/1对1/process_data/5" # 替换为你的文件夹路径
# folder_path = "E:/replay/demo"
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
mpl.rcParams['legend.fontsize'] = 10
# 方式2:设置三维图形模式
fig = plt.figure()
ax = fig.gca(projection='3d')
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if count>10:
break
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
df = pd.read_csv(file_path)
count+=1
x_arr = []
y_arr = []
z_arr = []
# df.to_csv('example.csv', index=False)
for index, row in df.iterrows():
if index>1:
x = row['tar_x']
y = row['tar_y']
z = row['tar_z']
x_arr.append(x)
y_arr.append(y)
z_arr.append(z)
# 绘制图形
ax.scatter(x_arr, y_arr, z_arr, s=2)
def change_colum(file_path):
df = pd.read_csv(file_path)
df = df[['number', 'longitude', 'latitude', 'altitude', 'yaw', 'pitch', 'roll',
'tarRng', 'tarAzi', 'tarEli', 'tar_x', 'tar_y', 'tar_z', 'position_change', 'v',
'v_change', 'r', 'eli_change', 'h_change']]
df.to_csv(file_path, index=False)
return 'finish'
def change_colum_for_files():
folder_path = "E:/replay/1对1/data/1" # 替换为你的文件夹路径
# folder_path = "E:/replay/demo"
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
results = []
count = 1
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# 解析XML文件
result = executor.submit(change_colum, file_path)
results.append(result)
for future in concurrent.futures.as_completed(results):
print(count)
print(future.result())
count += 1
if __name__ == '__main__':
folder_path = "E:/replay/1对1/data/2/"
file_path=folder_path + "default - 20230601-134029.csv"
# df = pd.read_csv(file_path)
# df = df[['number', 'longitude', 'latitude', 'altitude', 'yaw', 'pitch', 'roll',
# 'tarRng', 'tarAzi', 'tarEli','tar_x','tar_y','tar_z','position_change','v',
# 'v_change','r','eli_change','h_change']]
# df.to_csv(file_path, index=False)
# process(file_path1,file_name1)
# cal_features(file_path, file_name)
# processFiles()
# cal_features_for_files()
# change_colum_for_files()
draw()
plt.show()
# 显示图形
# plt.show()
0.16689902544021606
0.09015128761529922
0.07931145280599594
0.07927117496728897
0.06992689520120621
0.06491272151470184
0.06490819156169891
0.06490745395421982
0.06490493565797806
0.06490547209978104
0.06490184366703033
0.06490079313516617
0.06489940732717514
0.06489758938550949
0.0648963674902916
0.06489498913288116
0.06489413976669312
0.06489422172307968
0.0648917555809021
0.06489308923482895
0.06489050388336182
0.06489156186580658
0.06489019840955734
0.06489014625549316
0.06488970667123795
0.06488940119743347
0.0648890882730484
0.06488877534866333
0.054654814302921295
0.009252983145415783
0.00923607312142849
0.009236348792910576
0.009236103855073452
0.009235227480530739
0.009234465658664703
0.00923363957554102
0.009233028627932072
0.009232483804225922
0.009231953881680965
0.009231491014361382
0.009231118485331535
0.009230795316398144
0.00923048984259367
0.009230225346982479
0.009229970164597034
0.009229743853211403
0.009229538030922413
0.009229367598891258
0.009229221381247044
0.009229096584022045
0.009228979237377644
0.009228871203958988
0.009228760376572609
0.009228644892573357
0.009228519164025784
0.009228400886058807
0.009228283539414406
0.0092281773686409
0.00922804418951273
0.009228064678609371
0.009227816946804523
0.009227808564901352
0.009227623231709003
0.0092275720089674
0.009227360598742962
0.009227430447936058
0.009227169677615166
0.009227215312421322
0.009227119386196136
0.009226889349520206
0.009226965717971325
0.009226837195456028
0.00922674871981144
0.009226693771779537
0.00922651682049036
0.009226593188941479
0.009226150810718536
0.009226472117006779
0.009226332418620586
0.009226283989846706
0.009226219728589058
0.009226111695170403
0.00922610703855753
0.009226024150848389
0.00922599621117115
0.009225867688655853
0.009225884452462196
0.009225696325302124
0.009225760586559772
0.009226232767105103
0.009225727990269661
0.009225597605109215
0.009225585497915745
0.009225527755916119
0.009225485846400261
0.009225433692336082
0.009225395508110523
0.009225340560078621
0.009225291199982166
0.009225242771208286
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_all=pd.DataFrame()
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# print(file_path)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data_all = pd.concat([data_all, data], axis=0, ignore_index=True) # 将文件内容合并到data_all中
from sklearn.preprocessing import MinMaxScaler
#保证为float ensure all data is float
value = data_all.values
value = value.astype('float32')
#归一化 normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(value)
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),1:4]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),1:4])
return np.array(dataX), np.array(dataY)
dataX,dataY=create_dataset(scaled,200,100,100)
#随机取80%的轨迹为训练集,20%的轨迹为测试集
#p为百分比
def split_dataset(dataX,dataY,p=0.8):
train_X=[]
train_Y=[]
test_X=[]
test_Y=[]
# train_size = int(len(dataset) * 0.8)
for i in range(len(dataX)):
r=random.random()
if r<=p:
train_X.append(dataX[i])
train_Y.append(dataY[i])
else:
test_X.append(dataX[i])
test_Y.append(dataY[i])
return np.array(train_X), np.array(train_Y), np.array(test_X), np.array(test_Y)
train_X,train_Y,test_X,test_Y=split_dataset(dataX,dataY)
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(50, input_shape=(200, 3))) # LSTM层,50个神经元
# model.add(LSTM(units=100)) # LSTM层,50个神经元
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.5))
model.add(Dense(300,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 3 = 30
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_squared_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=200, batch_size=72, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/lstm_model_compare.h5')
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),0:3]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
train_X,train_Y=create_dataset(data_tr,200,100,100)
test_X,test_Y=create_dataset(data_te,200,100,100)
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(100, input_shape=(200, 3))) # LSTM层,50个神经元
# model.add(LSTM(units=100)) # LSTM层,50个神经元
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.5))
model.add(Dense(300,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 3 = 30
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_absolute_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=200, batch_size=72, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/lstm_model_compare1.h5')
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_all=pd.DataFrame()
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
file_path = os.path.join(folder_path, file_name)
# print(file_path)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data_all = pd.concat([data_all, data], axis=0, ignore_index=True) # 将文件内容合并到data_all中
from sklearn.preprocessing import MinMaxScaler
#保证为float ensure all data is float
value = data_all.values
value = value.astype('float32')
#归一化 normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(value)
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),1:4])
return np.array(dataX), np.array(dataY)
dataX,dataY=create_dataset(scaled,200,100,100)
#随机取80%的轨迹为训练集,20%的轨迹为测试集
#p为百分比
def split_dataset(dataX,dataY,p=0.8):
train_X=[]
train_Y=[]
test_X=[]
test_Y=[]
# train_size = int(len(dataset) * 0.8)
for i in range(len(dataX)):
r=random.random()
if r<=p:
train_X.append(dataX[i])
train_Y.append(dataY[i])
else:
test_X.append(dataX[i])
test_Y.append(dataY[i])
return np.array(train_X), np.array(train_Y), np.array(test_X), np.array(test_Y)
train_X,train_Y,test_X,test_Y=split_dataset(dataX,dataY)
import os
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(50, input_shape=(200, 10))) # LSTM层,50个神经元
# model.add(LSTM(units=100)) # LSTM层,50个神经元
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.5))
model.add(Dense(300,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 3 = 30
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_squared_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=200, batch_size=72, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/lstm_model1.h5')
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
#改了训练集和测试集的归一化
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
train_X,train_Y=create_dataset(data_tr,200,100,100)
test_X,test_Y=create_dataset(data_te,200,100,100)
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(100, input_shape=(200, 10))) # LSTM层
# model.add(LSTM(units=100)) # LSTM层,50个神经元
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
model.add(Dense(300,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.2))
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_absolute_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=200, batch_size=72, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/lstm_model3.h5')
# tf.keras.backend.clear_session()
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
#改了训练集和测试集的归一化
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),:-1])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
train_X,train_Y=create_dataset(data_tr,200,100,100)
test_X,test_Y=create_dataset(data_te,200,100,100)
start_time = time.time()
##模型定义 design network 100帧预测10帧
model = Sequential()
model.add(LSTM(100, input_shape=(200, 10))) # LSTM层,50个神经元
# model.add(LSTM(units=100)) # LSTM层,50个神经元
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
model.add(Dense(1000,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 10 = 100
# model.add(Dropout(0.2))
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 10)))
model.compile(loss='mean_absolute_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=100, batch_size=72, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
# with open('loss.txt','a', encoding='utf-8') as f:
# for loss in history.history['loss']:
# f.write(str(loss) + '\n')
# with open('val_loss.txt','a', encoding='utf-8') as f:
# for loss in history.history['val_loss']:
# f.write(str(loss) + '\n')
model.save('/home/lxm/model/lstm_model4.h5')
# tf.keras.backend.clear_session()
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
#改了训练集和测试集的归一化
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
train_X,train_Y=create_dataset(data_tr,200,30,100)
test_X,test_Y=create_dataset(data_te,200,30,100)
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(units=70, input_shape=(200, 10))) # LSTM层
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
model.add(Dense(300,kernel_initializer='normal',activation='relu')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.2))
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_absolute_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=200, batch_size=128, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# with open('loss_200.txt','a', encoding='utf-8') as f:
# for loss in history.history['loss']:
# f.write(str(loss) + '\n')
# with open('val_loss_200.txt','a', encoding='utf-8') as f:
# for loss in history.history['val_loss']:
# f.write(str(loss) + '\n')
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/real/lstm_model3.h5')
# tf.keras.backend.clear_session()
#!/usr/bin/env python
# coding: utf-8
import os
import time
import pandas as pd
from tqdm import tqdm
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import tensorflow as tf
from matplotlib import pyplot
import numpy as np
import random
#改了训练集和测试集的归一化
from tqdm import tqdm
import os
#先分训练集和测试集
folder_path = "/home/lxm/1vs1/total" # 替换为你的文件夹路径
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
data_train=pd.DataFrame()
data_test=pd.DataFrame()
count=0
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".csv"):
count+=1
if count<=4:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_train = pd.concat([data_train, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("train",file_path)
else:
file_path = os.path.join(folder_path, file_name)
# 解析CSV文件
df = pd.read_csv(file_path) # 读取csv文件到dataframe中
data =df.iloc[:,1:]
data1=pd.DataFrame(data,columns=['tar_x','tar_y','tar_z','tarEli','position_change','v','v_change','r','eli_change',
'h_change','id'])
data_test = pd.concat([data_test, data1], axis=0, ignore_index=True) # 将文件内容合并到data_all中
# print("test",file_path)
import numpy as np
#分别在测试集和训练集中分x和y
def create_dataset(dataset,window,offset,predict_length):
dataX, dataY = [], []
for i in range(0,len(dataset)-window-1,offset):
if (i + window+predict_length)<len(dataset) :
id1=dataset[i,-1]
id2=dataset[i+window-1,-1]
id3=dataset[i+window+predict_length-1,-1]
if id1==id2 and id1==id3:
a = dataset[i:(i+window),:-1]
dataX.append(a)
dataY.append(dataset[i + window:(i + window+predict_length),0:3])
return np.array(dataX), np.array(dataY)
train=data_train.values
test=data_test.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train) ## 生成规则
data_tr = scaler.transform(train) ## 将规则应用于训练集
data_te = scaler.transform(test) ## 将规则应用于测试集
train_X,train_Y=create_dataset(data_tr,200,30,100)
test_X,test_Y=create_dataset(data_te,200,30,100)
start_time = time.time()
##模型定义 design network 200帧预测100帧
model = Sequential()
model.add(LSTM(units=128, return_sequences=True,input_shape=(200, 10))) # LSTM层
# 第二个隐藏层 LSTM
model.add(LSTM(units=64,))
# model.add(Dense(200,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
model.add(Dense(300,kernel_initializer='normal',activation='sigmoid')) # 输出维度为 10 * 3 = 30
# model.add(Dropout(0.2))
# 重塑输出,使其成为[10, 3]
model.add(tf.keras.layers.Reshape((100, 3)))
model.compile(loss='mean_absolute_error', optimizer='adam') # 使用均方误差作为损失函数,Adam优化器
#模型训练 fit network
history = model.fit(train_X, train_Y, epochs=300, batch_size=128, validation_data=(test_X, test_Y), verbose=2,
shuffle=False)
end_time = time.time()
print("time:",end_time-start_time)
#输出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# with open('loss_200.txt','a', encoding='utf-8') as f:
# for loss in history.history['loss']:
# f.write(str(loss) + '\n')
# with open('val_loss_200.txt','a', encoding='utf-8') as f:
# for loss in history.history['val_loss']:
# f.write(str(loss) + '\n')
# 使用模型进行预测
yhat = model.predict(test_X)
model.save('/home/lxm/model/real/lstm_model2.h5')
# tf.keras.backend.clear_session()
import copy
from copy import deepcopy
import math
import matplotlib.pyplot as plt
#option是一个字典,确定了坐标系,cor_P是P点相对坐标(形如列表[x,y]),返回P点的经纬度(形如列表[lng,lat])
import numpy as np
def gps_to_xyz(latitude, longitude, altitude, lat_ref, long_ref, alt_ref):
# 将经纬度转换为弧度制
latitude_rad = math.radians(latitude)
longitude_rad = math.radians(longitude)
lat_ref_rad = math.radians(lat_ref)
long_ref_rad = math.radians(long_ref)
# 地球的平均半径,单位:米
R = 6371000 # 注意:北纬40度附近
# 计算纬度和经度的距离差(m)
d_lat = (latitude_rad - lat_ref_rad) * R
d_long = (longitude_rad - long_ref_rad) * R * math.cos(lat_ref_rad)
# 将距离差转换为直角坐标系中的x和y坐标
x = d_long
y = d_lat
# 计算z轴上的高度差
z = altitude - alt_ref
result = [x, y, z]
return result
def xyz_to_gps(x, y, z, lat_ref, long_ref, alt_ref):
# 地球的平均半径,单位:米
R = 6371000 # 注意:北纬40度附近,可调
# 将经纬度转换为弧度制
lat_ref_rad = math.radians(lat_ref)
long_ref_rad = math.radians(long_ref)
# 将 x、y 转换为经纬差
d_long = x / (R * math.cos(lat_ref_rad))
d_lat = y / R
# 计算待转换点的纬度和经度弧度制
latitude_rad = lat_ref_rad + d_lat
longitude_rad = long_ref_rad + d_long
# 将经纬度转换为度数制
latitude = math.degrees(latitude_rad)
longitude = math.degrees(longitude_rad)
# 计算待转换点的高度
altitude = z + alt_ref
result = [latitude, longitude, altitude]
return result
def draw(data):
plt.figure(num=1, figsize=(10, 10))
x = data[:, 0]
y = data[:, 1]
plt.scatter(x, y)
# plt.xlim(-1000, 1000)
# plt.ylim(-0, 7001)
ax = plt.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
# x1 = np.linspace(300, 700, 500)
# center1 = 500 + np.sqrt(200 ** 2 - (x1 - 500) ** 2)
# center2 = 500 - np.sqrt(200 ** 2 - (x1 - 500) ** 2)
# plt.plot(x1, center1,c='b')
# plt.plot(x1, center2,c='b')
# x2 = np.linspace(200, 800, 500)
# center21 = 500 + np.sqrt(300 ** 2 - (x2 - 500) ** 2)
# center22 = 500 - np.sqrt(300 ** 2 - (x2 - 500) ** 2)
# plt.plot(x2, center21, c='r')
# plt.plot(x2, center22, c='r')
# x3 = np.linspace(100, 900, 500)
# center31 = 500 + np.sqrt(400 ** 2 - (x3 - 500) ** 2)
# center32 = 500 - np.sqrt(400 ** 2 - (x3 - 500) ** 2)
# plt.plot(x3, center31, c='g')
# plt.plot(x3, center32, c='g')
# model = KMeans(n_clusters=5, random_state=0).fit(data)
# center = model.cluster_centers_
# for c in center:
# plt.scatter(c[0], c[1],s=200,marker='p')
return plt
#主函数为测试样例,仅供参考
if __name__ == '__main__':
point=[115.82869371103702, 39.934012711037056]
# users= [[115.81213005558247, 39.91493319843596], [115.80151534346862, 39.89924075328783], [115.81181641633103, 39.91345439036004], [115.81848975759513, 39.89903321215211], [115.85197567, 39.9198535], [115.80020969196244, 39.9189566370977], [115.80196883, 39.92988283], [115.79974025758239, 39.90582839900009], [115.7997408, 39.9058]]
users=[[115.82869371103702, 39.934012711037056],
[115.82882156385072, 39.93437556385077],
[115.82852192424052, 39.9342609242405],
[115.83312770598623, 39.92981770598637],
[115.83292091918966, 39.929899919189836],
[115.83301170598625, 39.92970970598638],
[115.8325003116783, 39.93359531167772],
[115.83289629147556, 39.93401129147525],
[115.83301557069605, 39.934121570695886]]
data=[]
for user in users:
data.append(gps_to_xyz(user[0],user[1],500,point[0],point[1],0))
data=np.array(data)
# print(data)
draw(data).show()
# file = open('相对坐标.txt', 'w')
#
# point_map={
# "10": [117.4067305, 39.55563215],
# "9": [117.4025971, 39.55762687],
# "8": [117.4051509, 39.55808252],
# "7": [117.4038813, 39.55929924],
# "6": [117.4015306, 39.55961509],
# "5": [117.4028736, 39.56110118],
# "4": [117.401473, 39.5607669],
# "3": [117.4035416, 39.56090042],
# "2": [117.4024371, 39.56174394],
# "1": [117.4018553, 39.56173589],
# "回传点": [117.4049073, 39.55535354],
# }
# points=[]
# for key in point_map:
# points.append(point_map[key])
# print(get_option())
# # option=determine_coordinate(points)
# option=get_option()
# file.write("("+str(option["cor_O"][0])+", "+str(option["cor_O"][1])+") 对应 ")
# file.write(str(option["ll_O"][0])+", "+str(option["ll_O"][1])+'\n')
# file.write("(" + str(option["cor_A"][0]) + ", " + str(option["cor_A"][1]) + ") 对应 ")
# file.write(str(option["ll_A"][0]) + ", " + str(option["ll_A"][1]) + '\n')
# file.write("(" + str(option["cor_B"][0]) + ", " + str(option["cor_B"][1]) + ") 对应 ")
# file.write(str(option["ll_B"][0]) + ", " + str(option["ll_B"][1]) + '\n')
# file.write('\n')
#
# for key in point_map:
# ans=lnglat_to_coordinate(option, point_map[key])
# file.write(key+", "+'('+str(ans[0])+', '+str(ans[1])+')'+'\n')
#
#
#
# file.close()
# uavs=[[2560.02056799,2086.20168574],
# [4085.42479909,5313.20660584]]
# for uav in uavs:
# print(coordinate_to_lnglat(option,uav))
50 0.0064 0.0089 18.280
60 0.0078 0.0090 18.347
70 0.0056 0.0052 12.885
80 0.0058 0.0080 16.715
90 0.0077 0.0079 16.813
100 0.0059 0.0057 13.206
110 0.0059 0.0060 14.344
120 0.0175 0.0126 19.897
步长
100 0.0059 0.0069 15.384
150 0.0057 0.0071 14.678
200 0.0056 0.0052 12.885
250 0.0060 0.0064 14.033
300 0.0078 0.0109 18.321
\ No newline at end of file
import xml.etree.ElementTree as ET
import os
import pandas as pd
from tqdm import tqdm
import concurrent.futures
#我们创建了一个空的DataFrame,包含四个列:id、title、author和price。
# df = pd.DataFrame(columns=['id','number', 'longitude', 'latitude','altitude', 'yaw', 'pitch', 'roll',
# 'tarRng', 'tarAzi', 'tarEli'])
count=1
def processFile(file_path,filename):
filename=filename.split(".")[0]
df = pd.DataFrame(columns=['number', 'longitude', 'latitude', 'altitude', 'yaw', 'pitch', 'roll',
'tarRng', 'tarAzi', 'tarEli'])
tree = ET.parse(file_path)
replay = tree.getroot()
objectsSequences = replay.find('objectsSequences')
for sequence in objectsSequences:
group = sequence.find('group').text
if group == '0':
frames = sequence.find('frames')
for frame in frames:
number = frame.find('number').text
item = frame.find('data')
if item.get('Type') == '1':
longitude = item.find('longitude').text
if longitude=="0.000000":
continue
latitude = item.find('latitude').text
altitude = item.find('altitude').text
yaw = item.find('yaw').text
pitch = item.find('pitch').text
roll = item.find('roll').text
devices = item.find('devices')
tarRng = ''
tarAzi = ''
tarEli = ''
if devices != None:
for device in devices:
if device.get('Type') == "F1911::Radar":
tracks = device.find("tracks")
if tracks != None:
track = tracks.find("track")
if track != None:
tarRng = track.find('tarRng').text
tarAzi = track.find('tarAzi').text
tarEli = track.find('tarEli').text
if(tarRng==''):
continue
df = df.append(
pd.Series([number, longitude, latitude, altitude, yaw, pitch, roll, tarRng, tarAzi, tarEli],
index=['number', 'longitude', 'latitude', 'altitude', 'yaw', 'pitch', 'roll',
'tarRng', 'tarAzi', 'tarEli']), ignore_index=True)
df.to_excel('E:/replay/1对1/original_data/1/'+filename+'.xlsx', index=False)
return filename+'finish'
if __name__ == '__main__':
folder_path = "E:/replay/replay/20230602_1对1/1" # 替换为你的文件夹路径
filename='default - 20230601-133944.replay'
file_path='E:/replay/replay/20230602_1对1/1/default - 20230601-133944.replay'
processFile(file_path,filename)
# file_list = os.listdir(folder_path)
# results=[]
# count=1
# with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
# for file_name in tqdm(file_list, desc="Processing files"):
# if file_name.endswith(".replay"):
# file_path = os.path.join(folder_path, file_name)
# # 解析XML文件
# result=executor.submit(processFile,file_path, file_name)
# results.append(result)
# for future in concurrent.futures.as_completed(results):
# print(count)
# print(future.result())
# count+=1
#
#
import xml.etree.ElementTree as ET
import os
import pandas as pd
from tqdm import tqdm
folder_path = "E:/replay/replay/20230602_1对1/1" # 替换为你的文件夹路径
# folder_path ="E:/replay/demo"
# # 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
#我们创建了一个空的DataFrame,包含四个列:id、title、author和price。
df = pd.DataFrame(columns=['id','number', 'longitude', 'latitude','altitude', 'yaw', 'pitch', 'roll',
'tarRng', 'tarAzi', 'tarEli'])
count=1
for file_name in tqdm(file_list, desc="Processing files"):
if file_name.endswith(".replay"):
file_path = os.path.join(folder_path, file_name)
id = count
count += 1
# 解析XML文件
tree = ET.parse(file_path)
replay = tree.getroot()
objectsSequences=replay.find('objectsSequences')
for sequence in objectsSequences:
group=sequence.find('group').text
if group=='0':
frames= sequence.find('frames')
for frame in frames:
number=frame.find('number').text
item=frame.find('data')
if item.get('Type')=='1':
longitude = item.find('longitude').text
latitude = item.find('latitude').text
altitude = item.find('altitude').text
yaw = item.find('yaw').text
pitch = item.find('pitch').text
roll=item.find('roll').text
devices = item.find('devices')
tarRng = ''
tarAzi = ''
tarEli = ''
if devices != None:
for device in devices:
if device.get('Type') == "F1911::Radar":
tracks = device.find("tracks")
if tracks!=None:
track =tracks.find("track")
if track!=None:
tarRng = track.find('tarRng').text
tarAzi = track.find('tarAzi').text
tarEli = track.find('tarEli').text
df = df.append(pd.Series([id,number, longitude, latitude, altitude,yaw, pitch, roll, tarRng, tarAzi, tarEli],
index=['id','number', 'longitude', 'latitude','altitude', 'yaw', 'pitch', 'roll',
'tarRng', 'tarAzi', 'tarEli']), ignore_index=True)
df.to_excel('E:/replay/data/trajectory1.xlsx', index=False)
0.13156269490718842
0.08380892127752304
0.08336402475833893
0.08330120146274567
0.06786628067493439
0.06781288981437683
0.06777195632457733
0.06775036454200745
0.06773287802934647
0.06773624569177628
0.06772735714912415
0.06772556155920029
0.06772372871637344
0.06772041320800781
0.06771867722272873
0.06771715730428696
0.06771635264158249
0.06771714985370636
0.0677139014005661
0.06771580129861832
0.0677129402756691
0.06771411001682281
0.06771273165941238
0.0677129328250885
0.06771278381347656
0.06771276146173477
0.06771276146173477
0.06771276891231537
0.009751547127962112
0.009530491195619106
0.009525801986455917
0.009523127228021622
0.009520863182842731
0.009519031271338463
0.00951846968382597
0.009516251273453236
0.009514686651527882
0.009514556266367435
0.009514677338302135
0.0095140989869833
0.009513485245406628
0.00951301772147417
0.009512774646282196
0.009512780234217644
0.009512978605926037
0.009513217024505138
0.00951334647834301
0.009513288736343384
0.009513027034699917
0.009512611664831638
0.00951218232512474
0.009511832147836685
0.00951155461370945
0.009511313401162624
0.009511078707873821
0.009510821662843227
0.009510600008070469
0.00951029546558857
0.00951030757278204
0.009509805589914322
0.009510057047009468
0.009509586729109287
0.009509543888270855
0.009509347379207611
0.009509450756013393
0.009509209543466568
0.009509430266916752
0.00950931292027235
0.009509033523499966
0.009509569965302944
0.009509153664112091
0.009509089402854443
0.009509126655757427
0.009509110823273659
0.009509342722594738
0.009509074501693249
0.009509212337434292
0.009509410709142685
0.009509270079433918
0.009509287774562836
0.009509256109595299
0.009509343653917313
0.009509437717497349
0.00950941164046526
0.009509376250207424
0.009509420022368431
0.009509126655757427
0.00950985960662365
0.009506545960903168
0.009508593007922173
0.009508511051535606
0.00950886495411396
0.009508886374533176
0.009508845396339893
0.009508797898888588
0.009508750401437283
0.009508705697953701
0.009508660063147545
0.009508607909083366
0.009508557617664337
# Default ignored files
/shelf/
/workspace.xml
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
<option value="N806" />
<option value="N803" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/multiple_objective.iml" filepath="$PROJECT_DIR$/.idea/multiple_objective.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
import numpy as np
from numpy.linalg import LinAlgError
from numpy import seterr
seterr(all='raise')
def get_toa_gdop(bs_list, xyz):
"""
compute the gdop of the toa
:param bs_list: the base station coordinate
:param xyz: the location coordinate of the tag
:return: the gdop value
"""
bs_n = len(bs_list)
if bs_n < 3:
return None
h1 = np.mat(np.zeros((bs_n, 3)))
for i in range(0, len(bs_list)):
ri = np.sqrt((bs_list[i][0] - xyz[0]) ** 2 +
(bs_list[i][1] - xyz[1]) ** 2)
if ri == 0:
h1[i, 0] = 0
h1[i, 1] = 0
h1[i, 2] = 1
# h1[i, 3] = 1
else:
h1[i, 0] = (bs_list[i][0] - xyz[0]) / ri
h1[i, 1] = (bs_list[i][1] - xyz[1]) / ri
h1[i, 2] = 1
# h1[i, 3] = 1
m_tmp = h1.T * h1
gdop_value = None
try:
g = m_tmp.I
gdop_value = np.sqrt(g[0, 0] + g[1, 1])
# print(gdop_value)
finally:
return gdop_value
# 计算GDOP 不考虑时钟误差版本即DOP
def calculate_gdop(uavs, estimate_value):
"""
# :param point: 待定位点真实坐标
:param uavs: 无人机坐标集
:param estimate_value: 解算出的坐标
:return: gdop
"""
# estimate_value.append(0)
estimate_value=[estimate_value[0],estimate_value[1],0]
var1 = np.array(uavs) - estimate_value
# 计算距离列向量
d_estimate = (np.sum(var1**2, axis=1)**0.5).reshape(-1, 1)
# 计算visible MATRIX
H = var1 / d_estimate
GDOP = float('inf')
try:
GDOP = np.trace(np.linalg.inv(np.dot(np.transpose(H), H))) ** 0.5
except:
GDOP=float('inf')
finally:
return GDOP
if __name__ == '__main__':
bs_list=[[1,1,1],[2,3,4],[6,6,5]]
bs_list2 = [[1, 3, 3], [3, 1, 3], [5, 4, 3]]
xyz=[3,3.167,0]
print(calculate_gdop(bs_list,xyz))
print(get_toa_gdop(bs_list2,xyz))
\ No newline at end of file
import math
import numpy as np
from sklearn.cluster import KMeans
import km
import GDOP
from itertools import combinations
from pprint import pprint
import tool
import copy
class Match:
def __init__(self,users,uavs):
self.id = id
# self.cpUsers,self.pUsers,self.cUsers=Users.getAllUsers()
self.allUsers =users
# 4台无人机,每台服务20个人
self.uavs = uavs
self.serveMax = 20
self.distance= self.getUavAndUserDistance()
self.uavConnectNum = [0 for col in range(len(self.uavs))]
self.uav_group = list(combinations(self.uavs, 3))
self.snr_thre=0
self.Pmax=0.1
self.p_connection, self.c_connection = self.get_all_match()
self.uav_to_user,self.uav_to_cuser,self.uav_to_puser = self.get_uav_to_user()
def getUavInitialPos(self, k):
model = KMeans(n_clusters=k, # 聚类簇数
random_state=1, # 决定质心初始化的随机数生成,使用int使随机性具有确定性。
max_iter=300, # 执行一次k-means算法所进行的最大迭代数,默认300
).fit(self.allUsers)
center = model.cluster_centers_
uavs = []
# center=[[250, 250], [250, 750], [750, 250], [750, 750]]
for item in center:
height = 100
position = [int(item[0]), int(item[1]), height]
uavs.append(position)
# print(center)
return uavs
def getUavAndUserDistance(self):
user_num = len(self.allUsers)
uav_num = len(self.uavs)
distance = np.zeros((user_num, uav_num), dtype=np.float16)
for i in range(user_num):
for j in range(uav_num):
distance[i][j] = self.calculateDistance(self.allUsers[i], self.uavs[j])
return distance
def calculateDistance(self, user, uav):
distanceSquare = (user[0] - uav[0]) ** 2 + (user[1] - uav[1]) ** 2 + uav[2] ** 2
return math.sqrt(distanceSquare)
def get_appropriate_uavs(self, user):
uavs = [k for k, v in enumerate(self.uavConnectNum) if v < self.serveMax]
appropriate_uavs = []
for uav in uavs:
snr = tool.cal_snr(self.uavs[uav], user, self.Pmax)
if snr > self.snr_thre:
appropriate_uavs.append(uav)
return appropriate_uavs
# 获取定位匹配
def getPositionConnection(self, users):
# for user in users:
# 计算该user能通信的uav
# 获得uav组合
# 计算user与uav组合的gdop
# 选择最小的gdop组合,用字典保存,并且更新服务次数
user_to_uav_group = {}
for i in range(len(users)):
uavs = self.get_appropriate_uavs(users[i])
uav_group = list(combinations(uavs, 3))
gdop_min = float('inf')
index = 0
for j in range(len(uav_group)):
uavs_pos = [self.uavs[uav_group[j][0]], self.uavs[uav_group[j][1]], self.uavs[uav_group[j][2]]]
gdop_current = GDOP.calculate_gdop(uavs_pos, copy.copy(users[i]))
if gdop_current < gdop_min:
gdop_min = gdop_current
index = j
user_to_uav_group[i] = uav_group[index]
self.update_serve_num(uav_group[index])
return user_to_uav_group
# 纯定位用户的匹配
def getPConnection(self):
# cp_connection=self.getCPConnection()
p_connection = self.getPositionConnection(self.allUsers)
return p_connection
def getCommunicationConnection(self):
user_num = len(self.allUsers)
uavs = [k for k, v in enumerate(self.uavConnectNum) if v < self.serveMax]
uav_num = len(self.uavs)
distance_sum = self.distance.sum(axis=1) # 按照行求和
# print(distance_sum)
weight = np.zeros((user_num, uav_num), dtype=np.float16)
graph = []
for i in range(user_num):
for j in uavs:
# weight[i][j]=-self.distance_c[i][j]/(distance_sum[i]-self.distance_c[i][j])
weight[i][j] = -self.distance[i][j]
dic = {}
for i in range(user_num):
for j in uavs:
for number in range(self.serveMax - self.uavConnectNum[j]):
graph.append((i, j + 100 * number, weight[i][j]))
dic[j + 100 * number] = j
connection = km.run_kuhn_munkres(graph)
c_connection = {}
for connect in connection:
c_connection[connect[0]] = dic[connect[1]]
self.update_serve_num_by_c_connection(c_connection)
return c_connection
def update_serve_num(self, uavs):
for u in uavs:
self.uavConnectNum[u] += 1
# 根据通信连接更新服务次数
def update_serve_num_by_c_connection(self, c_connection):
for key in c_connection:
self.uavConnectNum[c_connection[key]] += 1
def get_all_match(self):
p_connection = self.getPConnection()
c_connection = self.getCommunicationConnection()
return p_connection, c_connection
def get_uav_to_user(self):
uav_to_user = {}
uav_to_cuser={}
uav_to_puser={}
for i in range(len(self.uavs)):
uav_to_user[i] = []
uav_to_cuser[i]=[]
uav_to_puser[i]=[]
# 编号规则:定位0-19,通信100-119
for key in self.p_connection:
for uav_index in self.p_connection[key]:
uav_to_user[uav_index].append(key)
uav_to_puser[uav_index].append(key)
for key in self.c_connection:
uav_to_user[self.c_connection[key]].append(key + 100)
uav_to_cuser[self.c_connection[key]].append(key)
return uav_to_user,uav_to_cuser,uav_to_puser
def dbmToW(self, p):
return pow(10, p / 10) / 1000
if __name__ == '__main__':
m = Match()
# pprint(m.getPConnection())
# print(m.get_uav_to_user())
print(m.p_connection,m.c_connection)
print(m.uav_to_user)
# pprint(m.getPConnection())
# pprint(m.getCommunicationConnection())
print(m.uavConnectNum)
print(m.get_min_speb())
# Program Name: NSGA-II.py
# Description: This is a python implementation of Prof. Kalyanmoy Deb's popular NSGA-II algorithm
# Author: Haris Ali Khan
# Supervisor: Prof. Manoj Kumar Tiwari
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import time
#计算用户平均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])
# print(gdop)
sum+=gdop
return -sum/len(users)
def punish(power,p_rest):
f = 0
i=0
for p in power:
dis = sum(p) - p_rest[i]
if dis > 0.001:
f += 10 ** (dis * 100)
for p_singe in p: # 功率要大于0
dis1 = 0 - p_singe
if dis1>0:
f += 10 ** max(0, dis1 * 100)
i+=1
return f
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
#Function to sort by values
def sort_by_values(list1, values):
sorted_list = []
while(len(sorted_list)!=len(list1)):
if index_of(min(values),values) in list1:
sorted_list.append(index_of(min(values),values))
values[index_of(min(values),values)] = math.inf
return sorted_list
#Function to carry out NSGA-II's fast non dominated sort
def fast_non_dominated_sort(values1, values2):
#支配的节点
S=[[] for i in range(0,len(values1))]
front = [[]]
n=[0 for i in range(0,len(values1))]#被支配的数量
rank = [0 for i in range(0, len(values1))]#等级
for p in range(0,len(values1)):
S[p]=[]
n[p]=0
for q in range(0, len(values1)):
if (values1[p] > values1[q] and values2[p] > values2[q]) or (values1[p] >= values1[q] and values2[p] > values2[q]) or (values1[p] > values1[q] and values2[p] >= values2[q]):
if q not in S[p]:
S[p].append(q)
elif (values1[q] > values1[p] and values2[q] > values2[p]) or (values1[q] >= values1[p] and values2[q] > values2[p]) or (values1[q] > values1[p] and values2[q] >= values2[p]):
n[p] = n[p] + 1
if n[p]==0:
rank[p] = 0
if p not in front[0]:
front[0].append(p)
i = 0
while(front[i] != []):
Q=[]
for p in front[i]:
for q in S[p]:
n[q] =n[q] - 1
if( n[q]==0):
rank[q]=i+1
if q not in Q:
Q.append(q)
i = i+1
front.append(Q)
del front[len(front)-1]
return front,rank
#Function to calculate crowding distance
def crowding_distance(values1, values2, front):
distance = [0 for i in range(0,len(front))]
#从小到大排序
sorted1 = sort_by_values(front, values1[:])
sorted2 = sort_by_values(front, values2[:])
distance[0] = 4444444444444444
distance[len(front) - 1] = 4444444444444444
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted1[k+1]] - values1[sorted1[k-1]])/(max(values1)-min(values1))
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values2[sorted2[k+1]] - values2[sorted2[k-1]])/(max(values2)-min(values2))
return distance
#初始化无人机位置
def init(pop_size,k,users):
min_pos=0
max_pos=1000
pos_solution=[]
p_solution=[]
for i in range(pop_size):
uavs_pos=[[min_pos+(max_pos-min_pos)*random.random(),min_pos+(max_pos-min_pos)*random.random(),100] for i in range(k)]
p_alloc=init_p(uavs_pos,users)
pos_solution.append(uavs_pos)
p_solution.append(p_alloc)
# print(pos_solution)
return pos_solution,p_solution
def get_dis(i,uavs_pos,users,uav_to_user):
dis=[]
for k in uav_to_user[i]:
dis.append(tool.calculate_3d_distance(uavs_pos[i],users[k]))
return dis
def init_p(uavs_pos,users):
c_association=tool.get_c_association(users,uavs_pos,math.ceil(len(users)/len(uavs_pos)))
uav_to_user=tool.get_uav_to_user(c_association,uavs_pos)
# print(uav_to_user)
p_association = tool.get_p_association(users, uavs_pos, c_association, len(users) * 2)
p_rest=tool.get_rest_p(users,uavs_pos,p_association)
# print(p_rest)
p_alloc=[]
for i in range(len(uavs_pos)):
#归一化生成 功率
dis=get_dis(i,uavs_pos,users,uav_to_user)
# p=[random.randint(1,len(uav_to_user[i])) for i in range(len(uav_to_user[i]))]
p_new=[0 for i in range(len(users))]
for j in range(len(uav_to_user[i])):
p_new[uav_to_user[i][j]]=dis[j]/sum(dis)*p_rest[i]
# p_new.append(p[j]/sum(p)*p_rest[i])
p_alloc.append(p_new)
# p_alloc.append(np.random.uniform(0, p_rest[i] / len(uav_to_user[i]), (len(uav_to_user[i]))))
return p_alloc
def cross_over_old(pos_solution1,pos_solution2):
child1 = [pos_solution2[j] if random.random() < 0.5 else pos_solution1[j]
for j in range(len(pos_solution2))]
return child1
def cross_over_stage(pos_solution1,pos_solution2,iter,iter_max):
p_cross=get_beta_stage(iter,iter_max)
child1 = [pos_solution2[j] if random.random() < p_cross else pos_solution1[j]
for j in range(len(pos_solution2))]
return child1
#交叉 pos_solution1=[[],[],[]]
def cross_over(pos_solution1,pos_solution2,iter,iter_max):
p_cross=get_beta(iter,iter_max)
child1 = [pos_solution2[j] if random.random() < p_cross else pos_solution1[j]
for j in range(len(pos_solution2))]
# for i in range(len(pos_solution1)):
# pos1 = []
# pos2=[]
# beta = get_beta()
#
# for j in range(len(pos_solution1[i])):
# if j<len(pos_solution1[i])-1:
# x1 = (pos_solution1[i][j] + pos_solution2[i][j]) / 2
# x2 = abs((pos_solution1[i][j] - pos_solution2[i][j]) / 2)
# x1=x1 + beta * x2
# x2=abs(x1 - beta * x2)
# pos1.append(x1)
# pos2.append(x2)
# else:
# pos1.append(100)
# pos2.append(100)
# child1.append(pos1)
# child2.append(pos2)
return child1
def cross_over2(pos_solution1,pos_solution2,iter,iter_max):
p_cross=get_beta2(iter,iter_max)
child1 = [pos_solution2[j] if random.random() < p_cross else pos_solution1[j]
for j in range(len(pos_solution2))]
return child1
def get_beta_old(crossover_param=2):
u = random.random()
if u <= 0.5:
return (2 * u) ** (1 / (crossover_param + 1))
return (2 * (1 - u)) ** (-1 / (crossover_param + 1))
def get_beta_stage(iter,iter_max):
if iter/iter_max<=0.34:
return 0.9
elif iter/iter_max>0.34 and iter/iter_max<=0.67:
return 0.4
else:
return 0.1
def get_beta(iter,iter_max,p_max=0.9,p_min=0.1,crossover_param=2):
return p_max-(p_max-p_min)*iter/iter_max
# u = random.random()
# if u <= 0.5:
# return (2 * u) ** (1 / (crossover_param + 1))
# return (2 * (1 - u)) ** (-1 / (crossover_param + 1))
def get_beta2(iter,iter_max,p_max=0.9,p_min=0.1,crossover_param=2):
return p_min+(p_max-p_min)/2*(1+math.cos(iter/iter_max*math.pi))
def get_delta(iter,iter_max,p_max=0.1,p_min=0.01,mutation_param=5):
u = random.random()
a=random.random()
delta=p_max-(p_max-p_min)*iter/iter_max
if a<0.5:
return u,delta
return u,-delta
# if u < 0.5:
# return u, (2 * u) ** (1 / (mutation_param + 1)) - 1
# return u, 1 - (2 * (1 - u)) ** (1 / (mutation_param + 1))
def get_delta2(iter,iter_max,p_max=0.1,p_min=0.01,mutation_param=5):
u = random.random()
a=random.random()
delta=p_min+(p_max-p_min)/2*(1+math.cos(iter/iter_max*math.pi))
if a<0.5:
return u,delta
return u,-delta
def get_delta_stage(iter,iter_max):
u = random.random()
a=random.random()
if iter / iter_max <= 0.34:
delta = 0.1
elif iter / iter_max > 0.34 and iter / iter_max <= 0.67:
delta = 0.05
else:
delta = 0.01
if a<0.5:
return u,delta
return u,-delta
# if u < 0.5:
# return u, (2 * u) ** (1 / (mutation_param + 1)) - 1
# return u, 1 - (2 * (1 - u)) ** (1 / (mutation_param + 1))
def get_delta_old(mutation_param=5):
u = random.random()
return u,0.05
# if u < 0.5:
# return u, (2 * u) ** (1 / (mutation_param + 1)) - 1
# return u, 1 - (2 * (1 - u)) ** (1 / (mutation_param + 1))
def mutate_old(child,variables_range):
u, delta = get_delta_old()
child_new = []
if u < 0.5:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x = child[i][j] + delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x = child[i][j] + delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j < len(child_new[i]) - 1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def mutate_stage(child,variables_range,iter,iter_max):
u, delta = get_delta_stage(iter,iter_max)
child_new=[]
if u < 0.5:
for i in range(len(child)):
pos=[]
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x=child[i][j]+ delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j<len(child[i])-1:
x= child[i][j] +delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j<len(child_new[i])-1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def mutate(child,variables_range,iter,iter_max):
u, delta = get_delta(iter,iter_max)
child_new=[]
if u < 0.5:
for i in range(len(child)):
pos=[]
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x=child[i][j]+ delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j<len(child[i])-1:
x= child[i][j] +delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j<len(child_new[i])-1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def mutate2(child,variables_range,iter,iter_max):
u, delta = get_delta2(iter,iter_max)
child_new=[]
if u < 0.5:
for i in range(len(child)):
pos=[]
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x=child[i][j]+ delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j<len(child[i])-1:
x= child[i][j] +delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j<len(child_new[i])-1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def get_function_values(pop_size,pos_solution,p_solution,users):
function1_values = []
function2_values = []
punish_values = []
for i in range(pop_size):
uavs_pos = pos_solution[i]
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_rest = tool.get_rest_p(users, uavs_pos, p_association)
function1_values.append(function_snr(users, pos_solution[i], c_association, p_solution[i]))
function2_values.append(function_gdop(users, uavs_pos, c_association, p_association, ))
punish_values.append(punish(p_solution[i], p_rest))
return function1_values,function2_values,punish_values
def tournament(pos_solution,non_dominated_sorted_solution,rank,distance):
a1 = random.randint(0, len(pos_solution) - 1)
b1=a1
while b1==a1:
b1 = random.randint(0, len(pos_solution) - 1)
participants = [pos_solution[a1],pos_solution[b1]]
best = None
for participant in participants:
if best is None or crowding_operator(a1,b1,non_dominated_sorted_solution,rank,distance) == 1:
best = participant
return best
def get_f_by_pos(pos,users):
c_association = tool.get_c_association(users, pos, math.ceil(len(users) / len(pos)))
p_association = tool.get_p_association(users, pos, c_association, len(users) * 2 / len(pos))
p = init_p(pos, users)
function1_value=function_snr(users, pos, c_association, p)
function2_value=function_gdop(users, pos, c_association, p, )
return function1_value,function2_value
def crowding_operator(index1,index2,non_dominated_sorted_solution,rank,distance):
rank1=rank[index1]#index1的等级
rank2=rank[index2]
distance1=0
distance2=0
for i in range(len(non_dominated_sorted_solution[rank1])):
if non_dominated_sorted_solution[rank1][i]==index1:
distance1=distance[rank1][i]
for i in range(len(non_dominated_sorted_solution[rank2])):
if non_dominated_sorted_solution[rank2][i]==index2:
distance2=distance[rank2][i]
if rank1<rank2 or (rank1==rank2 and distance1>distance2):
return 1
else:
return 0
def drawResultAndIter(resultAndIter):
f, ax = plt.subplots(1, 1)
plt.plot(resultAndIter)
ax.set_xlabel('iteration')
ax.set_ylabel('fitness')
plt.show()
if __name__ == '__main__':
num=[5, 7, 4, 4, 4, 4, 4, 8, 9, 7, 9, 8, 8, 9, 9, 9, 11, 13, 14, 12, 15, 14, 15, 14, 14, 14, 12, 14, 14, 15, 15, 15, 19, 19, 19, 19, 18, 18, 19, 15, 17, 17, 17, 17, 17, 18, 19, 19, 17, 17, 18, 20, 15, 16, 16, 16, 17, 17, 17, 18, 18, 19, 19, 19, 20, 22, 25, 25, 25, 26, 26, 26, 26, 27, 28, 30, 21, 22, 23, 24, 25, 26, 27, 27, 28, 29, 29, 29, 28, 28, 29, 29, 29, 29, 31, 30, 30, 26, 26, 27, 27, 27, 27, 27, 28, 29, 29, 29, 30, 33, 35, 35, 34, 36, 36, 39, 41, 40, 40, 41, 40, 42, 42, 42, 43, 43, 43, 46, 46, 48, 48, 52, 54, 54, 58, 59, 59, 60]
drawResultAndIter(num)
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import time
import NSGA2 as ns
import TS as ts
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=ns.init(pop_size,k,users)
# print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
function1_best=[]
function2_best=[]
solution_num=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=ns.get_function_values(pop_size,pos_solution,p_solution,users)
non_dominated_sorted_solution,rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(ns.crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
#todo 采用TS对父代每个个体进行搜索
# for index in range(len(pos_solution)):
# pos_solution[index]=ts.tabu_search(pos_solution[index],users,10)
# p_solution[index]=ns.init_p(pos_solution[index],users)
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
# child = ns.cross_over_old(parent1, parent2)
# child_mute = ns.mutate_old(child, pos_range)
child = ns.cross_over(parent1, parent2, gen_no, max_gen)
child_mute = ns.mutate(child, pos_range, gen_no, max_gen)
child_p=ns.init_p(child_mute,users)
#todo 对每个子代进行TS
# child_mute=ts.tabu_search(child_mute,users,10)
# child_p=ns.init_p(child_mute,users)
pos_solution2.append(child_mute)
p_solution2.append(child_p)
function1_values2, function2_values2, punish_values2 = ns.get_function_values(2*pop_size, pos_solution2, p_solution2,users)
non_dominated_sorted_solution2,rank2 = ns.fast_non_dominated_sort(function1_values2[:], function2_values2[:])
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
ns.crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = ns.sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
function1_best,function2_best,_=ns.get_function_values(len(pos_solution),pos_solution,
p_solution,users)
best_pos,rank=ns.fast_non_dominated_sort(function1_best[:], function2_best[:])
solution_num.append(len(best_pos[0]))
if len(best_pos[0]) >= pop_size:
break
# if len(best_pos[0])> 30:
# for index in range(len(pos_solution)):
# pos_solution[index] = ts.tabu_search(pos_solution[index], users, 5, rank[index], len(best_pos),gen_no,max_gen)
# p_solution[index] = ns.init_p(pos_solution[index], users)
# for r in range(1,len(best_pos)):#取所有支配解
# for index in best_pos[r]:
# pos_solution[index] = ts.tabu_search(pos_solution[index], users, 5, rank[index], len(best_pos))
# p_solution[index] = ns.init_p(pos_solution[index], users)
if len(best_pos[0])< pop_size/2:
# for r in range(0, len(best_pos)):
# for index in best_pos[r]:
# pos_solution[index] = ts.tabu_search(pos_solution[index], users, 1, len(best_pos[0]), 60,r,len(best_pos))
# p_solution[index] = ns.init_p(pos_solution[index], users)
for index in range(len(pos_solution)):
pos_solution[index] = ts.tabu_search(pos_solution[index], users, 1, len(best_pos[0]), pop_size,1,len(best_pos))
p_solution[index] = ns.init_p(pos_solution[index], users)
gen_no+=1
for i in range(len(best_pos[0])):
f1_best.append(function1_best[best_pos[0][i]])
f2_best.append(function2_best[best_pos[0][i]])
return f1_best,f2_best,solution_num
def compare_pop():
pop=[i for i in range(10,110,10)]
filename = "./data.csv"
print(pop)
times=[]
for i in pop:
run_time=run_pop(filename,i,150,3)
times.append(run_time)
print(times)
def run_pop(filename,pop_size,iter_max,uav_num):
users = Users.getUsers(filename)
start_time = time.time()
f1, f2, solution_num = main(users, pop_size, iter_max, uav_num)
end_time = time.time()
run_time = end_time - start_time
return run_time
def run(filename,pop_size,iter_max,uav_num):
users = Users.getUsers(filename)
start_time = time.time()
f1, f2, solution_num = main(users, pop_size, iter_max, uav_num)
end_time = time.time()
run_time = end_time - start_time
print(f1, f2)
print("程序运行时间为:", run_time)
print(solution_num)
plt.xlabel('Average snr', fontsize=12)
plt.ylabel('Average -gdop', fontsize=12)
plt.scatter(f1, f2, )
plt.show()
def run_ts():
filename = "./data.csv"
times=[]
for i in range(10):
run_time = run_pop(filename, 30, 150, 3)
print("time-",run_time)
times.append(run_time)
print(times)
if __name__ == '__main__':
# compare_pop()
filename="./data.csv"
# run_ts()
# print(run_pop(filename,60,200,3))
run(filename,60,200,3)
# users = Users.getUsers("./data.csv")
# start_time = time.time()
# f1,f2,solution_num=main(users,60,120,3)
# end_time = time.time()
# run_time = end_time - start_time
# print(f1, f2)
# print("程序运行时间为:", run_time)
# print(solution_num)
# plt.xlabel('Average snr', fontsize=12)
# plt.ylabel('Average -gdop', fontsize=12)
#
# plt.scatter(f1, f2, )
#
# plt.show()
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import time
import NSGA2 as ns
import TS as ts
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
#初始化无人机位置
def init(pop_size,k,users):
min_pos=0
max_pos=1000
pos_solution=[]
p_solution=[]
for i in range(pop_size):
uavs_pos=[[min_pos+(max_pos-min_pos)*random.random(),min_pos+(max_pos-min_pos)*random.random(),100] for i in range(k)]
p_alloc=init_p(uavs_pos,users)
pos_solution.append(uavs_pos)
p_solution.append(p_alloc)
# print(pos_solution)
return pos_solution,p_solution
def init_p(uavs_pos,users):
c_association=tool.get_c_association(users,uavs_pos,math.ceil(len(users)/len(uavs_pos)))
uav_to_user=tool.get_uav_to_user(c_association,uavs_pos)
# print(uav_to_user)
p_association = tool.get_p_association(users, uavs_pos, c_association, len(users) * 2)
p_rest=tool.get_rest_p(users,uavs_pos,p_association)
# print(p_rest)
p_alloc=[]
for i in range(len(uavs_pos)):
#平分功率
# p=[random.randint(1,len(uav_to_user[i])) for i in range(len(uav_to_user[i]))]
p_new=[0 for i in range(len(users))]
for j in range(len(uav_to_user[i])):
p_new[uav_to_user[i][j]]=1/len(uav_to_user[i])*p_rest[i]
# p_new.append(p[j]/sum(p)*p_rest[i])
p_alloc.append(p_new)
# p_alloc.append(np.random.uniform(0, p_rest[i] / len(uav_to_user[i]), (len(uav_to_user[i]))))
return p_alloc
def get_beta(crossover_param=2):
u = random.random()
if u <= 0.5:
return (2 * u) ** (1 / (crossover_param + 1))
return (2 * (1 - u)) ** (-1 / (crossover_param + 1))
def mutate(child,variables_range):
u, delta = get_delta()
child_new=[]
if u < 0.5:
for i in range(len(child)):
pos=[]
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x=child[i][j]+ delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j<len(child[i])-1:
x= child[i][j] +delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j<len(child_new[i])-1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def get_delta(mutation_param=5):
u = random.random()
if u < 0.5:
return u, (2 * u) ** (1 / (mutation_param + 1)) - 1
return u, 1 - (2 * (1 - u)) ** (1 / (mutation_param + 1))
def cross_over(pos_solution1,pos_solution2):
child1=[]
child2=[]
for i in range(len(pos_solution1)):
pos1 = []
pos2=[]
beta = get_beta()
for j in range(len(pos_solution1[i])):
if j<len(pos_solution1[i])-1:
x1 = (pos_solution1[i][j] + pos_solution2[i][j]) / 2
x2 = abs((pos_solution1[i][j] - pos_solution2[i][j]) / 2)
x1=x1 + beta * x2
x2=abs(x1 - beta * x2)
pos1.append(x1)
pos2.append(x2)
else:
pos1.append(100)
pos2.append(100)
child1.append(pos1)
child2.append(pos2)
u=random.random()
if u>0.5:
return child1
else:
return child2
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=init(pop_size,k,users)
# print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
function1_best=[]
function2_best=[]
solution_num=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=ns.get_function_values(pop_size,pos_solution,p_solution,users)
non_dominated_sorted_solution,rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(ns.crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
# child = ns.cross_over_old(parent1, parent2)
# child_mute = ns.mutate_old(child, pos_range)
# child = cross_over(parent1, parent2,)
# child_mute = mutate(child, pos_range)
child = ns.cross_over(parent1, parent2, gen_no, max_gen)
child_mute = ns.mutate(child, pos_range, gen_no, max_gen)
child_p=init_p(child_mute,users)
pos_solution2.append(child_mute)
p_solution2.append(child_p)
function1_values2, function2_values2, punish_values2 = ns.get_function_values(2*pop_size, pos_solution2, p_solution2,users)
non_dominated_sorted_solution2,rank2 = ns.fast_non_dominated_sort(function1_values2[:], function2_values2[:])
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
ns.crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = ns.sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
function1_best,function2_best,_=ns.get_function_values(len(pos_solution),pos_solution,
p_solution,users)
best_pos,rank=ns.fast_non_dominated_sort(function1_best[:], function2_best[:])
solution_num.append(len(best_pos[0]))
if len(best_pos[0]) == 60:
break
# if len(best_pos[0])> 30:
# for index in range(len(pos_solution)):
# pos_solution[index] = ts.tabu_search(pos_solution[index], users, 5, rank[index], len(best_pos),gen_no,max_gen)
# p_solution[index] = ns.init_p(pos_solution[index], users)
# for r in range(1,len(best_pos)):#取所有支配解
# for index in best_pos[r]:
# pos_solution[index] = ts.tabu_search(pos_solution[index], users, 5, rank[index], len(best_pos))
# p_solution[index] = ns.init_p(pos_solution[index], users)
if len(best_pos[0])< 30:
for r in range(1, len(best_pos)):
for index in best_pos[r]:
pos_solution[index] = ts.tabu_search(pos_solution[index], users, 1, len(best_pos[0]), 60)
p_solution[index] = ns.init_p(pos_solution[index], users)
# for index in range(len(pos_solution)):
# pos_solution[index] = ts.tabu_search(pos_solution[index], users, 5, gen_no, max_gen)
# p_solution[index] = ns.init_p(pos_solution[index], users)
gen_no+=1
for r in range(len(best_pos)):
for i in range(len(best_pos[r])):
f1_best.append(function1_best[best_pos[0][i]])
f2_best.append(function2_best[best_pos[0][i]])
return f1_best,f2_best,solution_num
if __name__ == '__main__':
users = Users.getUsers("./data.csv")
start_time = time.time()
f1,f2,solution_num=main(users,60,150,3)
end_time = time.time()
run_time = end_time - start_time
print(f1, f2)
print("程序运行时间为:", run_time)
print(solution_num)
plt.xlabel('average snr', fontsize=12)
plt.ylabel('average -gdop', fontsize=12)
# plt.xlim(70, 81)
# plt.ylim(0,0.1)
plt.scatter(f1, f2, )
plt.show()
# Program Name: NSGA-II.py
# Description: This is a python implementation of Prof. Kalyanmoy Deb's popular NSGA-II algorithm
# Author: Haris Ali Khan
# Supervisor: Prof. Manoj Kumar Tiwari
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import time
import NSGA2 as ns
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=ns.init(pop_size,k,users)
print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
function1_best=[]
function2_best=[]
solution_num=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=ns.get_function_values(pop_size,pos_solution,p_solution,users)
# print(function1_values)
# print(function2_values)
# print(punish_values)
non_dominated_sorted_solution,rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
# print("等级")
# print(rank)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(ns.crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
# child = ns.cross_over_old(parent1, parent2)
# child_mute = ns.mutate_old(child, pos_range)
child = ns.cross_over(parent1, parent2, gen_no, max_gen)
child_mute = ns.mutate(child, pos_range, gen_no, max_gen)
child_p=ns.init_p(child_mute,users)
pos_solution2.append(child_mute)
p_solution2.append(child_p)
# child1,child2=cross_over(parent1,parent2)
# child1_mute=mutate(child1,pos_range)
# child2_mute=mutate(child2,pos_range)
# child1_p=init_p(child1_mute,users)
# child2_p=init_p(child2_mute,users)
# pos_solution2.append(child1_mute)
# pos_solution2.append(child2_mute)
# p_solution2.append(child1_p)
# p_solution2.append(child2_p)
function1_values2, function2_values2, punish_values2 = ns.get_function_values(2*pop_size, pos_solution2, p_solution2,users)
non_dominated_sorted_solution2,rank2 = ns.fast_non_dominated_sort(function1_values2[:], function2_values2[:])
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
ns.crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = ns.sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
function1_best,function2_best,_=ns.get_function_values(len(pos_solution),pos_solution,
p_solution,users)
best_pos,_=ns.fast_non_dominated_sort(function1_best[:], function2_best[:])
solution_num.append(len(best_pos[0]))
# if len(best_pos[0])==60:
# break
gen_no+=1
for r in range(len(best_pos)):
for i in range(len(best_pos[r])):
f1_best.append(function1_best[best_pos[r][i]])
f2_best.append(function2_best[best_pos[r][i]])
# for i in range(len(best_pos[0])):
# f1_best.append(function1_best[best_pos[0][i]])
# f2_best.append(function2_best[best_pos[0][i]])
return f1_best,f2_best,solution_num
def run_pop(filename,pop_size,iter_max,uav_num):
users = Users.getUsers(filename)
start_time = time.time()
f1, f2, solution_num = main(users, pop_size, iter_max, uav_num)
end_time = time.time()
run_time = end_time - start_time
return run_time
def run_linear():
filename = "./data.csv"
times=[]
for i in range(10):
run_time = run_pop(filename, 30, 150, 3)
print("time-",run_time)
times.append(run_time)
print(times)
def run(filename,pop_size,iter_max,uav_num):
users = Users.getUsers(filename)
start_time = time.time()
f1, f2, solution_num = main(users, pop_size, iter_max, uav_num)
end_time = time.time()
run_time = end_time - start_time
print(f1, f2)
print("程序运行时间为:", run_time)
print(solution_num)
plt.xlabel('Average snr', fontsize=12)
plt.ylabel('Average -gdop', fontsize=12)
plt.scatter(f1, f2, )
plt.show()
if __name__ == '__main__':
#60 200 3 3架无人机
#30 200 4 4架无人机
# run_linear()
filename = "./data.csv"
run(filename,60,200,3)
# users = Users.getUsers("./data-20.csv")
# start_time = time.time()
# f1,f2,solution_num=main(users,30,200,3)
# end_time = time.time()
# run_time = end_time - start_time
# print(f1, f2)
# print("程序运行时间为:", run_time)
# print(solution_num)
# plt.xlabel('average snr', fontsize=12)
# plt.ylabel('average -gdop', fontsize=12)
# # plt.xlim(70, 81)
# # plt.ylim(0,0.1)
# plt.scatter(f1, f2, )
#
# plt.show()
# Program Name: NSGA-II.py
# Description: This is a python implementation of Prof. Kalyanmoy Deb's popular NSGA-II algorithm
# Author: Haris Ali Khan
# Supervisor: Prof. Manoj Kumar Tiwari
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
#First function to optimize
def function1(x):
value = -x**2
return value
#Second function to optimize
def function2(x):
value = -(x-2)**2
return value
#计算用户平均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])
# print(gdop)
sum+=gdop
return -sum/len(users)
def punish(power,p_rest):
f = 0
i=0
for p in power:
dis = sum(p) - p_rest[i]
if dis > 0.001:
f += 10 ** (dis * 100)
for p_singe in p: # 功率要大于0
dis1 = 0 - p_singe
if dis1>0:
f += 10 ** max(0, dis1 * 100)
i+=1
return f
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
#Function to sort by values
def sort_by_values(list1, values):
sorted_list = []
while(len(sorted_list)!=len(list1)):
if index_of(min(values),values) in list1:
sorted_list.append(index_of(min(values),values))
values[index_of(min(values),values)] = math.inf
return sorted_list
#Function to carry out NSGA-II's fast non dominated sort
def fast_non_dominated_sort(values1, values2):
#支配的节点
S=[[] for i in range(0,len(values1))]
front = [[]]
n=[0 for i in range(0,len(values1))]#被支配的数量
rank = [0 for i in range(0, len(values1))]#等级
for p in range(0,len(values1)):
S[p]=[]
n[p]=0
for q in range(0, len(values1)):
if (values1[p] > values1[q] and values2[p] > values2[q]) or (values1[p] >= values1[q] and values2[p] > values2[q]) or (values1[p] > values1[q] and values2[p] >= values2[q]):
if q not in S[p]:
S[p].append(q)
elif (values1[q] > values1[p] and values2[q] > values2[p]) or (values1[q] >= values1[p] and values2[q] > values2[p]) or (values1[q] > values1[p] and values2[q] >= values2[p]):
n[p] = n[p] + 1
if n[p]==0:
rank[p] = 0
if p not in front[0]:
front[0].append(p)
i = 0
while(front[i] != []):
Q=[]
for p in front[i]:
for q in S[p]:
n[q] =n[q] - 1
if( n[q]==0):
rank[q]=i+1
if q not in Q:
Q.append(q)
i = i+1
front.append(Q)
del front[len(front)-1]
return front,rank
#Function to calculate crowding distance
def crowding_distance(values1, values2, front):
distance = [0 for i in range(0,len(front))]
#从小到大排序
sorted1 = sort_by_values(front, values1[:])
sorted2 = sort_by_values(front, values2[:])
distance[0] = 4444444444444444
distance[len(front) - 1] = 4444444444444444
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted1[k+1]] - values1[sorted1[k-1]])/(max(values1)-min(values1))
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values2[sorted2[k+1]] - values2[sorted2[k-1]])/(max(values2)-min(values2))
return distance
#初始化无人机位置
def init(pop_size,k,users):
min_pos=0
max_pos=1000
pos_solution=[]
p_solution=[]
for i in range(pop_size):
uavs_pos=[[min_pos+(max_pos-min_pos)*random.random(),min_pos+(max_pos-min_pos)*random.random(),100] for i in range(k)]
p_alloc=init_p(uavs_pos,users)
pos_solution.append(uavs_pos)
p_solution.append(p_alloc)
# print(pos_solution)
return pos_solution,p_solution
def get_dis(i,uavs_pos,users,uav_to_user):
dis=[]
for k in uav_to_user[i]:
dis.append(tool.calculate_3d_distance(uavs_pos[i],users[k]))
return dis
def init_p(uavs_pos,users):
c_association=tool.get_c_association(users,uavs_pos,math.ceil(len(users)/len(uavs_pos)))
uav_to_user=tool.get_uav_to_user(c_association,uavs_pos)
print(uav_to_user)
p_association = tool.get_p_association(users, uavs_pos, c_association, len(users) * 2)
p_rest=tool.get_rest_p(users,uavs_pos,p_association)
# print(p_rest)
p_alloc=[]
for i in range(len(uavs_pos)):
#归一化生成 功率
dis=get_dis(i,uavs_pos,users,uav_to_user)
# p=[random.randint(1,len(uav_to_user[i])) for i in range(len(uav_to_user[i]))]
p_new=[0 for i in range(len(users))]
for j in range(len(uav_to_user[i])):
p_new[uav_to_user[i][j]]=1/len(uav_to_user[i])*p_rest[i]
# p_new.append(p[j]/sum(p)*p_rest[i])
p_alloc.append(p_new)
# p_alloc.append(np.random.uniform(0, p_rest[i] / len(uav_to_user[i]), (len(uav_to_user[i]))))
return p_alloc
#交叉 pos_solution1=[[],[],[]]
def cross_over(pos_solution1,pos_solution2):
child1=[]
child2=[]
for i in range(len(pos_solution1)):
pos1 = []
pos2=[]
beta = get_beta()
for j in range(len(pos_solution1[i])):
if j<len(pos_solution1[i])-1:
x1 = (pos_solution1[i][j] + pos_solution2[i][j]) / 2
x2 = abs((pos_solution1[i][j] - pos_solution2[i][j]) / 2)
x1=x1 + beta * x2
x2=abs(x1 - beta * x2)
pos1.append(x1)
pos2.append(x2)
else:
pos1.append(100)
pos2.append(100)
child1.append(pos1)
child2.append(pos2)
return child1,child2
def cross_over_p(p_solution1,p_solution2):
child1 = []
child2 = []
for i in range(len(p_solution1)):
p1 = []
p2 = []
beta = get_beta()
for j in range(len(p_solution1[i])):
x1 = (p_solution1[i][j] + p_solution2[i][j]) / 2
x2 = abs((p_solution1[i][j] - p_solution2[i][j]) / 2)
x1 = x1 + beta * x2
x2 = abs(x1 - beta * x2)
p1.append(x1)
p2.append(x2)
child1.append(p1)
child2.append(p2)
return child1,child2
def get_beta(crossover_param=2):
u = random.random()
if u <= 0.5:
return (2 * u) ** (1 / (crossover_param + 1))
return (2 * (1 - u)) ** (-1 / (crossover_param + 1))
def mutate(child,variables_range):
u, delta = get_delta()
child_new=[]
if u < 0.5:
for i in range(len(child)):
pos=[]
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x=child[i][j]+ delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j<len(child[i])-1:
x= child[i][j] +delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j<len(child_new[i])-1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def get_delta(mutation_param=5):
u = random.random()
if u < 0.5:
return u, (2 * u) ** (1 / (mutation_param + 1)) - 1
return u, 1 - (2 * (1 - u)) ** (1 / (mutation_param + 1))
def get_function_values(pop_size,pos_solution,p_solution):
function1_values = []
function2_values = []
punish_values = []
for i in range(pop_size):
uavs_pos = pos_solution[i]
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_rest = tool.get_rest_p(users, uavs_pos, p_association)
function1_values.append(function_snr(users, pos_solution[i], c_association, p_solution[i]))
function2_values.append(function_gdop(users, uavs_pos, c_association, p_association, ))
punish_values.append(punish(p_solution[i], p_rest))
return function1_values,function2_values,punish_values
def tournament(pos_solution,non_dominated_sorted_solution,rank,distance):
a1 = random.randint(0, len(pos_solution) - 1)
b1=a1
while b1==a1:
b1 = random.randint(0, len(pos_solution) - 1)
participants = [pos_solution[a1],pos_solution[b1]]
best = None
for participant in participants:
if best is None or crowding_operator(a1,b1,non_dominated_sorted_solution,rank,distance) == 1:
best = participant
return best
def get_f_by_pos(pos):
c_association = tool.get_c_association(users, pos, math.ceil(len(users) / len(pos)))
p_association = tool.get_p_association(users, pos, c_association, len(users) * 2 / len(pos))
p = init_p(pos, users)
function1_value=function_snr(users, pos, c_association, p)
function2_value=function_gdop(users, pos, c_association, p, )
return function1_value,function2_value
def crowding_operator(index1,index2,non_dominated_sorted_solution,rank,distance):
rank1=rank[index1]#index1的等级
rank2=rank[index2]
distance1=0
distance2=0
for i in range(len(non_dominated_sorted_solution[rank1])):
if non_dominated_sorted_solution[rank1][i]==index1:
distance1=distance[rank1][i]
for i in range(len(non_dominated_sorted_solution[rank2])):
if non_dominated_sorted_solution[rank2][i]==index2:
distance2=distance[rank2][i]
if rank1<rank2 or (rank1==rank2 and distance1>distance2):
return 1
else:
return 0
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=init(pop_size,k,users)
print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=get_function_values(pop_size,pos_solution,p_solution)
# for i in range(pop_size):
# uavs_pos=pos_solution[i]
# 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_rest=tool.get_rest_p(users, uavs_pos, p_association)
# function1_values.append(function_snr(users,pos_solution[i],c_association,p_solution[i]))
# function2_values.append(function_gdop(users,uavs_pos,c_association,p_association,))
# punish_values.append(punish(p_solution[i],p_rest))
print(function1_values)
print(function2_values)
print(punish_values)
non_dominated_sorted_solution,rank = fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
print("等级")
print(rank)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
child1,child2=cross_over(parent1,parent2)
child1_mute=mutate(child1,pos_range)
child2_mute=mutate(child2,pos_range)
child1_p=init_p(child1_mute,users)
child2_p=init_p(child2_mute,users)
pos_solution2.append(child1_mute)
pos_solution2.append(child2_mute)
p_solution2.append(child1_p)
p_solution2.append(child2_p)
function1_values2, function2_values2, punish_values2 = get_function_values(2*pop_size, pos_solution2, p_solution2)
print(function1_values2)
print(function2_values2)
print(punish_values2)
non_dominated_sorted_solution2,rank2 = fast_non_dominated_sort(function1_values2[:], function2_values2[:])
print(non_dominated_sorted_solution2)
print(rank2)
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
# function1_last, function2_last, _ = get_function_values(len(solution), solution,
# p_solution_)
# non_dominated_sorted_solution = fast_non_dominated_sort(function1_last[:], function2_last[:])
# print(non_dominated_sorted_solution[0])
# pos_now=[solution[i] for i in non_dominated_sorted_solution[0]]
# p_now=[p_solution_[i] for i in non_dominated_sorted_solution[0]]
# best_pos.append(pos_now)
# best_p.append(p_now)
function1_best,function2_best,_=get_function_values(len(pos_solution),pos_solution,
p_solution)
non_dominated_sorted_solution3,_ = fast_non_dominated_sort(function1_best[:], function2_best[:])
function1_best1=[]
function2_best1 = []
for i in range(len(non_dominated_sorted_solution3[0])):
# print(i)
function1_best1.append(function1_best[non_dominated_sorted_solution3[0][i]])
function2_best1.append(function2_best[non_dominated_sorted_solution3[0][i]])
# f1_best.extend(function1_best1)
# f2_best.extend(function2_best1)
f1_best=function1_best1
f2_best=function2_best1
gen_no+=1
# plt.xlabel('average snr', fontsize=15)
# plt.ylabel('average 1/gdop', fontsize=15)
# plt.scatter(function1_best, function2_best)
# plt.show()
return f1_best,f2_best,best_pos,best_p
if __name__ == '__main__':
users = Users.getUsers("./data.csv")
f1,f2,_,_=main(users,60,300,3)
print(f1, f2)
plt.xlabel('average snr', fontsize=12)
plt.ylabel('average -gdop', fontsize=12)
# plt.xlim(70, 81)
# plt.ylim(0,0.1)
plt.scatter(f1, f2, )
plt.show()
# Program Name: NSGA-II.py
# Description: This is a python implementation of Prof. Kalyanmoy Deb's popular NSGA-II algorithm
# Author: Haris Ali Khan
# Supervisor: Prof. Manoj Kumar Tiwari
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import time
import NSGA2 as ns
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=ns.init(pop_size,k,users)
print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
function1_best=[]
function2_best=[]
solution_num=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=ns.get_function_values(pop_size,pos_solution,p_solution,users)
# print(function1_values)
# print(function2_values)
# print(punish_values)
non_dominated_sorted_solution,rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
# print("等级")
# print(rank)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(ns.crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
# child = ns.cross_over_old(parent1, parent2)
# child_mute = ns.mutate_old(child, pos_range)
child = ns.cross_over_stage(parent1, parent2, gen_no, max_gen)
child_mute = ns.mutate_stage(child, pos_range, gen_no, max_gen)
child_p=ns.init_p(child_mute,users)
pos_solution2.append(child_mute)
p_solution2.append(child_p)
# child1,child2=cross_over(parent1,parent2)
# child1_mute=mutate(child1,pos_range)
# child2_mute=mutate(child2,pos_range)
# child1_p=init_p(child1_mute,users)
# child2_p=init_p(child2_mute,users)
# pos_solution2.append(child1_mute)
# pos_solution2.append(child2_mute)
# p_solution2.append(child1_p)
# p_solution2.append(child2_p)
function1_values2, function2_values2, punish_values2 = ns.get_function_values(2*pop_size, pos_solution2, p_solution2,users)
non_dominated_sorted_solution2,rank2 = ns.fast_non_dominated_sort(function1_values2[:], function2_values2[:])
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
ns.crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = ns.sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
function1_best,function2_best,_=ns.get_function_values(len(pos_solution),pos_solution,
p_solution,users)
best_pos,_=ns.fast_non_dominated_sort(function1_best[:], function2_best[:])
solution_num.append(len(best_pos[0]))
# if len(best_pos[0])==60:
# break
gen_no+=1
for r in range(len(best_pos)):
for i in range(len(best_pos[r])):
f1_best.append(function1_best[best_pos[r][i]])
f2_best.append(function2_best[best_pos[r][i]])
# for i in range(len(best_pos[0])):
# f1_best.append(function1_best[best_pos[0][i]])
# f2_best.append(function2_best[best_pos[0][i]])
return f1_best,f2_best,solution_num
if __name__ == '__main__':
users = Users.getUsers("./data.csv")
start_time = time.time()
f1,f2,solution_num=main(users,60,200,3)
end_time = time.time()
run_time = end_time - start_time
print(f1, f2)
print("程序运行时间为:", run_time)
print(solution_num)
plt.xlabel('average snr', fontsize=12)
plt.ylabel('average -gdop', fontsize=12)
# plt.xlim(70, 81)
# plt.ylim(0,0.1)
plt.scatter(f1, f2, )
plt.show()
# Program Name: NSGA-II.py
# Description: This is a python implementation of Prof. Kalyanmoy Deb's popular NSGA-II algorithm
# Author: Haris Ali Khan
# Supervisor: Prof. Manoj Kumar Tiwari
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import time
import NSGA2 as ns
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=ns.init(pop_size,k,users)
print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
function1_best=[]
function2_best=[]
solution_num=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=ns.get_function_values(pop_size,pos_solution,p_solution,users)
# print(function1_values)
# print(function2_values)
# print(punish_values)
non_dominated_sorted_solution,rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
# print("等级")
# print(rank)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(ns.crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = ns.tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
child = ns.cross_over_old(parent1, parent2)
child_mute = ns.mutate_old(child, pos_range)
# child = ns.cross_over(parent1, parent2, gen_no, max_gen)
# child_mute = ns.mutate(child, pos_range, gen_no, max_gen)
child_p=ns.init_p(child_mute,users)
pos_solution2.append(child_mute)
p_solution2.append(child_p)
# child1,child2=cross_over(parent1,parent2)
# child1_mute=mutate(child1,pos_range)
# child2_mute=mutate(child2,pos_range)
# child1_p=init_p(child1_mute,users)
# child2_p=init_p(child2_mute,users)
# pos_solution2.append(child1_mute)
# pos_solution2.append(child2_mute)
# p_solution2.append(child1_p)
# p_solution2.append(child2_p)
function1_values2, function2_values2, punish_values2 = ns.get_function_values(2*pop_size, pos_solution2, p_solution2,users)
non_dominated_sorted_solution2,rank2 = ns.fast_non_dominated_sort(function1_values2[:], function2_values2[:])
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
ns.crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = ns.sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
function1_best,function2_best,_=ns.get_function_values(len(pos_solution),pos_solution,
p_solution,users)
best_pos,_=ns.fast_non_dominated_sort(function1_best[:], function2_best[:])
solution_num.append(len(best_pos[0]))
# if len(best_pos[0])==60:
# break
gen_no+=1
# for r in range(len(best_pos)):
# for i in range(len(best_pos[r])):
# f1_best.append(function1_best[best_pos[r][i]])
# f2_best.append(function2_best[best_pos[r][i]])
for i in range(len(best_pos[0])):
f1_best.append(function1_best[best_pos[0][i]])
f2_best.append(function2_best[best_pos[0][i]])
return f1_best,f2_best,solution_num
if __name__ == '__main__':
users = Users.getUsers("./data.csv")
# start_time = time.time()
# f1,f2,solution_num=main(users,60,200,3)
# end_time = time.time()
# run_time = end_time - start_time
# print(f1, f2)
# print("程序运行时间为:", run_time)
# print(solution_num)
# plt.xlabel('average snr', fontsize=12)
# plt.ylabel('average -gdop', fontsize=12)
# # plt.xlim(70, 81)
# # plt.ylim(0,0.1)
# plt.scatter(f1, f2, )
#
# plt.show()
f11=[44.01293032115052, 47.83374754674163, 47.85528465884196, 44.01293032115052, 44.01293032115052, 46.63593006080242, 39.62478182480577, 44.01293032115052, 47.17679025658907, 44.01293032115052, 47.82808413404777, 47.82808413404777, 46.76029845544239, 47.17679025658907, 45.044452988184645, 47.17679025658907, 47.543896627698835, 46.8849173446886, 44.01293032115052, 46.76029845544239, 44.01293032115052, 47.85528465884196, 46.76029845544239, 44.01293032115052, 44.01293032115052, 47.3229745773721, 44.01293032115052, 46.76029845544239, 47.599713025764835, 43.38306806385106, 47.17679025658907, 47.17679025658907, 44.01293032115052, 46.76029845544239, 47.599713025764835, 46.76029845544239, 47.17239267042667, 47.82808413404777, 46.76029845544239, 47.83374754674163, 42.01969688660906, 44.01293032115052, 47.85528465884196, 47.82808413404777, 46.76029845544239, 47.82808413404777, 47.82808413404777, 47.599713025764835, 47.71696642889315, 47.17679025658907, 47.85528465884196, 44.01293032115052, 44.01293032115052, 46.76029845544239, 47.22576564590512, 46.67715661386702, 44.67828196719196, 46.2996992724134, 46.67715661386702, 44.01293032115052]
f12=[-2.9306299727420435, -6.746681686929208, -7.620343115050427, -2.9306299727420435, -2.9306299727420435, -3.640093821617248, -2.821788441120495, -2.9306299727420435, -4.170921680968133, -2.9306299727420435, -5.907046245460523, -5.907046245460523, -3.9462164822262786, -4.170921680968133, -2.9749259469999108, -4.170921680968133, -4.651331808328007, -3.9668788407598825, -2.9306299727420435, -3.9462164822262786, -2.9306299727420435, -7.620343115050427, -3.9462164822262786, -2.9306299727420435, -2.9306299727420435, -4.298700541930365, -2.9306299727420435, -3.9462164822262786, -5.338312872832227, -2.882918744052549, -4.170921680968133, -4.170921680968133, -2.9306299727420435, -3.9462164822262786, -5.338312872832227, -3.9462164822262786, -4.154760990048628, -5.907046245460523, -3.9462164822262786, -6.746681686929208, -2.8372490343870385, -2.9306299727420435, -7.620343115050427, -5.907046245460523, -3.9462164822262786, -5.907046245460523, -5.907046245460523, -5.338312872832227, -5.374574095972783, -4.170921680968133, -7.620343115050427, -2.9306299727420435, -2.9306299727420435, -3.9462164822262786, -4.202109252160319, -3.7840000822410667, -2.9530523643591864, -3.5360407260131788, -3.7840000822410667, -2.9306299727420435]
plt.scatter(f11, f12, )
plt.show()
print(len(f11))
\ No newline at end of file
#Importing required modules
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import Users
import tool
import GDOP
import p_tool
from itertools import combinations
#计算用户平均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(power,p_rest):
f = 0
i=0
for p in power:
dis = sum(p) - p_rest[i]
if dis > 0.001:
f += 10 ** (dis * 100)
for p_singe in p: # 功率要大于0
dis1 = 0 - p_singe
if dis1>0:
f += 10 ** max(0, dis1 * 100)
i+=1
return f
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
#Function to sort by values
def sort_by_values(list1, values):
sorted_list = []
while(len(sorted_list)!=len(list1)):
if index_of(min(values),values) in list1:
sorted_list.append(index_of(min(values),values))
values[index_of(min(values),values)] = math.inf
return sorted_list
#Function to carry out NSGA-II's fast non dominated sort
def fast_non_dominated_sort(values1, values2):
#支配的节点
S=[[] for i in range(0,len(values1))]
front = [[]]
n=[0 for i in range(0,len(values1))]#被支配的数量
rank = [0 for i in range(0, len(values1))]#等级
for p in range(0,len(values1)):
S[p]=[]
n[p]=0
for q in range(0, len(values1)):
if (values1[p] > values1[q] and values2[p] > values2[q]) or (values1[p] >= values1[q] and values2[p] > values2[q]) or (values1[p] > values1[q] and values2[p] >= values2[q]):
if q not in S[p]:
S[p].append(q)
elif (values1[q] > values1[p] and values2[q] > values2[p]) or (values1[q] >= values1[p] and values2[q] > values2[p]) or (values1[q] > values1[p] and values2[q] >= values2[p]):
n[p] = n[p] + 1
if n[p]==0:
rank[p] = 0
if p not in front[0]:
front[0].append(p)
i = 0
while(front[i] != []):
Q=[]
for p in front[i]:
for q in S[p]:
n[q] =n[q] - 1
if( n[q]==0):
rank[q]=i+1
if q not in Q:
Q.append(q)
i = i+1
front.append(Q)
del front[len(front)-1]
return front,rank
#Function to calculate crowding distance
def crowding_distance(values1, values2, front):
distance = [0 for i in range(0,len(front))]
#从小到大排序
sorted1 = sort_by_values(front, values1[:])
sorted2 = sort_by_values(front, values2[:])
distance[0] = 4444444444444444
distance[len(front) - 1] = 4444444444444444
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted1[k+1]] - values1[sorted1[k-1]])/(max(values1)-min(values1))
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values2[sorted2[k+1]] - values2[sorted2[k-1]])/(max(values2)-min(values2))
return distance
#初始化无人机位置
def init(pop_size,k,users):
min_pos=0
max_pos=1000
pos_solution=[]
p_solution=[]
for i in range(pop_size):
uavs_pos=[[min_pos+(max_pos-min_pos)*random.random(),min_pos+(max_pos-min_pos)*random.random(),100] for i in range(k)]
p_alloc=init_p(uavs_pos,users)
pos_solution.append(uavs_pos)
p_solution.append(p_alloc)
# print(pos_solution)
return pos_solution,p_solution
def get_dis(i,uavs_pos,users,uav_to_user):
dis=[]
for k in uav_to_user[i]:
dis.append(tool.calculate_3d_distance(uavs_pos[i],users[k]))
return dis
def init_p(uavs_pos,users):
uavs_initial = [i for i in range(len(uavs_pos))]
combination = list(combinations(uavs_initial, 3))
c_association, p_association = p_tool.get_p_association_first(users, uavs_pos,
math.ceil(len(users) / len(combination)),
math.ceil(len(users) / len(uavs_pos)))
uav_to_user=tool.get_uav_to_user(c_association,uavs_pos)
print(uav_to_user)
p_rest=tool.get_rest_p(users,uavs_pos,p_association)
# print(p_rest)
p_alloc=[]
for i in range(len(uavs_pos)):
#归一化生成 功率
dis=get_dis(i,uavs_pos,users,uav_to_user)
# p=[random.randint(1,len(uav_to_user[i])) for i in range(len(uav_to_user[i]))]
p_new=[0 for i in range(len(users))]
for j in range(len(uav_to_user[i])):
p_new[uav_to_user[i][j]]=dis[j]/sum(dis)*p_rest[i]
# p_new.append(p[j]/sum(p)*p_rest[i])
p_alloc.append(p_new)
# p_alloc.append(np.random.uniform(0, p_rest[i] / len(uav_to_user[i]), (len(uav_to_user[i]))))
return p_alloc
#交叉 pos_solution1=[[],[],[]]
def cross_over(pos_solution1,pos_solution2):
child1=[]
child2=[]
for i in range(len(pos_solution1)):
pos1 = []
pos2=[]
beta = get_beta()
for j in range(len(pos_solution1[i])):
if j<len(pos_solution1[i])-1:
x1 = (pos_solution1[i][j] + pos_solution2[i][j]) / 2
x2 = abs((pos_solution1[i][j] - pos_solution2[i][j]) / 2)
x1=x1 + beta * x2
x2=abs(x1 - beta * x2)
pos1.append(x1)
pos2.append(x2)
else:
pos1.append(100)
pos2.append(100)
child1.append(pos1)
child2.append(pos2)
return child1,child2
def cross_over_p(p_solution1,p_solution2):
child1 = []
child2 = []
for i in range(len(p_solution1)):
p1 = []
p2 = []
beta = get_beta()
for j in range(len(p_solution1[i])):
x1 = (p_solution1[i][j] + p_solution2[i][j]) / 2
x2 = abs((p_solution1[i][j] - p_solution2[i][j]) / 2)
x1 = x1 + beta * x2
x2 = abs(x1 - beta * x2)
p1.append(x1)
p2.append(x2)
child1.append(p1)
child2.append(p2)
return child1,child2
def get_beta(crossover_param=2):
u = random.random()
if u <= 0.5:
return (2 * u) ** (1 / (crossover_param + 1))
return (2 * (1 - u)) ** (-1 / (crossover_param + 1))
def mutate(child,variables_range):
u, delta = get_delta()
child_new=[]
if u < 0.5:
for i in range(len(child)):
pos=[]
for j in range(len(child[i])):
if j < len(child[i]) - 1:
x=child[i][j]+ delta * (child[i][j] - variables_range[0])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
else:
for i in range(len(child)):
pos = []
for j in range(len(child[i])):
if j<len(child[i])-1:
x= child[i][j] +delta * (variables_range[1] - child[i][j])
pos.append(x)
else:
pos.append(100)
child_new.append(pos)
for i in range(len(child_new)):
for j in range(len(child_new[i])):
if j<len(child_new[i])-1:
if child_new[i][j] < variables_range[0]:
child_new[i][j] = variables_range[0]
elif child_new[i][j] > variables_range[1]:
child_new[i][j] = variables_range[1]
return child_new
def mutate_p(child,variables_range):
return
def get_delta(mutation_param=5):
u = random.random()
if u < 0.5:
return u, (2 * u) ** (1 / (mutation_param + 1)) - 1
return u, 1 - (2 * (1 - u)) ** (1 / (mutation_param + 1))
def get_function_values(pop_size,pos_solution,p_solution):
function1_values = []
function2_values = []
punish_values = []
for i in range(pop_size):
uavs_pos = pos_solution[i]
uavs_initial = [i for i in range(len(uavs_pos))]
combination = list(combinations(uavs_initial, 3))
c_association,p_association=p_tool.get_p_association_first(users, uavs_pos, math.ceil(len(users) / len(combination)),
math.ceil(len(users) / len(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_rest = tool.get_rest_p(users, uavs_pos, p_association)
function1_values.append(function_snr(users, pos_solution[i], c_association, p_solution[i]))
function2_values.append(function_gdop(users, uavs_pos, c_association, p_association, ))
punish_values.append(punish(p_solution[i], p_rest))
return function1_values,function2_values,punish_values
def tournament(pos_solution,non_dominated_sorted_solution,rank,distance):
a1 = random.randint(0, len(pos_solution) - 1)
b1=a1
while b1==a1:
b1 = random.randint(0, len(pos_solution) - 1)
participants = [pos_solution[a1],pos_solution[b1]]
best = None
for participant in participants:
if best is None or crowding_operator(a1,b1,non_dominated_sorted_solution,rank,distance) == 1:
best = participant
return best
def get_f_by_pos(pos):
c_association = tool.get_c_association(users, pos, math.ceil(len(users) / len(pos)))
p_association = tool.get_p_association(users, pos, c_association, len(users) * 2 / len(pos))
p = init_p(pos, users)
function1_value=function_snr(users, pos, c_association, p)
function2_value=function_gdop(users, pos, c_association, p, )
return function1_value,function2_value
def crowding_operator(index1,index2,non_dominated_sorted_solution,rank,distance):
rank1=rank[index1]#index1的等级
rank2=rank[index2]
distance1=0
distance2=0
for i in range(len(non_dominated_sorted_solution[rank1])):
if non_dominated_sorted_solution[rank1][i]==index1:
distance1=distance[rank1][i]
for i in range(len(non_dominated_sorted_solution[rank2])):
if non_dominated_sorted_solution[rank2][i]==index2:
distance2=distance[rank2][i]
if rank1<rank2 or (rank1==rank2 and distance1>distance2):
return 1
else:
return 0
def main(users,pop_size,max_gen,k=3):
pos_solution,p_solution=init(pop_size,k,users)
print(p_solution)
# max_gen = 100
gen_no = 0
pos_range=[0,1000]
best_pos=[]
best_p=[]
f1_best=[]
f2_best=[]
while(gen_no<max_gen):
function1_values,function2_values,punish_values=get_function_values(pop_size,pos_solution,p_solution)
# for i in range(pop_size):
# uavs_pos=pos_solution[i]
# 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_rest=tool.get_rest_p(users, uavs_pos, p_association)
# function1_values.append(function_snr(users,pos_solution[i],c_association,p_solution[i]))
# function2_values.append(function_gdop(users,uavs_pos,c_association,p_association,))
# punish_values.append(punish(p_solution[i],p_rest))
print(function1_values)
print(function2_values)
print(punish_values)
non_dominated_sorted_solution,rank = fast_non_dominated_sort(function1_values[:], function2_values[:])
print(non_dominated_sorted_solution)
print("等级")
print(rank)
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
pos_solution2 = pos_solution[:]
p_solution2=p_solution[:]
#排序要考虑惩罚项
#交叉变异生成子代
while (len(pos_solution2) != 2 * pop_size):
#锦标赛选择
parent1 = tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
parent2 = parent1
while parent1== parent2:
parent2 = tournament(pos_solution,non_dominated_sorted_solution,rank,crowding_distance_values)
#交叉变异
child1,child2=cross_over(parent1,parent2)
child1_mute=mutate(child1,pos_range)
child2_mute=mutate(child2,pos_range)
child1_p=init_p(child1_mute,users)
child2_p=init_p(child2_mute,users)
pos_solution2.append(child1_mute)
pos_solution2.append(child2_mute)
p_solution2.append(child1_p)
p_solution2.append(child2_p)
function1_values2, function2_values2, punish_values2 = get_function_values(2*pop_size, pos_solution2, p_solution2)
print(function1_values2)
print(function2_values2)
print(punish_values2)
non_dominated_sorted_solution2,rank2 = fast_non_dominated_sort(function1_values2[:], function2_values2[:])
print(non_dominated_sorted_solution2)
print(rank2)
crowding_distance_values2 = []
for i in range(0, len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(
crowding_distance(function1_values2[:], function2_values2[:], non_dominated_sorted_solution2[i][:]))
new_solution = []
for i in range(0, len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [
index_of(non_dominated_sorted_solution2[i][j], non_dominated_sorted_solution2[i]) for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front22 = sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in
range(0, len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if (len(new_solution) == pop_size):
break
if (len(new_solution) == pop_size):
break
pos_solution = [pos_solution2[i] for i in new_solution]
p_solution=[p_solution2[i] for i in new_solution]
# function1_last, function2_last, _ = get_function_values(len(solution), solution,
# p_solution_)
# non_dominated_sorted_solution = fast_non_dominated_sort(function1_last[:], function2_last[:])
# print(non_dominated_sorted_solution[0])
# pos_now=[solution[i] for i in non_dominated_sorted_solution[0]]
# p_now=[p_solution_[i] for i in non_dominated_sorted_solution[0]]
# best_pos.append(pos_now)
# best_p.append(p_now)
function1_best,function2_best,_=get_function_values(len(pos_solution),pos_solution,
p_solution)
non_dominated_sorted_solution3,_ = fast_non_dominated_sort(function1_best[:], function2_best[:])
function1_best1=[]
function2_best1 = []
for i in range(len(non_dominated_sorted_solution3[0])):
# print(i)
function1_best1.append(function1_best[non_dominated_sorted_solution3[0][i]])
function2_best1.append(function2_best[non_dominated_sorted_solution3[0][i]])
# f1_best.extend(function1_best1)
# f2_best.extend(function2_best1)
f1_best=function1_best1
f2_best=function2_best1
gen_no+=1
# plt.xlabel('average snr', fontsize=15)
# plt.ylabel('average 1/gdop', fontsize=15)
# plt.scatter(function1_best, function2_best)
# plt.show()
return f1_best,f2_best,best_pos,best_p
if __name__ == '__main__':
users = Users.getUsers("./data.csv")
f1,f2,_,_=main(users,60,500,4)
print(f1, f2)
plt.xlabel('average snr', fontsize=12)
plt.ylabel('average -gdop', fontsize=12)
plt.scatter(f1, f2,)
plt.show()
import random
import NSGA2 as ns
def objective_function(function1,function2,x):
# 定义优化的目标函数,此处以一个简单的二维函数为例
return function1(x),function2(x)
#todo 按照非支配解个数来动态修改生成位置范围
def generate_neighbor(pos,iter,iter_max):
# 在当前解的邻域内随机生成新解
new_pos=[]
pos_range=[0,1000]
for loc in pos:
k=[]
for i in range(0,len(loc)-1):
# x = loc[i] + random.uniform(-20 + 10 * iter / iter_max, 20 -10 * iter / iter_max)
# x = loc[i] + random.uniform(-10, 10)
if iter<10:
x=loc[i] + random.uniform(-40+10*iter/iter_max, 40-10*iter/iter_max)
elif iter>=10 and iter<20:
x = loc[i] + random.uniform(-30 + 10 * iter / iter_max, 30 - 10 * iter / iter_max)
elif iter>=20 and iter<30:
x = loc[i] + random.uniform(-20 + 10 * iter / iter_max, 20 -10 * iter / iter_max)
else:
x = loc[i] + random.uniform(-10 + 5 * iter / iter_max, 10 - 5 * iter / iter_max)
if x>pos_range[1]:
x=pos_range[1]
if x<pos_range[0]:
x=pos_range[0]
k.append(x)
k.append(loc[2])
new_pos.append(k)
return new_pos
def generate_neighbor2(pos,rank,rank_max,iter_,iter_max):
# 在当前解的邻域内随机生成新解
new_pos=[]
pos_range=[0,1000]
for loc in pos:
k=[]
for i in range(0,len(loc)-1):
r1=-10-20 * (rank+1) / rank_max+10*iter_/iter_max
r2=10+ 20 * (rank+1) / rank_max-10*iter_/iter_max
x = loc[i] + random.uniform(r1,r2)
if x>pos_range[1]:
x=pos_range[1]
if x<pos_range[0]:
x=pos_range[0]
k.append(x)
k.append(loc[2])
new_pos.append(k)
return new_pos
#todo:根据当前解的等级调整领域范围生成领域解
def generate_neighbor3(pos,rank,rank_max):
new_pos=[]
pos_range=[0,1000]
for loc in pos:
k=[]
for i in range(0,len(loc)-1):
if rank_max>10:
r1=-50-20 * (rank+1) / rank_max
r2=50+ 20 * (rank+1) / rank_max
x = loc[i] + random.uniform(r1,r2)
elif rank_max<=10 and rank_max>5:
r1 = -20 - 20 * (rank + 1) / rank_max
r2 = 20 + 10 * (rank + 1) / rank_max
x = loc[i] + random.uniform(r1, r2)
else:
r1 = -20 - 10 * (rank + 1) / rank_max
r2 = 20 + 10 * (rank + 1) / rank_max
x = loc[i] + random.uniform(r1, r2)
if x>pos_range[1]:
x=pos_range[1]
if x<pos_range[0]:
x=pos_range[0]
k.append(x)
k.append(loc[2])
new_pos.append(k)
return new_pos
def get_best(neighbors,neighbors_p,users):
function1_values, function2_values, _ = ns.get_function_values(len(neighbors), neighbors,
neighbors_p, users)
non_dominated_sorted_solution, rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
best=non_dominated_sorted_solution[0][0]
return neighbors[best]
def tabu_search(pos,users,max_iter,iter,iterMax,rank,rank_max):
individual=pos
current_solution = pos # 初始解
best_solution = current_solution # 记录最优解
best=[]
tabu_list = [] # 禁忌表,避免重复搜索
tabu_tenure = 4 # 禁忌期限,即禁忌解在禁忌表中停留的迭代次数
for i in range(max_iter):
# neighbors = [generate_neighbor2(current_solution,rank,rank_max,iter,iterMax) for _ in range(10)] # 随机生成10个邻域解
neighbors = [generate_neighbor(current_solution, iter,iterMax) for _ in range(10)]
# neighbors = [generate_neighbor3(current_solution, rank, rank_max) for _ in range(10)]
neighbors_p=[]#根据领域解生成的功率分配
for j in range(len(neighbors)):
neighbors_p.append(ns.init_p(neighbors[j],users))
# 在邻域解中选择一个非禁忌的最优解,找到支配等级最高的解,
candidate = get_best(neighbors,neighbors_p,users)
while candidate in tabu_list:
neighbors.remove(candidate)
candidate = get_best(neighbors,neighbors_p,users)
# 更新当前解和最优解
current_solution = candidate
compare_group=[candidate,individual]
compare_group_p=[]
for i in range(len(compare_group)):
compare_group_p.append(ns.init_p(compare_group[i],users))
function1_values, function2_values, _ = ns.get_function_values(len(compare_group), compare_group,
compare_group_p, users)
non_dominated_sorted_solution, rank = ns.fast_non_dominated_sort(function1_values[:], function2_values[:])
# crowding_distance_values = []
# for i in range(0, len(non_dominated_sorted_solution)):
# crowding_distance_values.append(
# ns.crowding_distance(function1_values[:], function2_values[:], non_dominated_sorted_solution[i][:]))
if rank[0]<rank[1]:
best_solution = candidate
return best_solution
tabu_list.append(candidate) # 将当前解加入禁忌表
if len(tabu_list) > tabu_tenure: # 维护禁忌表的长度不超过禁忌期限
tabu_list.pop(0)
return best_solution
pos=[[313.99873528 ,416.45594562, 100. ],
[842.85965065 ,611.07755542, 100. ],
[810.63437665 ,371.17088506 ,100. ]]
# print(generate_neighbor(pos))
\ No newline at end of file
import math
import random
import numpy as np
import csv
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import pandas as pd
# 随机生成U个用户的位置
def generate(num,filename):
data = np.random.randint(1, 1000, (num, 2))
f = open(filename, 'w', encoding='utf-8', newline="")
# 2.基于文件对象构建csv写入对象
csv_write = csv.writer(f)
# 4.写入csv文件
for d in data:
csv_write.writerow(d)
return data
def generateNormalDistribution(num):
mu, sigma = 500, 170 # 有关于正态分布的值μ,σ
x = sigma * np.random.randn(1, num) + mu
x = ([i for item in x for i in item]) # 在这个循环中我们能把二维的数组转换成一维的数组,y2同理
y = sigma * np.random.randn(1, num) + mu
y = ([i for item in y for i in item])
data = np.zeros((num, 2))
for i in range(num):
data[i] = np.array([x[i], y[i]])
f = open('../data_normal.csv', 'w', encoding='utf-8', newline="")
csv_write = csv.writer(f)
for d in data:
csv_write.writerow(d)
print(data)
return data
# 用户按集群分布
def generateGroupDistribution(num):
centers = [[500, 500], [1600, 400], [700, 1200], [1400, 1500]]
sigma = 100 # 有关于正态分布的值σ
group_num = 4
x_ = []
y_ = []
for i in range(group_num):
number = int(num / group_num)
print(centers[i])
x = sigma * np.random.randn(1, number) + centers[i][0]
y = sigma * np.random.randn(1, number) + centers[i][1]
x_.extend([i for item in x for i in item])
y_.extend([i for item in y for i in item])
data = np.zeros((num, 2))
for i in range(num):
data[i] = np.array([x_[i], y_[i]])
f = open('../data_group.csv', 'w', encoding='utf-8', newline="")
csv_write = csv.writer(f)
for d in data:
csv_write.writerow(d)
print(data)
return data
def generateNormal(mean, sigma):
x = sigma * np.random.randn(1) + mean
return x
# 从csv文件读用户位置
def getUsers(filename):
data = pd.read_csv(filename, header=None)
list = data.values.tolist()
array = np.array(list)
return array
def getDistanceFromCenter(user, x, y):
return math.sqrt((user[0] - x) ** 2 + (user[1] - y) ** 2)
def draw(data):
plt.figure(num=1, figsize=(10, 10))
x = data[:, 0]
y = data[:, 1]
plt.scatter(x, y)
plt.xlim(0, 7001)
plt.ylim(0, 7001)
ax = plt.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
# x1 = np.linspace(300, 700, 500)
# center1 = 500 + np.sqrt(200 ** 2 - (x1 - 500) ** 2)
# center2 = 500 - np.sqrt(200 ** 2 - (x1 - 500) ** 2)
# plt.plot(x1, center1,c='b')
# plt.plot(x1, center2,c='b')
# x2 = np.linspace(200, 800, 500)
# center21 = 500 + np.sqrt(300 ** 2 - (x2 - 500) ** 2)
# center22 = 500 - np.sqrt(300 ** 2 - (x2 - 500) ** 2)
# plt.plot(x2, center21, c='r')
# plt.plot(x2, center22, c='r')
# x3 = np.linspace(100, 900, 500)
# center31 = 500 + np.sqrt(400 ** 2 - (x3 - 500) ** 2)
# center32 = 500 - np.sqrt(400 ** 2 - (x3 - 500) ** 2)
# plt.plot(x3, center31, c='g')
# plt.plot(x3, center32, c='g')
# model = KMeans(n_clusters=5, random_state=0).fit(data)
# center = model.cluster_centers_
# for c in center:
# plt.scatter(c[0], c[1],s=200,marker='p')
return plt
if __name__ == '__main__':
data=generate(20,"./data-20.csv")
# list=getUsers("./data2.csv")
# print(list)
# data=generateGroupDistribution(100)
# list = getUsers("../data_group.csv")
# draw(list).show()
#归一化pso
import math
import time
from itertools import combinations
import Users
from pso import PSO
import tool
import p_tool
import GDOP
import NSGA2 as ns
import draw
import NSGA2_p_first as ns_p
#计算用户平均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 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, )
return snr,gdop,snr+gdop
def fitness_p(users,uavs_pos):
uavs_initial = [i for i in range(len(uavs_pos))]
combination = list(combinations(uavs_initial, 3))
c_association, p_association = p_tool.get_p_association_first(users, uavs_pos,
math.ceil(len(users) / len(combination)),
math.ceil(len(users) / len(uavs_pos)))
p_solution = ns_p.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, )
return snr, gdop, snr + gdop
def run(users, k):
pso=PSO(users,[],)
X, V = pso.initParticle(k, users)
# print(X)
global_pos, global_best, result = pso.pso(X, V, k,fitness)
print(global_pos, global_best)
# pso迭代曲线
# draw.drawResultAndIter(result)
# plt.show()
return global_pos, global_best, result
def run_p(users, k):
pso = PSO(users, [], )
X, V = pso.initParticle(k, users)
# print(X)
global_pos, global_best, result = pso.pso(X, V, k, fitness_p)
print(global_pos, global_best)
# pso迭代曲线
# draw.drawResultAndIter(result)
# plt.show()
return global_pos, global_best, result
if __name__ == '__main__':
start_time = time.time()
users = Users.getUsers("./data.csv")
# global_pos, global_best,result=run(users,3)
# print(fitness(users,global_pos))
global_pos, global_best, result = run(users, 3)
print(global_pos)
print(fitness_p(users, global_pos))
end_time = time.time()
run_time = end_time - start_time
print("程序运行时间为:", run_time)
#主要目标法pso
import math
import time
from itertools import combinations
import Users
import p_tool
from pso import PSO
import tool
import GDOP
import NSGA2 as ns
import draw
import NSGA2_p_first as ns_p
#计算用户平均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 run(users, k):
pso=PSO(users,[],)
X, V = pso.initParticle(k, users)
# print(X)
global_pos, global_best, result = pso.pso(X, V, k,fitness)
print(global_pos, global_best)
# pso迭代曲线
# draw.drawResultAndIter(result)
# plt.show()
return global_pos, global_best, result
def fitness_p(users,uavs_pos):
uavs_initial = [i for i in range(len(uavs_pos))]
combination = list(combinations(uavs_initial, 3))
c_association, p_association = p_tool.get_p_association_first(users, uavs_pos,
math.ceil(len(users) / len(combination)),
math.ceil(len(users) / len(uavs_pos)))
p_solution = ns_p.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 run_p(users, k):
pso = PSO(users, [], )
X, V = pso.initParticle(k, users)
# print(X)
global_pos, global_best, result = pso.pso(X, V, k, fitness_p)
print(global_pos, global_best)
# pso迭代曲线
# draw.drawResultAndIter(result)
# plt.show()
return global_pos, global_best, result
if __name__ == '__main__':
start_time = time.time()
users = Users.getUsers("./data.csv")
global_pos, global_best, result = run(users, 3)
print(fitness(users, global_pos))
end_time = time.time()
run_time = end_time - start_time
print("程序运行时间为:", run_time)
#随机位置,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))
763,553
215,366
996,343
968,812
472,189
869,322
914,650
621,455
259,634
52,66
8,6
661,93
708,567
171,53
221,858
822,518
919,967
433,827
478,702
191,953
499,68
497,788
772,72
731,292
929,442
50,18
900,691
265,55
66,543
275,407
330,520
347,688
179,914
688,83
700,447
606,416
This source diff could not be displayed because it is too large. You can view the blob instead.
463,50
413,347
722,696
301,271
274,739
325,969
604,199
497,630
436,522
844,378
181,633
19,455
478,364
622,231
649,383
70,337
142,901
274,86
694,316
839,58
75,363
700,136
303,523
508,732
407,275
165,881
456,391
479,530
996,261
217,73
617,137
416,996
520,480
208,653
503,280
842,995
979,720
830,25
504,703
878,984
223,20
542,267
464,813
279,58
384,874
import math
import random
import matplotlib.pyplot as plt
#First function to optimize
def function1(x):
value = -x**2
return value
#Second function to optimize
def function2(x):
value = -(x-2)**2
return value
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
#Function to sort by values
def sort_by_values(list1, values):
sorted_list = []
while(len(sorted_list)!=len(list1)):
if index_of(min(values),values) in list1:
sorted_list.append(index_of(min(values),values))
values[index_of(min(values),values)] = math.inf
return sorted_list
#Function to carry out NSGA-II's fast non dominated sort
def fast_non_dominated_sort(values1, values2):
S=[[] for i in range(0,len(values1))]
front = [[]]
n=[0 for i in range(0,len(values1))]
rank = [0 for i in range(0, len(values1))]
for p in range(0,len(values1)):
S[p]=[]
n[p]=0
for q in range(0, len(values1)):
if (values1[p] > values1[q] and values2[p] > values2[q]) or (values1[p] >= values1[q] and values2[p] > values2[q]) or (values1[p] > values1[q] and values2[p] >= values2[q]):
if q not in S[p]:
S[p].append(q)
elif (values1[q] > values1[p] and values2[q] > values2[p]) or (values1[q] >= values1[p] and values2[q] > values2[p]) or (values1[q] > values1[p] and values2[q] >= values2[p]):
n[p] = n[p] + 1
if n[p]==0:
rank[p] = 0
if p not in front[0]:
front[0].append(p)
i = 0
while(front[i] != []):
Q=[]
for p in front[i]:
for q in S[p]:
n[q] =n[q] - 1
if( n[q]==0):
rank[q]=i+1
if q not in Q:
Q.append(q)
i = i+1
front.append(Q)
del front[len(front)-1]
return front
#Function to calculate crowding distance
def crowding_distance(values1, values2, front):
distance = [0 for i in range(0,len(front))]
sorted1 = sort_by_values(front, values1[:])
sorted2 = sort_by_values(front, values2[:])
distance[0] = 4444444444444444
distance[len(front) - 1] = 4444444444444444
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted1[k+1]] - values2[sorted1[k-1]])/(max(values1)-min(values1))
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted2[k+1]] - values2[sorted2[k-1]])/(max(values2)-min(values2))
return distance
#Function to carry out the crossover
def crossover(a,b):
r=random.random()
if r>0.5:
return mutation((a+b)/2)
else:
return mutation((a-b)/2)
#Function to carry out the mutation operator
def mutation(solution):
mutation_prob = random.random()
if mutation_prob <1:
solution = min_x+(max_x-min_x)*random.random()
return solution
#Main program starts here
pop_size = 20
max_gen = 921
#Initialization
min_x=-55
max_x=55
solution=[min_x+(max_x-min_x)*random.random() for i in range(0,pop_size)]
gen_no=0
while(gen_no<max_gen):
function1_values = [function1(solution[i])for i in range(0,pop_size)]
function2_values = [function2(solution[i])for i in range(0,pop_size)]
non_dominated_sorted_solution = fast_non_dominated_sort(function1_values[:],function2_values[:])
print("The best front for Generation number ",gen_no, " is")
for valuez in non_dominated_sorted_solution[0]:
print(round(solution[valuez],3),end=" ")
print("\n")
crowding_distance_values=[]
for i in range(0,len(non_dominated_sorted_solution)):
crowding_distance_values.append(crowding_distance(function1_values[:],function2_values[:],non_dominated_sorted_solution[i][:]))
solution2 = solution[:]
#Generating offsprings
while(len(solution2)!=2*pop_size):
a1 = random.randint(0,pop_size-1)
b1 = random.randint(0,pop_size-1)
solution2.append(crossover(solution[a1],solution[b1]))
function1_values2 = [function1(solution2[i])for i in range(0,2*pop_size)]
function2_values2 = [function2(solution2[i])for i in range(0,2*pop_size)]
non_dominated_sorted_solution2 = fast_non_dominated_sort(function1_values2[:],function2_values2[:])
crowding_distance_values2=[]
for i in range(0,len(non_dominated_sorted_solution2)):
crowding_distance_values2.append(crowding_distance(function1_values2[:],function2_values2[:],non_dominated_sorted_solution2[i][:]))
new_solution= []
for i in range(0,len(non_dominated_sorted_solution2)):
non_dominated_sorted_solution2_1 = [index_of(non_dominated_sorted_solution2[i][j],non_dominated_sorted_solution2[i] ) for j in range(0,len(non_dominated_sorted_solution2[i]))]
front22 = sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
front = [non_dominated_sorted_solution2[i][front22[j]] for j in range(0,len(non_dominated_sorted_solution2[i]))]
front.reverse()
for value in front:
new_solution.append(value)
if(len(new_solution)==pop_size):
break
if (len(new_solution) == pop_size):
break
solution = [solution2[i] for i in new_solution]
gen_no = gen_no + 1
#Lets plot the final front now
function1 = [i * -1 for i in function1_values]
print(function1_values)
print(function2_values)
function2 = [j * -1 for j in function2_values]
plt.xlabel('Function 1', fontsize=15)
plt.ylabel('Function 2', fontsize=15)
plt.scatter(function1, function2)
plt.show()
\ No newline at end of file
import matplotlib.pyplot as plt # 导入 Matplotlib 工具包
import networkx as nx # 导入 NetworkX 工具包
def example():
# 问题 2:无向图的最短路问题(司守奎,数学建模算法与应用,P43,例4.3)
G2 = nx.Graph() # 创建无向图
G2.add_weighted_edges_from([(1, 2, 2), (1, 3, 8), (1, 4, 1),
(2, 3, 6), (2, 5, 1),
(3, 4, 7), (3, 5, 5), (3, 6, 1), (3, 7, 2),
(4, 7, 9),
(5, 6, 3), (5, 8, 2), (5, 9, 9),
(6, 7, 4), (6, 9, 6),
(7, 9, 3), (7, 10, 1),
(8, 9, 7), (8, 11, 9),
(9, 10, 1), (9, 11, 2),
(10, 11, 4)]) # 向图中添加多条赋权边: (node1,node2,weight)
# 两个指定顶点之间的最短加权路径
minWPath_v1_v5 = nx.dijkstra_path(G2, source=1, target=5) # 顶点 0 到 顶点 3 的最短加权路径
print("顶点 v1 到 顶点 v5 的最短加权路径: ", minWPath_v1_v5)
# 两个指定顶点之间的最短加权路径的长度
lMinWPath_v1_v5 = nx.dijkstra_path_length(G2, source=1, target=5) # 最短加权路径长度
print("顶点 v1 到 顶点 v5 的最短加权路径长度: ", lMinWPath_v1_v5)
# === 关注 Youcans 原创系列(https://blog.csdn.net/youcans)===
pos = nx.spring_layout(G2) # 用 FR算法排列节点
nx.draw(G2, pos, with_labels=True, alpha=0.5)
labels = nx.get_edge_attributes(G2, 'weight')
nx.draw_networkx_edge_labels(G2, pos, edge_labels=labels)
plt.show()
def example2():
x = [1, 3, 4, 5, 7, 6]
y = [4, 5, 2, 8, 5, 10]
pos = {i + 1: [x[i], y[i]] for i in range(len(x))}
G = nx.Graph()
G.add_nodes_from(pos.keys())
for n, p in pos.items():
G._node[n]['pos'] = p
G.add_edges_from([(1, 3), (1, 5), (2, 4), (3, 6), (4, 6)])
nx.draw(G, pos=pos, with_labels=True, font_size=8, node_size=150)
plt.show()
def example3():
G = nx.Graph()
# 添加对应的边和点
for i in range(1, 10):
G.add_node(i, desc=str(i)) # 结点名称不能为str,desc为标签即结点名称
G.add_edge(1, 2, name='6') # 添加边, 参数name为边权值
G.add_edge(1, 3, name='4')
G.add_edge(1, 4, name='5')
G.add_edge(2, 5, name='1')
G.add_edge(3, 5, name='1')
G.add_edge(4, 6, name='2')
G.add_edge(5, 7, name='9')
G.add_edge(5, 8, name='7')
G.add_edge(6, 8, name='4')
G.add_edge(7, 9, name='2')
G.add_edge(8, 9, name='4')
pos = [(1, 3), (1, 3), (2, 4), (2, 2), (2, 1), (3, 3), (4, 1), (5, 4), (5, 2),
(6, 3)] # pos列表从第0位开始,但我定义是从结点1开始,这里令前两个坐标相同
# 按pos所定位置画出节点,无标签无权值
nx.draw_networkx(G, pos, with_labels=None)
# 画出标签
node_labels = nx.get_node_attributes(G, 'desc')
nx.draw_networkx_labels(G, pos, labels=node_labels)
# 画出边权值
edge_labels = nx.get_edge_attributes(G, 'name')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.show()
def draw_topology_before(users,graph,g):
plt.figure()
pos = {i + 1: [users[i][0], users[i][1]] for i in range(len(users))}
pos[0]=g
G = nx.Graph()
# 添加对应的边和点
for i in range(0, len(users)+1):
G.add_node(i, desc=str(i)) # 结点名称不能为str,desc为标签即结点名称
for edge in graph:
G.add_edge(edge[0], edge[1], name=edge[2]) # 添加边, 参数name为边权值
# 按pos所定位置画出节点,无标签无权值
nx.draw_networkx(G, pos, with_labels=None)
# 画出标签
node_labels = nx.get_node_attributes(G, 'desc')
nx.draw_networkx_labels(G, pos, labels=node_labels)
# 画出边权值
edge_labels = nx.get_edge_attributes(G, 'name')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
def draw_topology_after(uavs,users,graph,g):
plt.figure()
pos = {i + 1: [users[i][0], users[i][1]] for i in range(len(users))}
pos[0]=g
for i in range(len(uavs)):
pos[i+100]=[uavs[i][0],uavs[i][1]]
G = nx.Graph()
# 添加对应的边和点
for i in range(0, len(users)+1):
G.add_node(i, desc=str(i)) # 结点名称不能为str,desc为标签即结点名称
for i in range(100,100+len(uavs)):
G.add_node(i, desc=str(i)) # 结点名称不能为str,desc为标签即结点名称
for edge in graph:
G.add_edge(edge[0], edge[1], name=edge[2]) # 添加边, 参数name为边权值
# 按pos所定位置画出节点,无标签无权值
nx.draw_networkx(G, pos, with_labels=None)
# 画出标签
node_labels = nx.get_node_attributes(G, 'desc')
nx.draw_networkx_labels(G, pos, labels=node_labels)
# 画出边权值
edge_labels = nx.get_edge_attributes(G, 'name')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
# plt.title('AOE_CPM', fontsize=10)
def drawResultAndIter(resultAndIter):
f, ax = plt.subplots(1, 1)
plt.plot(resultAndIter)
ax.set_xlabel('iteration')
ax.set_ylabel('fitness')
plt.show()
if __name__ == '__main__':
f11=[78.55335494041263, 78.4925571817822, 78.12553455940584, 74.64405628626322, 74.81648579421885, 78.38827173203428,
74.55140845209807, 74.25000849350343, 78.53516476576708, 78.62622103565846, 77.80989106559173, 78.49073674312767,
74.56187387317372, 73.8567018719367, 78.33811448348496, 78.39409737006262, 78.45073133117388, 77.40271093532404,
78.14754301619742, 78.29073591677286, 78.20984708408737, 77.58599589624374, 77.50354215075774, 74.49757141289503,
77.7276672803666, 74.37167194076233, 74.04065468827585, 78.18592122242832, 78.63426482129661, 74.59491249776092]
f21=[0.007917562416945053, 0.008151915801430798, 0.008694667137021531, 0.009298857060978374, 0.009168856063992566, 0.008393988454835794, 0.009356937434857335, 0.00944301517076346, 0.008052155456294353, 0.007891764380788865, 0.008955166010251241, 0.00823125303080821, 0.009324932673847845, 0.009564614590386999, 0.008460548514006244, 0.008326270775816673, 0.00829068236337162, 0.009167415032401014, 0.008674229967017484, 0.008570277672074586, 0.008634748200016893, 0.009081593338821761, 0.009103629944510878, 0.009379318906272775, 0.00897481373615487, 0.009419446727519166, 0.009517387594754897, 0.008666954147779366, 0.007889234462668473, 0.00931283329983273]
f1=[76.09611889350377, 78.77730268287569, 77.27692095290696, 78.66804524192476, 78.05854827300608, 78.72977555318688,
77.86763080696251, 78.47870754906403, 78.2432740754877, 79.0176228328904, 78.78766830591486, 77.79220146161504,
78.0416057000793, 78.91770303778918, 78.10175093982203, 78.69063008870197, 77.8448065926295, 78.89257481607883,
78.84616875980842, 78.54240776126834, 77.92089708265037, 78.27069703784417, 78.89814401504553, 77.26379035039697,
78.4852605896078, 78.4483362995136, 78.62594386393594, 76.95302464521706, 78.07787701339166, 78.54801211464334]
f2=[0.008957420243593904, 0.008201290740429946, 0.008927274457396635, 0.008288478456987991, 0.00876020337183325, 0.00821775769307678, 0.00884697549908514, 0.008564012376663105, 0.008693185801597466, 0.00735141379320691, 0.008121597040711687, 0.008870144914246, 0.008814175569114886, 0.007816144483473175, 0.008752339154269444, 0.008251089419735406, 0.008854797069740515, 0.00797346990413977, 0.00810949970682477, 0.008479282602830965, 0.0088147904312125, 0.008656288021137467, 0.007818774436980862, 0.008933195248335789, 0.008530920794556343, 0.008610826245068343, 0.008429900737165834, 0.008944929590962195, 0.008752409225371844, 0.008464885127027401]
f11 = [78.13158237224876, 79.67913916248689, 79.40202899951338, 78.77272197444738, 79.59917444374956,
80.09035223332909, 79.6681397124661, 78.34080376201238, 78.12819077368123, 79.85563519006915,
80.52055147165817, 79.30631771622784, 79.8274288624724, 79.56041457679224, 80.21400194139083,
79.73638571878287, 79.84995062609373, 78.26840266326194, 78.3831285983927, 79.52416434639552,
79.33923792160981, 79.05746289378486, 79.11942123132677, 79.42490159278476, 79.89660802047895,
78.79239337163062, 77.47565821766244, 79.29407602757921, 79.66940798370524, 79.77125064402064]
f12 = [0.22231773601132473, 0.16350837224085044, 0.17312398799855006, 0.18963403819980326, 0.16713480177497708,
0.14600814666994671, 0.16578890122242448, 0.19839836350150053, 0.22423854376689586, 0.1571067600159749,
0.12792181499374417, 0.1747848367451167, 0.15790084421713313, 0.16762497001543297, 0.1444292252839702,
0.16218682974741622, 0.15757268651940703, 0.2155643486159565, 0.19023432849851585, 0.16929884872510073,
0.17450508391491218, 0.1832180145938337, 0.18271473993899678, 0.1707995960118773, 0.15515245415593762,
0.1894473149044883, 0.23583166359095892, 0.1765863721724546, 0.16394723572377376, 0.16163081747436026]
f21 = [78.31098477060134, 78.82560236305012, 78.57826894095565, 78.3108960440399, 78.5854728828511,
77.30031160364588, 78.11383167173456, 78.25213341781318, 78.04134358140921, 78.77412389989188,
77.9454224332219, 78.97431294265247, 79.09061910039671, 78.48348634443312, 78.21024906731701,
78.4721077341294, 78.97911928203568, 77.55794714768187, 77.08805834582111, 78.53105259648503,
77.71578342289433, 77.50550382969944, 78.43462896476744, 78.9513392331249, 79.11843761386997,
78.9294332432202, 78.1978485303893, 78.7511370236766, 78.58663330340367, 77.7955757103145]
f22 = [0.2911141433778622, 0.27823663193938153, 0.28568828153083287, 0.2913045174684795, 0.28494162087279007,
0.30198200261447683, 0.2936150040593367, 0.2920916867844547, 0.2959621683803247, 0.2807112259494087,
0.29615233759813037, 0.27271478371269403, 0.26918049567143515, 0.287245782388438, 0.29221192743690416,
0.28865182933677797, 0.2711034108106382, 0.300264700268352, 0.30252685474214913, 0.286811199780341,
0.2994874545333383, 0.300273046692719, 0.2887174952405154, 0.27418992817388244, 0.26076702354427583,
0.2777877052773878, 0.2923068759498851, 0.2817938400732662, 0.2844466978672097, 0.2976794824343081]
f31 = [80.40384249037861, ]
f32 = [0.14848535240622637]
labels = ["proposed NSGA2-communication first", "proposed NSGA2-localization first", "pso-weighting method",
"pso-main objective method","pso-weighting method-localization first","pso-main objective method-localization-first"]
f41 = [81.46866648101934, ]
f42 = [0.1379323588640624]
f51 = [81.20664927884438, ]
f52 = [0.269883203999093]
f61 = [81.21235572744315, ]
f62 = [0.2577773453056189]
plt.xlabel('average snr', fontsize=12)
plt.ylabel('average 1/gdop', fontsize=12)
plt.scatter(f11, f12, label=labels[0])
plt.scatter(f21, f22, label=labels[1])
plt.scatter(f31, f32, label=labels[2])
plt.scatter(f41, f42, label=labels[3])
plt.scatter(f51, f52, label=labels[4])
plt.scatter(f61, f62, label=labels[5])
plt.legend()
plt.show()
import numpy as np
import random
import time
zero_threshold = 0.00000001
class KMNode(object):
def __init__(self, id, exception=0, match=None, visit=False):
self.id = id
self.exception = exception
self.match = match
self.visit = visit
class KuhnMunkres(object):
def __init__(self):
self.matrix = None
self.x_nodes = []
self.y_nodes = []
self.minz = float('inf')
self.x_length = 0
self.y_length = 0
self.index_x = 0
self.index_y = 1
def __del__(self):
pass
def set_matrix(self, x_y_values):
xs = set()
ys = set()
for x, y, value in x_y_values:
xs.add(x)
ys.add(y)
#选取较小的作为x
if len(xs) < len(ys):
self.index_x = 0
self.index_y = 1
else:
self.index_x = 1
self.index_y = 0
xs, ys = ys, xs
x_dic = {x: i for i, x in enumerate(xs)}
y_dic = {y: j for j, y in enumerate(ys)}
self.x_nodes = [KMNode(x) for x in xs]
self.y_nodes = [KMNode(y) for y in ys]
self.x_length = len(xs)
self.y_length = len(ys)
self.matrix = np.zeros((self.x_length, self.y_length))
for row in x_y_values:
x = row[self.index_x]
y = row[self.index_y]
value = row[2]
x_index = x_dic[x]
y_index = y_dic[y]
self.matrix[x_index, y_index] = value
for i in range(self.x_length):
self.x_nodes[i].exception = max(self.matrix[i, :])
def km(self):
for i in range(self.x_length):
while True:
self.minz = float('inf')
self.set_false(self.x_nodes)
self.set_false(self.y_nodes)
if self.dfs(i):
break
self.change_exception(self.x_nodes, -self.minz)
self.change_exception(self.y_nodes, self.minz)
def dfs(self, i):
x_node = self.x_nodes[i]
x_node.visit = True
for j in range(self.y_length):
y_node = self.y_nodes[j]
if not y_node.visit:
t = x_node.exception + y_node.exception - self.matrix[i][j]
if abs(t) < zero_threshold:
y_node.visit = True
if y_node.match is None or self.dfs(y_node.match):
x_node.match = j
y_node.match = i
return True
else:
if t >= zero_threshold:
self.minz = min(self.minz, t)
return False
def set_false(self, nodes):
for node in nodes:
node.visit = False
def change_exception(self, nodes, change):
for node in nodes:
if node.visit:
node.exception += change
def get_connect_result(self):
ret = []
for i in range(self.x_length):
x_node = self.x_nodes[i]
j = x_node.match
y_node = self.y_nodes[j]
x_id = x_node.id
y_id = y_node.id
value = self.matrix[i][j]
if self.index_x == 1 and self.index_y == 0:
x_id, y_id = y_id, x_id
ret.append((x_id, y_id, value))
return ret
def get_max_value_result(self):
ret = 0
for i in range(self.x_length):
j = self.x_nodes[i].match
ret += self.matrix[i][j]
return ret
def run_kuhn_munkres(x_y_values):
process = KuhnMunkres()
process.set_matrix(x_y_values)
process.km()
return process.get_connect_result()
# def test():
# values = []
# random.seed(0)
# for i in range(500):
# for j in range(1000):
# value = random.random()
# values.append((i, j, value))
#
# return run_kuhn_munkres(values)
if __name__ == '__main__':
s_time = time.time()
# ret = test()
# print("time usage: %s " % str(time.time() - s_time))
values = [
(1, (1,1), 3),
(1, (3,3), 4),
(2, (1,1), 2),
(2, (2,2), 1),
(2, (3,3), 3),
(3, (2,2), 4),
(3, (3,3), 5)
]
print(run_kuhn_munkres(values))
\ No newline at end of file
from itertools import combinations
import Users
import tool
import GDOP
import copy
import math
def get_p_association_first(users,uavs,service_num_p,service_num_c):
p_connection = {}
for i in range(len(users)):
p_connection[i]=[]
uavs_initial=[i for i in range(len(uavs))]
uav_group_all=list(combinations(uavs_initial, 3))
uav_serive_num = [service_num_p for i in range(len(uav_group_all))]
uav_serive_num_c=[service_num_c for i in range(len(uavs))]
# 获得所有信道数量大于0的无人机编号
for i in range(len(users)):
uav_need = [i for i in range(len(uav_group_all)) if uav_serive_num[i] > 0]
uav_group = [uav_group_all[i] for i in uav_need]
gdop_min = float('inf')
index = 0
for j in range(len(uav_group)):
uavs_pos = [uavs[uav_group[j][0]], uavs[uav_group[j][1]], uavs[uav_group[j][2]]]
gdop_current = GDOP.calculate_gdop(uavs_pos, copy.copy(users[i]))
if gdop_current < gdop_min:
gdop_min = gdop_current
index = j
print(gdop_min)
# for k in range(len(uav_group[index])):
p_connection[i].extend([uav_group[index][0],uav_group[index][1],uav_group[index][2]])
uav_serive_num[index] -= 1
c_connection={}
for i in range(len(users)):
uav_need = [i for i in range(len(uavs)) if uav_serive_num_c[i] > 0]
min=float('inf')
node=-1
for j in range(len(p_connection[i])):
if p_connection[i][j] in uav_need:
dis=tool.calculate_3d_distance(uavs[p_connection[i][j]],users[i])
if min>dis:
min=dis
node=p_connection[i][j]
c_connection[i]=node
uav_serive_num_c[node]-=1
# print(c_connection)
for i in range(len(p_connection)):
p_connection[i].remove(c_connection[i])
# print(p_connection)
return c_connection,p_connection
if __name__ == '__main__':
users=Users.getUsers("./data.csv")
uavs=tool.getUavInitialPos(3,users)
uavs_initial = [i for i in range(len(uavs))]
combination=list(combinations(uavs_initial, 3))
print(get_p_association_first(users,uavs,math.ceil(len(users)/len(combination)),math.ceil(len(users)/len(uavs))))
# uav_group = list(combinations(uav_need, 1))
# print(uav_group)
\ No newline at end of file
import math
import Users
import numpy as np
import random
from pprint import pprint
class PSO:
def __init__(self,users,cal_tool,N=60):
#之后解析JSON,从JSON中读参数
self.N=N
self.cal_tool=cal_tool
self.d = 3 # 可行解维数
self.limit = [0, 1000] # 边界位置限制
self.vlimit = [-100, 100] # 边界速度限制
self.height = 100
self.wmax = 1.5 # 惯性权重
self.wmin = 0.3
self.c1 = 2 # 自我学习因子
self.c2 = 2 # 群体学习因子
# self.c1 = 0.5 # 自我学习因子
# self.c2 = 0.5 # 群体学习因子
self.maxgen = 200
# self.users = Users.getUsers("./data.csv")
self.users = users
# #todo:防止无人机位置碰撞
# def punish_function(self,uavs):
# # user_arr = [1, 2, 5]
# punish=0
# for i in range(len(uavs)):
# for j in range(i+1,len(uavs)):
# dis=self.cal_tool.getDistance(uavs[i],uavs[j])
# if dis<200:
# punish+=100
#
# return punish
# 初始化粒子群,k是无人机数量
def initParticle(self, k, users):
X = []
# users=Users.generate(100)#用户位置
V = np.random.uniform(self.vlimit[0], self.vlimit[1], (self.N, k, 3))
for i in range(self.N):
uavs=[]
for index in range(k):
x=np.random.randint(self.limit[0],self.limit[1])
y=np.random.randint(self.limit[0],self.limit[1])
z=self.height
uavs.append([x,y,z])
# uavs = self.cal_tool.getUavInitialPos(k, users,self.height[0])
X.append(uavs)
X = np.array(X)
return X, V
# 初始化个体和全局最佳历史位置和最佳适应度
def initBest(self, X, k):
p_pos = X.copy() # 每个个体的历史最佳位置
global_pos = np.zeros((k, 3)) # 种群的历史最佳位置5*3
p_best = np.full((self.N, 1), float('-inf')) # 每个个体的历史最佳适应度
global_best = float('-inf') # 种群历史最佳适应度
return p_pos, global_pos, p_best, global_best
def pso(self, X, V, k,get_fitness):
# X, V, users = initParticlePos()
p_pos, global_pos, p_best, global_best = self.initBest(X, k)
result = np.zeros(self.maxgen)
for iter in range(self.maxgen):
# fitness = self.getfitness(X, users, k,P) # 计算所有粒子适应度
fitness = np.zeros(self.N)
for i in range(len(X)):
_,_,fitness[i]= get_fitness(self.users,X[i])
for i in range(self.N):
if fitness[i] > p_best[i]:
p_best[i] = fitness[i] # 更新个体历史最佳适应度
p_pos[i] = X[i].copy() # 更新个体历史最佳位置(取值)
if max(p_best) > global_best:
global_best = max(p_best) # 更新群体历史最佳适应度
max_index = p_best.argmax()
global_pos = X[max_index].copy() # 更新群体历史最佳位置
# 权重更新
w = self.wmax - iter * (self.wmax - self.wmin) / self.maxgen
for i in range(self.N):
V[i] = V[i] * w + self.c1 * random.random() * (p_pos[i] - X[i]) + self.c2 * random.random() * (
global_pos - X[i])
# print(V[i])
for j in range(len(V[i])):
for p in range(len(V[i][j])):
if V[i][j][p] > self.vlimit[1]:
V[i][j][p] = self.vlimit[1]
# V[i][j][p] = self.vlimit[0]+np.random.rand(1)*(self.vlimit[1]-self.vlimit[0])
elif V[i][j][p] < self.vlimit[0]:
V[i][j][p] = self.vlimit[0]
# print(V[i])
# 位置更新
X = X + V
# 边界位置处理
for i in range(self.N):
for j in range(len(X[i])):
for p in range(2):
if X[i][j][p] > self.limit[1]:
X[i][j][p] = self.limit[1]
elif X[i][j][p] < self.limit[0]:
X[i][j][p] = self.limit[0]
if X[i][j][2] > self.height:
X[i][j][2] = self.height
elif X[i][j][2] < self.height:
X[i][j][2] = self.height
result[iter] = global_best
# print(iter,global_pos,global_best)
# print(global_best)
# print(global_pos)
return global_pos,global_best,result
if __name__ == '__main__':
print()
30 200 4 15
ts 136.61536121368408s
f11=[54.0507626287143, 52.96308084332225, 53.81164827066072, 52.662348665211766, 53.058950945849816, 54.19019342328689, 53.9299688459228, 53.11426657277529, 53.53448095960305, 53.41244012096225, 52.161071436391765, 53.63152603890542, 52.60717139811691, 52.9419652152142, 53.12691669130094, 54.769726980442876, 53.221038636189846, 53.273098613877536, 54.813441694286276, 52.444405907733056, 52.07495261632682, 53.65582251950728, 54.572560522519765, 53.34200366227426, 52.951982284304776, 54.73271397453529, 54.740843042254234, 54.62014017494, 54.65028166545009, 54.058041455437795]
f12=[-2.6593781859878236, -2.543101161647058, -2.629703840153344, -2.5232018979680153, -2.5456278171312903, -2.6935826769370554, -2.6471125403460376, -2.553281887750045, -2.5912253989127305, -2.575347927941496, -2.507729928482692, -2.6029178154110104, -2.519878280391824, -2.5396945038293763, -2.554082938296093, -2.8538301515033497, -2.5609278449877055, -2.566614987963588, -2.9048977606725277, -2.5105198789979197, -2.491221788958603, -2.622021879332393, -2.772197542173876, -2.5684940830071743, -2.540468767759957, -2.827654957571949, -2.8307525713156143, -2.7958452945775663, -2.808613976366928, -2.6603893135495023]
linear
f21=[54.050685006781094, 54.283393761916976, 54.47656291210348, 54.74324070888281, 53.99842379062622, 51.528636671309236, 52.75218963603528, 54.84114777226443, 54.273369607211556, 53.58254967717716, 54.58375169247761, 51.284494357009486, 54.89359217394771, 53.600798991323046, 50.86788233140609, 54.476286152752024, 52.255896253350805, 54.65071141233971, 53.95519536414517, 53.282677590253826, 53.64150189178759, 54.134345252288654, 53.76200008453646, 51.57929194812203, 54.901465412391964, 54.05680886961717, 51.37917279898564, 52.04171632091941, 54.39133221686892, 54.74753796495144]
f22=[-2.654986150981363, -2.693018355944383, -2.7210723464506525, -2.7864337596677493, -2.6518544908865724, -2.444966870948845, -2.5464415029504903, -2.8258801390793424, -2.692146096562049, -2.5976241860819047, -2.7424514298711387, -2.438197829313505, -2.8528428455891137, -2.599653195343768, -2.431283621244636, -2.718041590820195, -2.485692740495766, -2.7714866271755527, -2.641513633880053, -2.5780465532926784, -2.6057845459446995, -2.6672188815808133, -2.6210307516417344, -2.445576451080987, -2.880499673026878, -2.660973875292016, -2.440809680204474, -2.4685965016751674, -2.705178447946934, -2.788315779933751]
30 200 5 30
f21=[51.334550890077836, 51.439931078634245, 51.683248011667956, 51.79320986700474, 51.74773078781322, 51.066584115404, 51.465600927140144, 50.91638741289003, 51.435648773245056, 50.94435567401892, 50.80237756584818, 51.11468577768979, 50.924785079829604, 51.578759424591475, 50.05252986777546, 51.075165500431204, 50.92063662520722, 50.80907917792338, 50.80582860326489, 51.246941894012174, 51.72772609250578, 51.08659894862157, 50.99738248640082, 51.46728162136219, 50.89467711194264, 51.87174348917633, 51.82639082365849, 50.993598263077686, 51.1913242679079, 51.21836600037675]
f22=[-2.566384248015569, -2.592968131062478, -2.696891979673827, -2.745844761338047, -2.728883383157762, -2.5121329706826527, -2.6112407203328982, -2.491221796089005, -2.591229007662642, -2.4984741419357577, -2.4806567659555645, -2.524850247488119, -2.4921996101705193, -2.6676583378520307, -2.409158020041916, -2.516711583016044, -2.4917306582487626, -2.4811503760525326, -2.4811211415350547, -2.550114654729561, -2.7031389569361743, -2.519740686177889, -2.502019524544895, -2.6142072933500042, -2.4905090225082773, -2.8293998979711334, -2.7980034318716367, -2.501470477979192, -2.540907235037267, -2.5448328297185085]
30 200 3 6
f31=[56.46907510714308, 56.31152006835182, 56.5069364355453, 56.65546579871943, 57.65572244421892, 56.537074313489654, 54.728001286126414, 56.71257763559322, 55.8790430205371, 56.31392385285384, 56.252242015120736, 55.72214664981578, 56.73305359657204, 54.73482564422065, 57.707600420188705, 55.73433913222626, 55.691417796384265, 56.665708111562225, 56.70578493156345, 56.62844599901684, 56.57821174331196, 56.76137252714323, 55.452059302856135, 57.49377772545475, 54.920993137552166, 56.614387469145534, 57.418712640751615, 56.04918950267493, 55.95185466451161, 57.51701412781926]
f32=[-3.027839142216957, -2.985878123714967, -3.0587403682717293, -3.1735775860398334, -4.1253845778201095, -3.066336190194695, -2.794401394953883, -3.21329609374846, -2.8850163579446826, -2.986885978939206, -2.9712895163027397, -2.866333453680601, -3.2350971885172064, -2.7947129156080197, -4.142099402500488, -2.874634676486394, -2.8563855146463712, -3.188822319243743, -3.210607568911858, -3.138741942898081, -3.0963794118572636, -3.2542231629655984, -2.8533669810824875, -3.8719649467160626, -2.8155056230211994, -3.1174818497736854, -3.8596923965708885, -2.9166464040747044, -2.9074874484447832, -3.8914722244903897]
3 10 15.384773015975952s
f11[53.15701374063989, 53.121439465960066, 50.80182203069932, 52.57704773190993, 52.116421205820686, 52.09329273740436, 52.399972462185715, 53.01678997498576, 50.807170387786, 53.326298012750634, 53.34190566809375, 50.81184773390719, 52.03451804459312, 51.9861301449006, 51.28067896102526, 53.325828586097074, 52.49847609177091, 49.292408973950806, 50.02228891711617, 51.72293287997159, 53.377990911067855, 52.08613787626742, 52.25767760436143, 53.38191040988062, 48.85624274835523, 52.25767760436143, 48.271449563838516, 52.18120069954898, 51.51698294628223, 53.19965725636094]
f12=[-4.7424166355797785, -4.513453375218427, -3.5943890061967876, -4.167452148384593, -3.8484763795448247, -3.8029009898454946, -4.037622926103712, -4.308518223735279, -3.5983506584093816, -5.287712830251175, -5.288431056864009, -3.6024041003298928, -3.793501824363529, -3.7683812816092397, -3.6202386010254024, -5.282493280214469, -4.104132449665276, -3.410528994407205, -3.4687279171780445, -3.725358712425691, -5.6681441205003775, -3.801806630712472, -3.972890625225026, -6.021619944112665, -3.4011907565203017, -3.972890625225026, -3.3791900861821937, -3.853850446523785, -3.645392363317767, -4.905403808886767]
3 20 65.87500405311584
f21=[45.834016331970325, 46.842404026080104, 45.94045152723605, 46.42827224025241, 46.251855922061814, 44.62584487748428, 46.89676226877265, 44.57046417411123, 47.41368813518143, 45.349395457193516, 47.08118934629392, 44.261763305736466, 46.401612819374726, 45.73940940353238, 46.835575183380456, 45.77541441143831, 47.3008955908348, 47.11031927291376, 44.679187273276305, 47.39251804257596, 47.20097887444749, 46.68052902779725, 47.50215603042076, 46.91697172969312, 46.16228709110786, 44.809257534469836, 45.926227268456664, 45.81400260193812, 47.44277260841224, 46.42827224025241]
f22=[-3.602227997889564, -3.7693855290562523, -3.632090146991377, -3.669691119481263, -3.637898796537504, -3.5718140421956512, -3.7988305944632748, -3.5644165862648656, -4.007652260162592, -3.5773993228856917, -3.8420823362404994, -3.547425831167228, -3.66454936187507, -3.5919482349036813, -3.725333399844625, -3.594369753236859, -3.8975035520421812, -3.8773725839117015, -3.5720637484629956, -3.9760226708214175, -3.883487728725116, -3.70330819927777, -4.10293633804125, -3.8399525976708935, -3.6340000246124724, -3.573425351082262, -3.6092631849525105, -3.599299254708529, -4.017091540549122, -3.669691119481263]
linear 91.6108136177063
f21_l=[46.79618184949475, 46.66173057329805, 47.048035449057245, 46.69420057121491, 46.53565738757049, 46.66161883107671, 46.1235761225788, 47.241066700521785, 46.611503519410846, 46.5229736380701, 47.09594822228021, 47.12455615201715, 46.003817954398684, 46.46336942734452, 47.04083977120062, 46.986035176967526, 47.07780200662248, 47.11707528453678, 47.28482107224288, 47.057084907593236, 46.71413609531813, 46.95838300559289, 46.98060186587708, 46.909028521789125, 47.092370130946236, 46.131922988760394, 46.75734538408214, 46.04274075369345, 47.14300506574648, 46.54637252224787]
f22_l=[-3.709122162038647, -3.6847169991471787, -3.7857050799838134, -3.6897570032031304, -3.66527004040039, -3.68469729515044, -3.6170565700424824, -3.8622391074070967, -3.676220943137094, -3.6636864028390064, -3.8055132164666987, -3.811329737079722, -3.605462567892802, -3.6567498090628563, -3.7851108435773755, -3.7619491560879013, -3.788187839985887, -3.8081523457403312, -3.8807695502446364, -3.78695250942519, -3.6976590423082216, -3.753304317282158, -3.760147474280349, -3.741238771314687, -3.804596894111487, -3.6327395231058985, -3.70536316854747, -3.615544928590912, -3.8182133648282433, -3.6666538282669876]
4 10 59.793779134750366
f31=[54.52245664123465, 55.959013088613474, 55.90919524888748, 56.04323778793106, 56.62688910064067, 56.527310681276084, 56.97600661134239, 56.804251461885976, 55.89222842050642, 55.51308351465983, 55.581478667918034, 54.42201774010683, 56.18377711686112, 56.4518813332583, 56.15200217930927, 57.08709543815009, 55.07239767017169, 54.633243985137916, 56.97454773954313, 56.17561419615326, 54.858042350200506, 56.56923529266034, 54.8471048892334, 56.61624965775959, 56.18377711686112, 56.46129792339117, 55.04642864123899, 55.77653197200065, 54.41935176901326, 56.183162384285275]
f32=[-2.3894560859047718, -2.503557193006404, -2.496198934326645, -2.5361925139069315, -2.73527987814952, -2.6801974621808853, -2.8784200648565887, -2.8044862060003446, -2.4905777651047996, -2.437403277202888, -2.460102424252358, -2.382228126320782, -2.6355501399682764, -2.6427826731164634, -2.5736419648400872, -2.9360719176142496, -2.4174280695654993, -2.394797245270132, -2.8291712528173045, -2.592587372358513, -2.4042744982395474, -2.7019810214304445, -2.3957679672104257, -2.7280756174286314, -2.6355501399682764, -2.657128100796301, -2.4120154234175217, -2.4834794164187377, -2.362570181158639, -2.6193303855868253]
4 20 288.8421359062195
f41=[51.741931566142526, 51.769393918636595, 51.4289451536845, 51.98822686920067, 50.461344139017676, 52.07141903589688, 51.20667675520541, 51.66049358343737, 51.68361280228959, 51.92241969980686, 51.4372372254511, 51.68389406273518, 51.37708272396709, 51.61591325907106, 51.71059140008647, 49.691927796142025, 51.61740030254972, 51.9523760025977, 50.91915418812668, 51.983748122984935, 51.04638364116797, 49.719832111034364, 51.34478938510604, 51.83586291877852, 51.99810830317019, 51.60888878340478, 51.29566477611089, 51.881135193618526, 51.98866858853559, 50.192225612156186]
f42=[-2.807628072853997, -2.8115086214045144, -2.7473289441363424, -2.895768951777114, -2.659690550988313, -2.964548645290694, -2.6990415981837326, -2.797083370049629, -2.8029268344139178, -2.849226454640806, -2.756608871451027, -2.80406672890553, -2.73197709613222, -2.7861828793299486, -2.80599414790823, -2.6372127023852006, -2.789837667382157, -2.859644002149485, -2.670784257045365, -2.887935524744255, -2.6919251396932364, -2.6541055308766763, -2.7115026939622626, -2.829755867138337, -2.9014524787009863, -2.7569856303387557, -2.709519873808802, -2.832857043616753, -2.898140230132415, -2.657812119234906]
[2.469273328781128, 7.421365737915039, 15.89266562461853, 30.616859912872314, 41.11850118637085, 48.21879506111145, 90.0976836681366, 85.44814968109131, 100.62214803695679, 140.64940476417542]
ts
[11.955068588256836, 18.25909113883972, 14.64045238494873, 16.398587226867676, 12.18566083908081, 10.024715662002563, 16.576231479644775, 12.345167398452759, 19.49023723602295, 15.916483640670776]
linear
[17.869938373565674, 19.484696865081787, 18.30145573616028, 17.97358202934265, 17.8395037651062, 17.644514799118042, 20.304096460342407, 16.842082262039185, 19.157524585723877, 17.43966555595398]
import math
import scipy.integrate
import numpy as np
from sklearn.cluster import KMeans
import GDOP
from itertools import combinations
import copy
import Users
# from Match import Match
import km
def calculate_3d_distance(a, b):
return math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2) + math.pow(a[2] - 0, 2))
# 计算3d距离
def calculate_2d_distance(a, b):
return math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2))
# 计算森林信道路径损耗
def forest_path_loss(uav, user):
dis = calculate_3d_distance(uav, user)
alpha = 3.5
A = 0.25
C = 0.39
E = 0.25
G = 0
B = 1
H = 0.05
f_c = 2 * 10 ** 9
c = 1 * 10 ** 8
path_loss = 10 * alpha * math.log10(dis)
theta = math.asin(uav[2] / dis)
theta = math.degrees(theta)
dis1 = 5 * dis / uav[2] # 树叶的高度
slant = A * math.pow(f_c / 1e6, C) * math.pow(dis1, E) * math.pow(theta + G, H)
fspl = 20 * math.log10(4 * math.pi * 1 * f_c / c)
L_K_N = slant + fspl + path_loss
return L_K_N
def expect_L(l1):
sigma = 3
R_u = lambda x1: ((10 ** (-(l1 + x1) / 10))) * 1 / (math.sqrt(2 * math.pi) * sigma) * math.exp(
-(x1 ** 2) / (2 * sigma ** 2))
R2, err = scipy.integrate.quad(R_u, -float("100"), float("100"))
return R2
def path_loss_dis(dis,h):
a = 9.6
b = 0.28
los = 1
nlos = 20
freePathLoss = 20 * math.log10(dis) + (20 * math.log10(2000000000)) + 20 * math.log10(4 * (math.pi) / 3 / 100000000)
angle = math.asin(h / dis)
angle = angle / math.pi * 180
plos = 1 / (1 + a * math.exp(-b * (angle - a)))
pnlos = 1 - plos
pl = plos * los + pnlos * nlos + freePathLoss
return pl
def free_path_loss(dis):
freePathLoss = 20 * math.log10(dis) + (20 * math.log10(2000000000)) + 20 * math.log10(4 * (math.pi) / 3 / 100000000)
return freePathLoss
# 计算snr
def cal_snr(uav, user, p):
# loss = forest_path_loss(uav, user)
dis=calculate_3d_distance(uav,user)
loss=path_loss_dis(dis,uav[2])
noise_power = (10 ** (-117 / 10)) / 1000
snr = p * (10 ** (-loss / 10)) / noise_power
return 10 * math.log10(snr)
# 计算数据传输速率
def cal_data_rate(snr, bandwidth):
date_rate = bandwidth * math.log2(1 + snr)
return date_rate
def dbmToW(p):
return pow(10, p / 10) / 1000
#获得每个用户的定位无人机组
def get_user_loc_uav(users,p_association):
user_loc_uav={}
for i in range(len(users)):
user_loc_uav[i]=[]
for i in range(len(p_association)):
for j in range(len(p_association[i])):
if p_association[i][j]==1:
user_loc_uav[j].append(i)
return user_loc_uav
#贪心关联
def get_association(users,uavs):
return
def getUavInitialPos(k, users):
model = KMeans(n_clusters=k, # 聚类簇数
random_state=1, # 决定质心初始化的随机数生成,使用int使随机性具有确定性。
max_iter=300, # 执行一次k-means算法所进行的最大迭代数,默认300
).fit(users)
center = model.cluster_centers_
uavs = []
for item in center:
# height = random.randint(100, 800)
height = 100
position = [int(item[0]), int(item[1]), height]
uavs.append(position)
# print(center)
return uavs
def get_c_association(users,uavs_pos,serveMax):
user_num = len(users)
uavs = [k for k in range(len(uavs_pos))]
uav_num = len(uavs)
# print(distance_sum)
weight = np.zeros((user_num, uav_num), dtype=np.float16)
graph = []
for i in range(user_num):
for j in uavs:
# weight[i][j]=-self.distance_c[i][j]/(distance_sum[i]-self.distance_c[i][j])
weight[i][j] = -calculate_3d_distance(uavs_pos[j],users[i])
dic = {}
for i in range(user_num):
for j in uavs:
for number in range(serveMax):
graph.append((i, j + 100 * number, weight[i][j]))
dic[j + 100 * number] = j
connection = km.run_kuhn_munkres(graph)
c_connection = {}
for connect in connection:
c_connection[connect[0]] = dic[connect[1]]
# print(c_connection)
return c_connection
def get_uav_to_user(c_connection,uavs):
uav_to_user={}
for i in range(len(uavs)):
uav_to_user[i]=[]
for i in c_connection:
uav_to_user[c_connection[i]].append(i)
return uav_to_user
# 选择好通信的无人机后,确定其他两架无人机与该无人机对用户获得最优的gdop值
def get_p_association(users,uavs,c_connection,service_num):
p_connection={}
for i in c_connection:
p_connection[i]=[]
if len(uavs)==3:
for i in range(len(users)):
uavs_all=[i for i in range(len(uavs))]
uavs_all.remove(c_connection[i])
p_connection[i]=[uavs_all[0],uavs_all[1]]
else:
uavs_initial = [i for i in range(len(uavs))]
uav_group_all = list(combinations(uavs_initial, 3))
uav_serive_num = [service_num for i in range(len(uav_group_all))]
uav_group_dic={}
for i in range(len(uav_group_all)):
uav_group_dic[uav_group_all[i]]=i
# uav_serive_num=[service_num for i in range(len(uavs))]
for i in range(len(users)):
#获得所有信道数量大于0的无人机编号
# uav_need=[i for i in range(len(uavs)) if uav_serive_num[i]>0]
uav_need = [i for i in range(len(uav_group_all)) if uav_serive_num[i] > 0]
uav_groups = [uav_group_all[i] for i in uav_need]#所有可用的uav_group
#移除通信的无人机
uav_group=[]
uav_dic={}
count=0
for group in uav_groups:
if c_connection[i] in group:
tmp=[group[0],group[1],group[2]]
tmp.remove(c_connection[i])
uav_group.append(tmp)
uav_dic[count]=group#找到group对饮的下标
count+=1
# uav_need.remove(c_connection[i])
# uav_group=list(combinations(uav_need, 2))
gdop_min = float('inf')
index = 0
for j in range(len(uav_group)):
uavs_pos = [uavs[c_connection[i]], uavs[uav_group[j][0]],uavs[uav_group[j][1]]]
gdop_current = GDOP.calculate_gdop(uavs_pos, copy.copy(users[i]))
if gdop_current < gdop_min:
gdop_min = gdop_current
index = j
# print(gdop_min)
p_connection[i].extend([uav_group[index][0], uav_group[index][1]])
uav_serive_num[uav_group_dic[uav_dic[index]]]-=1
# print(p_connection)
return p_connection
def get_p_by_snr(snr,uav,user,noise):
dis = calculate_3d_distance(uav, user)
pl= path_loss_dis(dis, uav[2])
# pl=path_loss_dis(uav,user)
noise=dbmToW(noise)
p=(10**(snr/10))*noise/10**(-pl/10)
# print(p)
return p
def get_rest_p(users,uavs,p_connection,snr_thre=0,noise=-117,pmax=0.1):
p_rest=[pmax for i in range(len(uavs))]
for user_index in p_connection:
uav_group=p_connection[user_index]
for uav_index in uav_group:
p_need=get_p_by_snr(snr_thre,uavs[uav_index],users[user_index],noise)
p_rest[uav_index]-=p_need
return p_rest
if __name__ == '__main__':
users=Users.getUsers("./data.csv")
uavs=getUavInitialPos(3,users)
c_connection=get_c_association(users,uavs,math.ceil(len(users)/len(uavs)))
p_connection=get_p_association(users,uavs,c_connection,math.ceil(len(users)*2/len(uavs)))
print(get_p_by_snr(20,uavs[2],users[0],-117))
# print(get_rest_p(users,uavs,p_connection))
\ No newline at end of file
import random
import math
from matplotlib import pyplot as plt
def objective_function(x):
# 定义优化的目标函数,此处以一个简单的二维函数为例
return (x[0] - 2) ** 2 + (x[1] - 3) ** 2
def generate_neighbor(x):
# 在当前解的邻域内随机生成新解
return [x[0] + random.uniform(-0.1, 0.1), x[1] + random.uniform(-0.1, 0.1)]
def tabu_search(max_iter):
current_solution = [0, 0] # 初始解
best_solution = current_solution # 记录最优解
best=[]
tabu_list = [] # 禁忌表
tabu_tenure = 10 # 禁忌期限,即禁忌解在禁忌表中停留的迭代次数
for i in range(max_iter):
neighbors = [generate_neighbor(current_solution) for _ in range(10)] # 随机生成10个邻域解
# 在邻域解中选择一个非禁忌的最优解
candidate = min(neighbors, key=objective_function)
while candidate in tabu_list:
neighbors.remove(candidate)
candidate = min(neighbors, key=objective_function)
# 更新当前解和最优解
current_solution = candidate
if objective_function(candidate) < objective_function(best_solution):
best_solution = candidate
best.append(objective_function(best_solution))
tabu_list.append(candidate) # 将当前解加入禁忌表
if len(tabu_list) > tabu_tenure: # 维护禁忌表的长度不超过禁忌期限
tabu_list.pop(0)
return best_solution,best
def drawResultAndIter(r1,r2,r3):
f, ax = plt.subplots(1, 1)
plt.plot(r1)
plt.plot(r2)
plt.plot(r3)
plt.axhline(y=60, color='r', linestyle='--', label='Horizontal Line at y=60')
ax.set_xlabel('iteration')
ax.set_ylabel('number of non-dominated solutions')
plt.show()
if __name__ == "__main__":
# num2=[2, 3, 9, 11, 7, 10, 14, 11, 12, 9, 14, 15, 16, 16, 15, 14, 15, 15, 15, 16, 19, 20, 20, 19, 23, 21, 21, 23, 26, 28,
# 28, 28, 29, 31, 32, 35, 34, 34, 34, 36, 37, 37, 37, 38, 38, 39, 39, 39, 39, 40, 40, 44, 45, 45, 45, 45, 45, 41, 41,
# 42, 41, 43, 44, 45, 44, 47, 46, 47, 48, 49, 50, 53, 53, 53, 52, 54, 55, 56, 57, 57, 58, 58, 59, 60]
# num1=[1, 3, 4, 4, 4, 5, 5, 5, 6, 5, 5, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 12, 13, 16, 18, 19, 20, 15, 14,
# 15, 14, 15, 15, 16, 17, 17, 17, 17, 17, 18, 17, 17, 19, 20, 21, 17, 18, 18, 19, 20, 22, 24, 25, 25, 26, 27, 28, 28,
# 27, 26, 27, 29, 29, 31, 30, 31, 29, 31, 32, 32, 34, 34, 35, 35, 35, 36, 35, 35, 33, 29, 29, 29, 29, 29, 33, 36, 35,
# 35, 35, 35, 38, 40, 41, 41, 43, 45, 43, 45, 45, 45, 43, 44, 44, 44, 45, 47, 47, 47, 43, 44, 46, 46, 49, 47, 48, 46,
# 46, 47, 48, 49, 47, 47, 46, 48, 49, 50, 50, 51, 51, 50, 50, 48, 46, 48, 49, 50, 53, 52, 54, 54, 55, 56, 56, 57, 57,
# 58, 59, 60]
# num2=[8, 7, 5, 8, 9, 6, 9, 11, 15, 12, 17, 21, 22, 22, 21, 20, 21, 23, 21, 22, 22, 24, 24, 25, 27, 26, 28, 30, 33, 34,
# 35, 37, 38, 39, 39, 41, 42, 42, 44, 46, 47, 48, 49, 51, 50, 51, 53, 56, 56, 58, 58, 58, 59, 60]
#
# num1=[4, 6, 5, 6, 7, 9, 9, 9, 11, 13, 9, 10, 9, 9, 9, 11, 10, 10, 12, 12, 13, 13, 13, 14, 14, 15, 16, 14, 14, 14, 13, 14,
# 14, 16, 20, 21, 22, 24, 26, 27, 28, 22, 22, 24, 25, 25, 26, 29, 29, 31, 26, 27, 27, 26, 29, 28, 26, 27, 29, 27, 29,
# 30, 32, 32, 34, 36, 37, 33, 35, 36, 39, 39, 39, 40, 41, 43, 43, 43, 45, 52, 52, 55, 52, 54, 55, 57, 57, 56, 57, 55,
# 56, 57, 59, 60, 60, 60, 58, 57, 60, 57, 59, 60, 60, 60, 60, 60, 57, 59, 60, 58, 58, 58, 59, 60, 60, 60, 60, 60, 60,
# 60, 60, 56, 56, 60, 60, 53, 55, 56, 56, 56, 55, 58, 58, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
# 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
# 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60]
# num2=[6, 8, 11, 12, 12, 9, 10, 11, 18, 21, 20, 22, 25, 27, 28, 29, 31, 32, 33, 35, 34, 36, 36, 37, 37, 36, 36, 36, 38,
# 39, 40, 40, 39, 44, 45, 46, 46, 48, 48, 50, 48, 48, 49, 51, 51, 51, 50, 51, 52, 52, 54, 55, 57, 57, 59, 60, 60, 60,
# 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 55, 56, 56, 57, 57, 58, 55, 57,
# 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
# 60, 60, 60, 60, 60, 60, 60, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
# 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 58, 59, 60, 60, 60, 60,
# 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60]
#
# num1=[8, 9, 8, 10, 3, 4, 4, 5, 6, 7, 5, 6, 6, 7, 8, 6, 7, 7, 6, 6, 6, 6, 6, 7, 8, 7, 8, 10, 10, 10, 10, 11, 11, 13, 16,
# 14, 14, 14, 13, 13, 15, 15, 16, 17, 17, 20, 20, 20, 21, 23, 20, 20, 21, 23, 23, 24, 22, 21, 23, 24, 27, 22, 23, 22,
# 14, 15, 17, 19, 19, 21, 21, 18, 20, 19, 19, 19, 20, 21, 22, 21, 23, 23, 23, 24, 25, 27, 27, 28, 28, 30, 30, 31, 33,
# 33, 35, 36, 36, 36, 37, 36]
#
# num2=[4, 3, 6, 5, 8, 12, 12, 16, 22, 19, 22, 22, 25, 28, 30, 30, 34, 35, 34, 35, 36, 37, 37, 36, 37, 39, 40, 41, 42, 43,
# 45, 47, 43, 44, 44, 44, 45, 46, 47, 47, 47, 47, 50, 52, 51, 52, 54, 56, 58, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60,
# 59, 60, 60, 60, 58, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
# 60, 60, 60, 60, 59, 60, 60, 60, 60, 60, 60, 60]
#
# num1=[6, 4, 5, 8, 9, 10, 10, 11, 12, 12, 11, 11, 11, 11, 9, 7, 8, 5, 6, 6, 6, 8, 9, 11, 11, 12, 12, 12, 12, 14, 16, 16,
# 16, 17, 18, 14, 14, 14, 15, 16, 16, 17, 18, 13, 13, 14, 13, 13, 13, 13, 13, 13, 13, 14, 18, 19, 23, 24, 27, 27, 29,
# 29, 30, 29, 30, 31, 33, 33, 33, 32, 33, 33, 40, 40, 40, 41, 43, 45, 46, 47, 40, 42, 42, 43, 46, 46, 47, 47, 48, 50,
# 42, 40, 40, 39, 40, 40, 37, 37, 37, 37, 37, 38, 40, 38, 33, 34, 34, 36, 36, 36, 36, 36, 36, 36, 35, 38, 34, 34, 36,
# 36, 37, 37, 38, 39, 37, 36, 36, 37, 38, 36, 38, 37, 38, 35, 35, 31, 31, 31, 31, 32, 32, 32, 33, 34, 34, 34, 36, 36,
# 37, 38, 40, 42, 42, 43, 46, 47, 48, 48, 48, 48, 50, 48, 48, 47, 49, 50, 52, 52, 53, 54, 53, 55, 58, 59, 60]
#
# num2=[4, 7, 7, 10, 13, 15, 8, 7, 13, 8, 13, 14, 15, 16, 24, 23, 29, 38, 39, 40, 40, 40, 42, 43, 43, 45, 47, 46, 47, 49,
# 50, 52, 51, 50, 49, 51, 50, 51, 56, 59, 60]
#
# num2=[4, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 8, 5, 7, 6, 7, 7, 7, 9, 9, 9, 6, 6, 7, 7, 7, 8, 10, 11, 11, 12, 14,
# 15, 12, 12, 12, 12, 15, 15, 15, 17, 16, 17, 19, 20, 21, 21, 24, 22, 22, 25, 26, 26, 26, 27, 27, 27, 27, 28, 29, 30,
# 27, 29, 30, 35, 34, 38, 39, 40, 40, 41, 37, 40, 46, 50, 51, 50, 51, 52, 53, 57, 58, 57, 59, 60]
#
num1=[2, 2, 2, 3, 4, 4, 6, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 7, 8, 9, 9, 11, 11, 11, 12, 13, 13, 13, 13,
13, 15, 17, 17, 16, 13, 13, 13, 12, 13, 15, 16, 17, 18, 20, 21, 21, 22, 23, 22, 22, 22, 24, 25, 25, 26, 28, 29, 31,
34, 35, 36, 36, 38, 41, 42, 43, 44, 45, 45, 45, 48, 52, 54, 55, 51, 50, 51, 52, 50, 51, 52, 56, 59, 59, 60]
num2=[3, 8, 7, 7, 12, 8, 8, 12, 10, 12, 16, 15, 24, 24, 26, 25, 32, 34, 37, 35, 38, 39, 40, 43, 41, 43, 44, 47, 50, 55,
55, 55, 55, 53, 49, 49, 49, 48, 50, 52, 53, 55, 56, 56, 56, 54, 56, 59, 60]
num2=[3, 5, 4, 6, 6, 11, 13, 8, 9, 9, 9, 10, 9, 10, 10, 9, 8, 3, 6, 6, 7, 9, 10, 11, 12, 13, 13, 14, 15, 19, 21, 16, 17, 23, 24, 23, 23, 24, 25, 27, 28, 27, 27, 29, 24, 24, 26, 29, 29, 32, 40, 45, 40, 38, 42, 45, 47, 53, 50, 49, 50, 52, 49, 50, 48, 51, 52, 50, 51, 55, 56, 57, 56, 59, 58, 57, 58, 59, 60]
num1=[3, 4, 7, 5, 8, 10, 6, 7, 6, 7, 6, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 9, 10, 11, 12, 12, 13, 12, 13,
13, 9, 9, 9, 10, 10, 10, 11, 13, 10, 10, 10, 11, 11, 11, 11, 14, 15, 16, 17, 17, 16, 16, 17, 17, 15, 14, 18, 18,
18, 17, 17, 18, 18, 19, 21, 21, 22, 22, 23, 24, 26, 26, 26, 22, 22, 22, 25, 26, 27, 28, 28, 29, 30, 30, 31, 32, 32,
31, 32, 31, 31, 32, 34, 31, 32, 34, 34, 36, 36, 37, 38, 34, 36, 38, 37, 39, 41, 43, 42, 44, 44, 44, 46, 46, 46, 48,
49, 49, 51, 53, 50, 50, 51, 51, 49, 53, 56, 57, 58, 55, 58, 60]
num3=[4, 4, 3, 5, 8, 8, 8, 9, 12, 7, 8, 9, 9, 9, 10, 10, 12, 12, 13, 14, 14, 14, 16, 17, 12, 13, 14, 12, 13, 11, 12, 13,
16, 16, 16, 16, 16, 22, 23, 23, 26, 24, 26, 26, 28, 30, 30, 34, 37, 38, 40, 41, 42, 42, 35, 35, 38, 41, 40, 42, 43,
43, 44, 41, 38, 39, 41, 43, 47, 45, 46, 48, 48, 49, 50, 51, 52, 52, 56, 60]
drawResultAndIter(num1,num2,num3)
print((0.8)**(1/6)-1)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment