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
This diff is collapsed.
#归一化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
This diff is collapsed.
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
This diff is collapsed.
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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.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]
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This diff is collapsed.
#归一化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
This diff is collapsed.
This diff is collapsed.
<?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
This diff is collapsed.
This diff is collapsed.
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
#if defined(GEODETICS_LIB)
# define GEODETICS_API __declspec(dllexport)
#else
# define GEODETICS_API __declspec(dllimport)
#endif
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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