def __init__(self, width, height, rCount, sCount): self.width = width # width of board in meters self.height = height # width of board in meters self.rC = [] # roomba list self.srC = [] # spike roomba list self.boardTime = TimeMultiplier(1) pixelspermeter = 30 # number of pixels per meter theta = 2*pi/rCount boardCenter = (width/2)*pixelspermeter+25 for x in range(rCount): # initialize roombas pos = Vector(boardCenter + 30*sin(theta*x), boardCenter + 30*cos(theta*x), 0) # put roombas in diagonal vel = Vector(sin(theta*x)/3, cos(theta*x)/3, 0) # random velocities (magnitude 1 m/s) rCircle = Circle(Point(pos.x, pos.y), 9.0/2) # creating circle object for roomba rLine = Line(Point(pos.x,pos.y), Point(pos.x+vel.x*50, pos.y+vel.y*50)) # velcoity vector line self.rC.append(Roomba(pos, vel, rCircle, rLine, self.boardTime)) # add new Roomba object to list for i in range(sCount): # initialize spike roombas at theta = 0, pi/2, pi, and 3pi/2 pos = Vector(30 * width / 2 + 25 + cos(i*pi/2) * 5 * 30,30 * height / 2 + 25 + sin(i*pi/2) * 5 * 30, 0) vel = Vector(-sin(i*pi/2)/3, cos(i*pi/2)/3, 0) rCircle = Circle(Point(pos.x, pos.y), 9.0/2) # creating spike roomba circle object self.srC.append(Spike(pos, vel, rCircle, i, self.boardTime)) # add new Spike object to list self.rCsrC = self.rC + self.srC #UAV initialization pos = Vector(boardCenter,boardCenter,0) vel = Vector(0,0,0) rCircle = Circle(Point(pos.x,pos.y), 6.0) maxSpeed = 2 # in m/s self.uav = UAV(pos, vel, rCircle, maxSpeed, self.boardTime, self.rC, self.srC)
def UAV_plot(self): T = self.xBest[0:N * ns] n = self.xBest[N * ns:2 * N * ns] phi = self.xBest[2 * N * ns:3 * N * ns] deltat = self.xBest[-1] T = np.reshape(T, (N, ns)) n = np.reshape(n, (N, ns)) phi = np.reshape(phi, (N, ns)) # 绘制迭代次数-适应度值 plt.figure() plt.title('适应度进化函数') plt.xlabel('迭代次数') plt.ylabel('适应度值') plt.plot(self.trace, color='g', linewidth=2) # 绘制最终的无人机位置的二维图 plt.figure() plt.title('二维图') My_UAV = UAV.UAV(N=5, ns=5, Dsafe=5, Dcomm=45, sigma=1.8e7) My_UAV.init_state() My_UAV.UAV_state(T, n, phi, deltat) J = My_UAV.UAV_fitness(self.xBest[-1]) x = J[1] y = J[2] plt.annotate('中心无人机', xy=(x[2, -1], y[2, -1])) plt.plot(x[:, -1], y[:, -1], '-o', markersize=7) plt.show()
def func(x): My_UAV = UAV.UAV(N=5, ns=5, Dsafe=5, Dcomm=45, sigma=1.8e7) My_UAV.init_state() My_UAV.UAV_state(x[0:N * ns], x[N * ns:2 * N * ns], x[2 * N * ns:3 * N * ns], x[-1]) J = My_UAV.UAV_fitness(x[-1]) return -J[0]
def __init__(self, width, height, rCount, sCount): self.width = width # width of board in meters self.height = height # width of board in meters self.rC = [] # roomba list self.srC = [] # spike roomba list self.boardTime = TimeMultiplier(1) pixelspermeter = 30 # number of pixels per meter theta = 2 * pi / rCount boardCenter = (width / 2) * pixelspermeter + 25 for x in range(rCount): # initialize roombas pos = Vector(boardCenter + 30 * sin(theta * x), boardCenter + 30 * cos(theta * x), 0) # put roombas in diagonal vel = Vector(sin(theta * x) / 3, cos(theta * x) / 3, 0) # random velocities (magnitude 1 m/s) rCircle = Circle(Point(pos.x, pos.y), 9.0 / 2) # creating circle object for roomba rLine = Line(Point(pos.x, pos.y), Point(pos.x + vel.x * 50, pos.y + vel.y * 50)) # velcoity vector line self.rC.append( Roomba(pos, vel, rCircle, rLine, self.boardTime)) # add new Roomba object to list for i in range( sCount ): # initialize spike roombas at theta = 0, pi/2, pi, and 3pi/2 pos = Vector(30 * width / 2 + 25 + cos(i * pi / 2) * 5 * 30, 30 * height / 2 + 25 + sin(i * pi / 2) * 5 * 30, 0) vel = Vector(-sin(i * pi / 2) / 3, cos(i * pi / 2) / 3, 0) rCircle = Circle(Point(pos.x, pos.y), 9.0 / 2) # creating spike roomba circle object self.srC.append( Spike(pos, vel, rCircle, i, self.boardTime)) # add new Spike object to list self.rCsrC = self.rC + self.srC #UAV initialization pos = Vector(boardCenter, boardCenter, 0) vel = Vector(0, 0, 0) rCircle = Circle(Point(pos.x, pos.y), 6.0) maxSpeed = 2 # in m/s self.uav = UAV(pos, vel, rCircle, maxSpeed, self.boardTime, self.rC, self.srC)
def UAV_plot(self): # 绘制迭代次数-适应度值 plt.figure() plt.title('适应度进化函数') plt.xlabel('迭代次数') plt.ylabel('适应度值') plt.plot(self.gb, color='g', linewidth=2) # 绘制最终的无人机位置的二维图 plt.figure() plt.title('二维图') My_UAV = UAV.UAV(N=5, ns=5, Dsafe=5, Dcomm=45, sigma=1.8e7) My_UAV.init_state() My_UAV.UAV_state(self.g[0:N * ns], self.g[N * ns:2 * N * ns], self.g[2 * N * ns:3 * N * ns], self.g[-1]) J = My_UAV.UAV_fitness(self.g[-1]) x = J[1] y = J[2] plt.annotate('中心无人机', xy=(x[2, -1], y[2, -1])) plt.plot(x[:, -1], y[:, -1], '-o', markersize=7) plt.show()
def plan(inital_pos, input_map, target): # inital_pos与target都是大小为2的列表 uav = UAV.UAV(inital_pos, input_map, 1, 2) path_record = [] path_record.append(inital_pos) enemyUK = enemy_record.get_enemy_pos() new_enemy_list = [] replanning = 0 while get_dis.eucliDist_m(uav.now_pos, target) > 0.001: if replanning == 1: update_map(uav, new_enemy_list) replanning = 0 dis_list = uav.dijskra_next_pos() next_pos = dis_list[target[0] * 20 + target[1]][0] move_length = get_dis.eucliDist_m(next_pos, uav.now_pos) if move_length > uav.step_length: mid = uav.step_length / move_length next_pos = [ uav.now_pos[0] + abs(next_pos[0] - uav.now_pos[0]) * mid, uav.now_pos[1] + abs(next_pos[1] - uav.now_pos[1]) * mid ] print('get new pos:') print(next_pos) uav.now_pos = next_pos path_record.append(next_pos) for enemy in enemyUK: if get_dis.eucliDist_m([enemy[0], enemy[1]], uav.now_pos) < uav.visual_field: replanning = 1 new_enemy_list.append(enemy) uav.enemy_find_list.append(enemy) enemyUK.remove(enemy) print('get new enemy') print(new_enemy_list) print(uav.map) return path_record
class Board: # rCount = roomba count, sCount = spike roomba count def __init__(self, width, height, rCount, sCount): self.width = width # width of board in meters self.height = height # width of board in meters self.rC = [] # roomba list self.srC = [] # spike roomba list self.boardTime = TimeMultiplier(1) pixelspermeter = 30 # number of pixels per meter theta = 2*pi/rCount boardCenter = (width/2)*pixelspermeter+25 for x in range(rCount): # initialize roombas pos = Vector(boardCenter + 30*sin(theta*x), boardCenter + 30*cos(theta*x), 0) # put roombas in diagonal vel = Vector(sin(theta*x)/3, cos(theta*x)/3, 0) # random velocities (magnitude 1 m/s) rCircle = Circle(Point(pos.x, pos.y), 9.0/2) # creating circle object for roomba rLine = Line(Point(pos.x,pos.y), Point(pos.x+vel.x*50, pos.y+vel.y*50)) # velcoity vector line self.rC.append(Roomba(pos, vel, rCircle, rLine, self.boardTime)) # add new Roomba object to list for i in range(sCount): # initialize spike roombas at theta = 0, pi/2, pi, and 3pi/2 pos = Vector(30 * width / 2 + 25 + cos(i*pi/2) * 5 * 30,30 * height / 2 + 25 + sin(i*pi/2) * 5 * 30, 0) vel = Vector(-sin(i*pi/2)/3, cos(i*pi/2)/3, 0) rCircle = Circle(Point(pos.x, pos.y), 9.0/2) # creating spike roomba circle object self.srC.append(Spike(pos, vel, rCircle, i, self.boardTime)) # add new Spike object to list self.rCsrC = self.rC + self.srC #UAV initialization pos = Vector(boardCenter,boardCenter,0) vel = Vector(0,0,0) rCircle = Circle(Point(pos.x,pos.y), 6.0) maxSpeed = 2 # in m/s self.uav = UAV(pos, vel, rCircle, maxSpeed, self.boardTime, self.rC, self.srC) # Draws the board and roombas def draw(self): pixelspermeter = 30 # number of pixels per meter self.pxwidth = self.width*pixelspermeter # pixel width of active board - the 30 is completely arbitrary self.pxheight = self.height*pixelspermeter # pixel height of active board buff = 50 # buffer around board self.win = GraphWin("My Board", self.pxwidth+buff, self.pxheight+buff, False) # creating a board w/ a 25 pixel buffer on each side # Four corner points upperleft = Point(buff/2, buff/2) upperright = Point(buff/2+self.pxwidth, buff/2) lowerright = Point(buff/2+self.pxwidth, buff/2 + self.pxheight) lowerleft = Point(buff/2, buff/2 + self.pxheight) # entire boundary boundary = Rectangle(upperleft, lowerright) # boundary of the grid boundary.setOutline(color_rgb(255, 255, 255)) # white boundary # grid blockwidth = pixelspermeter blockheight = pixelspermeter vertarray = [Line(Point(buff/2+i*blockwidth, buff/2), Point(buff/2+i*blockwidth, buff/2+self.pxheight)) for i in range(self.width)] # vertical lines horizarray = [Line(Point(buff/2, buff/2+j*blockheight), Point(buff/2+self.pxwidth, buff/2+j*blockheight)) for j in range(self.height)] # horizontal lines linearray = vertarray + horizarray # all lines for line in linearray: # color each line black line.setOutline(color_rgb(255, 255, 255)) # upper green line topline = Line(upperleft, upperright) topline.setOutline(color_rgb(0, 255, 0)) # lower red line botline = Line(lowerleft, lowerright) botline.setOutline(color_rgb(255, 0, 0)) # draw the boundary and all lines boundary.draw(self.win) for line in linearray: # draw grid lines line.draw(self.win) topline.draw(self.win) botline.draw(self.win) for r in self.rC: # draw roombas r.circle.setFill(color_rgb(0, 0, 0)) r.circle.draw(self.win) r.velVect.draw(self.win) print r.velVect for r in self.srC: # draw spike roombas r.circle.setFill(color_rgb(0,0,150)) r.circle.draw(self.win) # draw UAV self.uav.circle.setFill(color_rgb(150,0,0)) self.uav.circle.draw(self.win) self.win.setBackground(color_rgb(150, 150, 150)) # grey background #self.win.getMouse() # pause for click in self.window # Collision check: if distance between roomba centers is less than a threshold, they've collided # 1 for collision, 0 for no collision def collision(self, r, otherPos): threshold = 64 x = r.pos.x + r.vel.x*12 y = r.pos.y + r.vel.y*12 dx = x - otherPos.x dy = y - otherPos.y if threshold > dx*dx + dy*dy: return True else: return False # the primary method for running the simulation def run(self): self.draw() lastTime = self.boardTime.getTime() while len(self.srC) > 0: # while there are still roombas left, keep running timeInterval = self.boardTime.getTime()-lastTime lastTime = self.boardTime.getTime() for r in self.rC: if r.d == 1: # if the roomba is dead, remove it r.circle.undraw() self.rC.remove(r) self.rCsrC.remove(r) if self.uav.d == 1: # remove dead UAV self.uav.circle.undraw() cDetect = [] # list of roombas pairs for x in range(len(self.rCsrC)): # generates all possible unique pairs of roombas d = range(x, len(self.rCsrC)) e = [d.pop(0)] * len(d) cDetect = cDetect + zip(e, d) for x in cDetect: if self.collision(self.rCsrC[x[0]], self.rCsrC[x[1]].pos): # if there is a collision, reverse directions of both roombas if self.rCsrC[x[0]] in self.rC and self.rCsrC[x[0]].turning == False: self.rC[x[0]].flip() if self.collision(self.rCsrC[x[1]], self.rCsrC[x[0]].pos): if self.rCsrC[x[1]] in self.rC and self.rCsrC[x[1]].turning == False: self.rC[x[1]].flip() for r in self.rCsrC : # draw updated roombas # moves roombas with move function - uses less processing time #r.circle.move(timeInterval*r.vel.x*30, timeInterval*r.vel.y*30) # moves roombas by drawing and undrawing - laggy r.circle.undraw() r.circle.draw(self.win) if r in self.rC: r.velVect.undraw() r.velVect.draw(self.win) r.step() #Point(r.pos.x,r.pos.y).draw(self.win) # traces roomba path - laggy # draw updated UAV #self.uav.circle.move(timeInterval*self.uav.vel.x*30, timeInterval*self.uav.vel.y*30) self.uav.circle.undraw() self.uav.circle.draw(self.win) #Point(self.uav.pos.x,self.uav.pos.y).draw(self.win) #self.uav.update(self.rC,self.srC) self.uav.step() self.win.update() self.stop() # quit the simulation def stop(self): self.win.getMouse()
def run(): global turns_of_change global rate_of_change global destination time_swap = 1 MAP_RECORD = [] UAV_SET = [] MOVE_RECORD.clear() global_map = ( np.multiply(np.random.randn(CONFIG['width'], CONFIG['height']), 255.0 / (2.58 * 2)) + 127.5).astype(np.uint8) observer_uav = UAV(-1, CONFIG_PATH, logger) observer_uav.position[0] = 0 observer_uav.position[1] = 0 observer_uav.reset_destination(destination) observer_uav.openPrint = False observer_uav.weight_regression = False MAP_RECORD.append(copy.deepcopy(global_map)) #initialization for i in range(UAV_COUNTS): current_uav = UAV(i + 1, CONFIG_PATH, logger) current_uav.position[0] = 0 current_uav.position[1] = 0 current_uav.initialize_global_information(global_map) current_uav.reset_destination(destination) current_uav.openPrint = False UAV_SET.append(current_uav) while (len(UAV_SET) > 0 or observer_uav.working is True): #print("**time_swap: %d**"%time_swap) """ change_flag = (random.random() <= turns_of_change) if(change_flag is True): #print("[Notice]global map info is changed") element_count = CONFIG['width']*CONFIG['height'] change_count = int(element_count*rate_of_change) for i in range(change_count): number = random.randint(1,element_count) x = (number - 1)//int(CONFIG['height']) y = (number - 1)%int(CONFIG['height']) global_map[x][y] = random.randint(0,255) """ MAP_RECORD.append(copy.deepcopy(global_map)) #print("[Notice]update neighborhood information") for uav in UAV_SET: uav.update_one_skip_neighbor(UAV_SET) for uav in UAV_SET: uav.update_two_skip_neighbor() #print("[Notice]update environment information") for uav in UAV_SET: uav.update_local_environment_information(global_map, time_swap) for uav in UAV_SET: uav.update_environment_information() #print("[Notice]into stradegy period") for uav in UAV_SET: if ((uav.uid - 1) // UAV_BATCH < time_swap): uav.path_planning() #print("[Notice]into working period") for uav in UAV_SET: if ((uav.uid - 1) // UAV_BATCH < time_swap): uav.move() for uav in UAV_SET: if (uav.working is False): MOVE_RECORD[uav.uid] = uav.move_record UAV_SET.remove(uav) if (observer_uav.working is True): observer_uav.initialize_global_information(global_map) observer_uav.path_planning() observer_uav.move() time_swap += 1 avg_cost = 0 for uid, record in MOVE_RECORD.items(): path_cost = 0 path_record = [] position_record = [] time_step = 0 for element in record: time_step += 1 x = element[0] y = element[1] position_record.append([x, y]) if (len(path_record) > 0 and element[2] == path_record[-1][0]): continue path_record.append([element[2], time_step]) for element in path_record: grid_x = (element[0] - 1) // int(CONFIG['height']) grid_y = (element[0] - 1) % int(CONFIG['height']) path_cost += MAP_RECORD[element[1] - 1][grid_x][grid_y] avg_cost += path_cost if (observer_uav.openPrint is True): path = [element[0] for element in path_record] print("uav_{}'s move record is {}".format(uid, position_record)) print("uav_{}'s move grid's record is {}".format(uid, path)) print("uav_%d's path cost is %d" % (uid, path_cost)) avg_cost //= len(MOVE_RECORD) observer_path_cost = 0 observer_path_record = [] observer_position_record = [] time_step = 0 for element in observer_uav.move_record: time_step += 1 x = element[0] y = element[1] observer_position_record.append([x, y]) if (len(observer_path_record) > 0 and element[2] == observer_path_record[-1][0]): continue observer_path_record.append([element[2], time_step]) for element in observer_path_record: grid_x = (element[0] - 1) // int(CONFIG['height']) grid_y = (element[0] - 1) % int(CONFIG['height']) observer_path_cost += MAP_RECORD[element[1] - 1][grid_x][grid_y] if (observer_uav.openPrint is True): observer_path = [element[0] for element in observer_path_record] print("uav_observer's move record is {}".format( observer_position_record)) print("uav_observer's move grid's record is {}".format(observer_path)) print("uav_observer's path cost is %d" % (observer_path_cost)) print("average uav's path cost is %d" % (avg_cost)) extra_cost = float(avg_cost - observer_path_cost) / float(observer_path_cost) return extra_cost, observer_position_record
class Board: # rCount = roomba count, sCount = spike roomba count def __init__(self, width, height, rData, sData): self.width = width # width of board in meters self.height = height # width of board in meters self.rC = [] # roomba list self.srC = [] # spike roomba list pixelspermeter = 30 # number of pixels per meter theta = 2*pi/rCount boardCenter = (width/2)*pixelspermeter+25 for x in range(rCount): # initialize roombas pos = Vector(boardCenter + 30*sin(theta*x), boardCenter + 30*cos(theta*x), 0) # put roombas in diagonal vel = Vector(sin(theta*x)/3, cos(theta*x)/3, 0) # random velocities (magnitude 1 m/s) rCircle = Circle(Point(pos.x, pos.y), 9.0/2) # creating circle object for roomba rLine = Line(Point(pos.x,pos.y), Point(pos.x+vel.x*50, pos.y+vel.y*50)) # velcoity vector line self.rC.append(uavRoomba(pos, vel, rCircle, rLine, self.boardTime)) # add new Roomba object to list for i in range(sCount): # initialize spike roombas at theta = 0, pi/2, pi, and 3pi/2 pos = Vector(30 * width / 2 + 25 + cos(i*pi/2) * 5 * 30,30 * height / 2 + 25 + sin(i*pi/2) * 5 * 30, 0) vel = Vector(-sin(i*pi/2)/3, cos(i*pi/2)/3, 0) rCircle = Circle(Point(pos.x, pos.y), 9.0/2) # creating spike roomba circle object self.srC.append(uavSpike(pos, vel, rCircle, i, self.boardTime)) # add new Spike object to list self.rCsrC = self.rC + self.srC #UAV initialization pos = Vector(boardCenter,boardCenter,0) vel = Vector(0,0,0) rCircle = Circle(Point(pos.x,pos.y), 6.0) maxSpeed = 2 # in m/s self.uav = UAV(pos, vel, rCircle, maxSpeed, self.boardTime, self.rC, self.srC) # Collision check: if distance between roomba centers is less than a threshold, they've collided # 1 for collision, 0 for no collision def collision(self, r, otherPos): threshold = 64 x = r.pos.x + r.vel.x*12 y = r.pos.y + r.vel.y*12 dx = x - otherPos.x dy = y - otherPos.y if threshold > dx*dx + dy*dy: return True else: return False # the primary method for running the simulation def run(self): self.draw() lastTime = self.boardTime.getTime() while len(self.srC) > 0: # while there are still roombas left, keep running timeInterval = self.boardTime.getTime()-lastTime lastTime = self.boardTime.getTime() for r in self.rC: if r.d == 1: # if the roomba is dead, remove it r.circle.undraw() self.rC.remove(r) self.rCsrC.remove(r) if self.uav.d == 1: # remove dead UAV self.uav.circle.undraw() cDetect = [] # list of roombas pairs for x in range(len(self.rCsrC)): # generates all possible unique pairs of roombas d = range(x, len(self.rCsrC)) e = [d.pop(0)] * len(d) cDetect = cDetect + zip(e, d) for x in cDetect: if self.collision(self.rCsrC[x[0]], self.rCsrC[x[1]].pos): # if there is a collision, reverse directions of both roombas if self.rCsrC[x[0]] in self.rC and self.rCsrC[x[0]].turning == False: self.rC[x[0]].flip() if self.collision(self.rCsrC[x[1]], self.rCsrC[x[0]].pos): if self.rCsrC[x[1]] in self.rC and self.rCsrC[x[1]].turning == False: self.rC[x[1]].flip() for r in self.rCsrC : # draw updated roombas # moves roombas with move function - uses less processing time #r.circle.move(timeInterval*r.vel.x*30, timeInterval*r.vel.y*30) # moves roombas by drawing and undrawing - laggy r.circle.undraw() r.circle.draw(self.win) if r in self.rC: r.velVect.undraw() r.velVect.draw(self.win) r.step() #Point(r.pos.x,r.pos.y).draw(self.win) # traces roomba path - laggy # draw updated UAV #self.uav.circle.move(timeInterval*self.uav.vel.x*30, timeInterval*self.uav.vel.y*30) self.uav.circle.undraw() self.uav.circle.draw(self.win) #Point(self.uav.pos.x,self.uav.pos.y).draw(self.win) #self.uav.update(self.rC,self.srC) self.uav.step() self.win.update() self.stop() # quit the simulation def stop(self): self.win.getMouse()
#V0 = 0.5 t0 = 0 T = 60 kT = 0.1 for j in range(0,1): V0 = 0.5 + 0.05 * j target = Target(Xtg0, XtgT, d0) channel = Channel(Xbs, r0) uav = UAV(V0, X0, h) uav.setmission(target, channel, kappa, epsilon) X = np.zeros((int((T - t0) / h) + 1,2)) Psi = np.zeros((int((T - t0) / h) + 1,2)) t = np.zeros(int((T - t0) / h) + 1) u = np.zeros(int((T - t0) / h) + 1) gamma = 0 i = 0 gamma = -np.pi / 2 for s in np.arange(t0, T + h, h): #if s < T/2: # gamma = gamma - 2.0 * np.pi * h / T #else: # gamma = gamma + 2.0 * np.pi * h / T
class Board: # rCount = roomba count, sCount = spike roomba count def __init__(self, width, height, rCount, sCount): self.width = width # width of board in meters self.height = height # width of board in meters self.rC = [] # roomba list self.srC = [] # spike roomba list self.boardTime = TimeMultiplier(1) pixelspermeter = 30 # number of pixels per meter theta = 2 * pi / rCount boardCenter = (width / 2) * pixelspermeter + 25 for x in range(rCount): # initialize roombas pos = Vector(boardCenter + 30 * sin(theta * x), boardCenter + 30 * cos(theta * x), 0) # put roombas in diagonal vel = Vector(sin(theta * x) / 3, cos(theta * x) / 3, 0) # random velocities (magnitude 1 m/s) rCircle = Circle(Point(pos.x, pos.y), 9.0 / 2) # creating circle object for roomba rLine = Line(Point(pos.x, pos.y), Point(pos.x + vel.x * 50, pos.y + vel.y * 50)) # velcoity vector line self.rC.append( Roomba(pos, vel, rCircle, rLine, self.boardTime)) # add new Roomba object to list for i in range( sCount ): # initialize spike roombas at theta = 0, pi/2, pi, and 3pi/2 pos = Vector(30 * width / 2 + 25 + cos(i * pi / 2) * 5 * 30, 30 * height / 2 + 25 + sin(i * pi / 2) * 5 * 30, 0) vel = Vector(-sin(i * pi / 2) / 3, cos(i * pi / 2) / 3, 0) rCircle = Circle(Point(pos.x, pos.y), 9.0 / 2) # creating spike roomba circle object self.srC.append( Spike(pos, vel, rCircle, i, self.boardTime)) # add new Spike object to list self.rCsrC = self.rC + self.srC #UAV initialization pos = Vector(boardCenter, boardCenter, 0) vel = Vector(0, 0, 0) rCircle = Circle(Point(pos.x, pos.y), 6.0) maxSpeed = 2 # in m/s self.uav = UAV(pos, vel, rCircle, maxSpeed, self.boardTime, self.rC, self.srC) # Draws the board and roombas def draw(self): pixelspermeter = 30 # number of pixels per meter self.pxwidth = self.width * pixelspermeter # pixel width of active board - the 30 is completely arbitrary self.pxheight = self.height * pixelspermeter # pixel height of active board buff = 50 # buffer around board self.win = GraphWin( "My Board", self.pxwidth + buff, self.pxheight + buff, False) # creating a board w/ a 25 pixel buffer on each side # Four corner points upperleft = Point(buff / 2, buff / 2) upperright = Point(buff / 2 + self.pxwidth, buff / 2) lowerright = Point(buff / 2 + self.pxwidth, buff / 2 + self.pxheight) lowerleft = Point(buff / 2, buff / 2 + self.pxheight) # entire boundary boundary = Rectangle(upperleft, lowerright) # boundary of the grid boundary.setOutline(color_rgb(255, 255, 255)) # white boundary # grid blockwidth = pixelspermeter blockheight = pixelspermeter vertarray = [ Line(Point(buff / 2 + i * blockwidth, buff / 2), Point(buff / 2 + i * blockwidth, buff / 2 + self.pxheight)) for i in range(self.width) ] # vertical lines horizarray = [ Line(Point(buff / 2, buff / 2 + j * blockheight), Point(buff / 2 + self.pxwidth, buff / 2 + j * blockheight)) for j in range(self.height) ] # horizontal lines linearray = vertarray + horizarray # all lines for line in linearray: # color each line black line.setOutline(color_rgb(255, 255, 255)) # upper green line topline = Line(upperleft, upperright) topline.setOutline(color_rgb(0, 255, 0)) # lower red line botline = Line(lowerleft, lowerright) botline.setOutline(color_rgb(255, 0, 0)) # draw the boundary and all lines boundary.draw(self.win) for line in linearray: # draw grid lines line.draw(self.win) topline.draw(self.win) botline.draw(self.win) for r in self.rC: # draw roombas r.circle.setFill(color_rgb(0, 0, 0)) r.circle.draw(self.win) r.velVect.draw(self.win) print r.velVect for r in self.srC: # draw spike roombas r.circle.setFill(color_rgb(0, 0, 150)) r.circle.draw(self.win) # draw UAV self.uav.circle.setFill(color_rgb(150, 23, 189)) self.uav.circle.draw(self.win) self.win.setBackground(color_rgb(150, 150, 150)) # grey background #self.win.getMouse() # pause for click in self.window # Collision check: if distance between roomba centers is less than a threshold, they've collided # 1 for collision, 0 for no collision def collision(self, r, otherPos): threshold = 64 x = r.pos.x + r.vel.x * 12 y = r.pos.y + r.vel.y * 12 dx = x - otherPos.x dy = y - otherPos.y if threshold > dx * dx + dy * dy: return True else: return False # the primary method for running the simulation def run(self): self.draw() lastTime = self.boardTime.getTime() while len(self.srC ) > 0: # while there are still roombas left, keep running timeInterval = self.boardTime.getTime() - lastTime lastTime = self.boardTime.getTime() for r in self.rC: if r.d == 1: # if the roomba is dead, remove it r.circle.undraw() self.rC.remove(r) self.rCsrC.remove(r) if self.uav.d == 1: # remove dead UAV self.uav.circle.undraw() cDetect = [] # list of roombas pairs for x in range(len(self.rCsrC) ): # generates all possible unique pairs of roombas d = range(x, len(self.rCsrC)) e = [d.pop(0)] * len(d) cDetect = cDetect + zip(e, d) for x in cDetect: if self.collision( self.rCsrC[x[0]], self.rCsrC[x[1]].pos ): # if there is a collision, reverse directions of both roombas if self.rCsrC[x[0]] in self.rC and self.rCsrC[ x[0]].turning == False: self.rC[x[0]].flip() if self.collision(self.rCsrC[x[1]], self.rCsrC[x[0]].pos): if self.rCsrC[x[1]] in self.rC and self.rCsrC[ x[1]].turning == False: self.rC[x[1]].flip() for r in self.rCsrC: # draw updated roombas # moves roombas with move function - uses less processing time #r.circle.move(timeInterval*r.vel.x*30, timeInterval*r.vel.y*30) # moves roombas by drawing and undrawing - laggy r.circle.undraw() r.circle.draw(self.win) if r in self.rC: r.velVect.undraw() r.velVect.draw(self.win) r.step() #Point(r.pos.x,r.pos.y).draw(self.win) # traces roomba path - laggy # draw updated UAV #self.uav.circle.move(timeInterval*self.uav.vel.x*30, timeInterval*self.uav.vel.y*30) self.uav.circle.undraw() self.uav.circle.draw(self.win) #Point(self.uav.pos.x,self.uav.pos.y).draw(self.win) #self.uav.update(self.rC,self.srC) self.uav.step() self.win.update() self.stop() # quit the simulation def stop(self): self.win.getMouse()
def main(): ############################################################ ###################### INITIALIZATION ###################### ############################################################ telemetry_open = False client = interop.Client(url='http://127.0.0.1:8000', username='******', password='******') sys_db = database.db_connectt(url='http://127.0.0.1:8000', username='******', password='******') drone = UAV.connect(url='http://127.0.0.1:8000', username='******', password='******') dataRate = 0 ############################################################ ###################### API DEFINITONS ###################### ############################################################ def upload_telemetry(client, out): telemetry = interop.Telemetry(latitude=38.145215, longitude=-76.427942, altitude_msl=50, uas_heading=90) #send that info to the interop server client.post_telemetry(telemetry) out.insert(END,"Telemetry posted\n") def upload_all_targets(client, target_json, sys_db, out): # this is all boilerplate right now, we need to send target info as json # or extract the json info and send it this way. try: #create a target object. we will be building this object #the output of our image classification program, from v$ #stored in our database. targets, confidence = sys_db.get_all_targets() target_count = 0 confirmed_targets = [] for i in range(0,len(targets)): if confidence[i] > 90: confirmed_targets.append(targets[i]) #send the target info to the interop server for i in range(0,confirmed_targets): client.post_target(confirmed_targets[i]) except: out.insert(END, 'Something went wrong when uploading target\n') def view_current_targets(sys_db, out): #do that def upload_mission(client, mission_json, sys_db, out): # this is all boilerplate right now, we need to send mission info as json # or extract the json info and send it this way. try: mission = sys_db.get_mission() #send the mission info to the interop server mission = client.post_target(mission) out.insert(END, "Mission posted\n") except: out.insert(END, 'Something went wrong when uploading mission\n') def view_mission(sys_db, out): #do that def bottle_drop(drone, out): try: drone.bottle_drop() out.insert(END, "Bottle drop signal sent\n") except: out.insert(END, "Error sending bottle drop signal\n") def get_drone_info(drone, out): #do that def drone_start_video(drone, out): #do that def drone_take_picture(drone, out): #do that def connect(url, username, password, out): try: #set up the connection to the interop server at the specified #url with the specified username/password client = interop.Client(url=url, username=username, password=password) out.insert(END, "Connected to " + url + " with username '" + username + "' and password '" + password + "'.\n") except: out.insert(END, "Something when wrong when trying to connect\n") ############################################################ ###################### WINDOW SETUP ######################## ############################################################ window = Tkinter.Tk() window.title("MSUUS") window.geometry("590x560") url = StringVar( window ) url.set('http://127.0.0.1:8000') username = StringVar( window ) username.set('testuser') password = StringVar( window ) password.set('testpass') url_label = Label( window, text="Server URL") url_label.place(x=10,y=10) url_textbox = Entry( window, textvariable=url ) url_textbox.place(x=100, y=10) username_label = Label( window, text="Username:"******"Password:"******"Output" ) output_label.place(x=10, y=190) output_textbox = Text( window, width=79, wrap=WORD ) output_textbox.place(x=10, y=210) output_scrollbar = Scrollbar( window, command=output_textbox.yview ) output_textbox['yscrollcommand'] = output_scrollbar.set output_scrollbar.place(x=570,y=210,height=340) data_rate_label = Label( window, text="Telemetry Data Rate:" ) data_rate_label.place(x=290, y=10) data_rate_field = Entry( window, textvariable=dataRate ) data_rate_field.place(x=430, y=10, width=40) connect_button = Button( window, text="Connect", command = lambda: connect(url.get(),username.get(),password.get(),output_textbox) ) connect_button.place(x=10, y=90) target_upload_button = Button( window, text="Upload Target", command = lambda: upload_target(client, "{'id':1}",output_textbox) ) target_upload_button.place(x=10, y=150) window.after(500, lambda: upload_telemetry(client,output_textbox)) window.mainloop() if __name__ == "__main__": main()
X0 = np.array([0,0]) Xbs = np.array([2.0,3.0]) Xtg = np.array([10.0, -2.0]) r0 = 7.0 d0 = 3.5 kappa = 0.05 epsilon = 0.05 V0 = 0.5 h = 0.1 t0 = 0 T = 60 target = Target(Xtg, d0) channel = Channel(Xbs, r0) uav = UAV(V0, X0, h) uav.setmission(target, channel, kappa) print(uav.u([0,0])) X = np.zeros((int((T-t0)/h)+1,2)) t = np.zeros(int((T-t0)/h)+1) u = np.zeros(int((T-t0)/h)+1) gamma = -np.pi/2 i = 0 for s in np.arange(t0, T+h, h): gamma = gamma + 0.01 t[i] = s x = uav.step(gamma)
print("uav_3's path sum: %d "%sum3) print([node[2] for node in path3]) print("uav_4's path sum: %d "%sum4) print([node[2] for node in path4]) print("uav_5(shortest)'s path sum: %d "%sum5) print([node[2] for node in path5]) """ i = 0 all_extra_cost = 0.0 all_saved_time = 0.0 while(i < 100): print("process {}%".format(i+1)) uav_6 = UAV.UAV(6,'./config.json',logger) wide = uav_6.config['height']*uav_6.config['grid_size'] global_map = np.random.randn(uav_6.config['width'],uav_6.config['height']) global_map = (np.multiply(global_map,255.0/(2.58*2)) + 127.5).astype(np.uint8) uav_6.initialize_global_information(global_map) uav_6.update_all_level_maps() uav_6.position[0] = 0 uav_6.position[1] = 0 uav_7 = UAV.UAV(7,'./config.json',logger) uav_7.initialize_global_information(global_map) uav_7.update_all_level_maps(maxpool=True) uav_7.position[0] = uav_6.position[0] uav_7.position[1] = uav_6.position[1] uav_6.multi_levels = False uav_6.addWeight = False
def main(): ############################################################ ######################## DEFINITONS ####################### ############################################################ def upload_telemetry(client, last_telem, out): telemetry = interop.Telemetry(latitude=38.145215, longitude=-76.427942, altitude_msl=50, uas_heading=90) #send that info to the interop server delta = datetime.datetime.now() - last_telem out.set(1 / (delta.total_seconds())) client.post_telemetry(telemetry) def upload_all_targets(client, target_json, sys_db, out): cur = db.cursor() #allows execution of all SQL queries cur.execute("SELECT * FROM targets") #Fetches every row of the table; #Columns are as follows: #1st - target_id, 2 - type, 3 - latitude, 4 - longitude, 5 - orientation, 6 - shape, 7 - background-color, 8 - alphanumeric, 9 - alphanumeric_color # 10 - image path #note: target_id is a long/int, and latitude and longitude are floats/doubles for row in cur.fetchall(): target = interop.Target( type=row[ 1], #indexing starts from 0, data doesn't include target_id latitude=row[2], longitude=row[3], orientation=row[4], shape=row[5], background_color=row[6], alphanumeric=row[7], alphanumeric_color=row[8]) target = client.post_target(target) #send target values to server #open corresponding image file. Assumes the naming convention goes "1_lettercolor_letter_shapecolor_shape.png". Ex. "2_white_B_green_square.png" with open(imagedir + "/" + row[10] + '.png', 'rb') as f: #the 'rb' option reads the file in binary, as opposed to as a text file image_data = f.read() client.put_target_image(target.id, image_data) def view_current_targets(sys_db, out): cur = db.cursor() #allows execution of all SQL queries cur.execute("SELECT * FROM targets") for row in cur.fetchall(): target = interop.Target( type=row[ 1], #indexing starts from 0, data doesn't include target_id latitude=row[2], longitude=row[3], orientation=row[4], shape=row[5], background_color=row[6], alphanumeric=row[7], alphanumeric_color=row[8]) out.insert(END, target) out.insert(END, "\n") out.see(END) def download_mission(client, sys_db, out): try: missions = client.get_missions() out.insert( END, "Mission info downloaded from interoperability server\n") for wp in missions[0].mission_waypoints: insert_stmt = ( "INSERT INTO waypoints (wp_order, latitude, longitude, altitude, type) " "VALUES (%s, %s, %s, %s, %s)") data = (wp.order, wp.latitude, wp.longitude, wp.altitude_msl, "waypoint") cur = db.cursor() print(insert_stmt, data) cur.execute(insert_stmt, data) db.commit() out.insert(END, "Mission info uploaded to database.\n") out.see(END) except: out.insert(END, 'Something went wrong when downloading mission\n') out.see(END) def download_obstacles(client, sys_db, out): try: missions = client.get_missions() out.insert(END, "Obstacle info downloaded from interop\n") for wp in missions[0].mission_waypoints: insert_stmt = ( "INSERT INTO obstacles (wp_order, latitude, longitude, altitude, type) " "VALUES (%s, %s, %s, %s, %s)") data = (wp.order, wp.latitude, wp.longitude, wp.altitude_msl, "waypoint") cur = db.cursor() print(insert_stmt, data) cur.execute(insert_stmt, data) db.commit() out.insert(END, "Obstacle info uploaded to database.\n") out.insert(END, "\n") out.see(END) except: out.insert(END, 'Something went wrong when downloading obstacles\n') out.see(END) def bottle_drop(drone, out): try: drone.bottle_drop() out.insert(END, "Bottle drop signal sent\n") out.see(END) except: out.insert(END, "Error sending bottle drop signal\n") out.see(END) def ping_drone(drone, out): try: info = drone.get_info() out.insert(END, info["message"]) out.insert(END, "\n") out.see(END) except: out.insert(END, "Error pinging drone.\n") out.see(END) def drone_start_video(drone, out): stream = drone.take_picture() return 0 def drone_take_picture(drone, sys_db, out, pic_out): try: picture = drone.take_picture() out.insert(END, "Picture signal sent\n") insert_stmt = ( "INSERT INTO target_images (id, image) VALUES (%s, %s)") data = (picture["id"], picture["image"]) cur = db.cursor() cur.execute(insert_stmt, data) db.commit() im = PIL.Image.open(BytesIO(base64.b64decode(picture["image"]))) im2 = PIL.ImageTk.PhotoImage(im.resize((180, 160)).rotate(180)) pic_out.configure(image=im2) pic_out.image = im2 out.insert( END, "Picture: " + picture["filename"] + " uploaded to database\n") out.see(END) except: out.insert(END, "Error sending take picture signal\n") out.see(END) def interop_connect(url, username, password, out): try: #set up the connection to the interop server at the specified #url with the specified username/password client = interop.Client(url=url, username=username, password=password) out.insert( END, "Connected to " + url + " with username '" + username + "' and password '" + password + "'.\n") out.see(END) except: out.insert(END, "Something when wrong when trying to connect\n") out.see(END) def on_closing(): window.destroy() ############################################################ ###################### INITIALIZATION ###################### ############################################################ telemetry_open = False client = interop.Client(url='http://127.0.0.1:8000', username='******', password='******') datarate = 0 # to store avg datarate last_telem = datetime.datetime.now() imagedir = 'target_images' drone = UAV.UAV('http://192.168.1.31:5000', 'MSUUS', 'Unmanned2017') #Connect to the mySQL database db = MySQLdb.connect(host="localhost", user="******", passwd="password", db="MSUUS") #Use own credentials for actual database ############################################################ ###################### WINDOW SETUP ######################## ############################################################ window = tkinter.Tk() window.protocol("WM_DELETE_WINDOW", on_closing) window.title("MSUUS System Software v0.6") window.geometry("590x560") url = StringVar(window) url.set('http://127.0.0.1:8000') username = StringVar(window) username.set('testuser') password = StringVar(window) password.set('testpass') url_label = Label(window, text="Interop URL") url_label.place(x=10, y=10) url_textbox = Entry(window, textvariable=url) url_textbox.place(x=100, y=10) username_label = Label(window, text="Username:"******"Password:"******"Output") output_label.place(x=10, y=190) output_textbox = Text(window, width=79, wrap=WORD) output_textbox.place(x=10, y=210) output_scrollbar = Scrollbar(window, command=output_textbox.yview) output_textbox['yscrollcommand'] = output_scrollbar.set output_scrollbar.place(x=570, y=210, height=340) data_rate_str = StringVar(window) data_rate_str.set('0') data_rate_label = Label(window, text="Telemetry Data Rate:") data_rate_label.place(x=290, y=10) data_rate_field = Entry(window, textvariable=data_rate_str) data_rate_field.place(x=430, y=10, width=60) last_pic = PIL.ImageTk.PhotoImage(PIL.Image.open('blank.png')) picture_box_label = Label(window, text="Last Image:") picture_box_label.place(x=290, y=40) picture_box_field = Label(window, image=last_pic) picture_box_field.place(x=370, y=40, width=180, height=160) connect_button = Button( window, text="Interop Connect", command=lambda: interop_connect(url.get(), username.get(), password.get(), output_textbox)) connect_button.place(x=10, y=90) ping_button = Button(window, text="Ping Drone", command=lambda: ping_drone(drone, output_textbox)) ping_button.place(x=136, y=90) take_picture_button = Button( window, text="Take Picture", command=lambda: drone_take_picture(drone, db, output_textbox, picture_box_field)) take_picture_button.place(x=10, y=120) auto_picture_button = Button( window, text="Auto Picture", command=lambda: drone_take_picture(drone, db, output_textbox, picture_box_field)) auto_picture_button.place(x=112, y=120) auto_picture_button.configure(state='disable') stream_button = Button( window, text="Start Stream", command=lambda: drone_start_video(drone, db, output_textbox)) stream_button.place(x=214, y=120) stream_button.configure(state='disable') target_upload_button = Button( window, text="Download Mission", command=lambda: download_mission(client, db, output_textbox)) target_upload_button.place(x=10, y=150) ############################################################ ######################## MAIN LOOP ######################### ############################################################ while True: upload_telemetry(client, last_telem, data_rate_str) last_telem = datetime.datetime.now() window.update_idletasks() window.update()
class Board: # rCount = roomba count, sCount = spike roomba count def __init__(self, width, height, rData, sData): self.width = width # width of board in meters self.height = height # width of board in meters self.rC = [] # roomba list self.srC = [] # spike roomba list pixelspermeter = 30 # number of pixels per meter theta = 2 * pi / rCount boardCenter = (width / 2) * pixelspermeter + 25 for x in range(rCount): # initialize roombas pos = Vector(boardCenter + 30 * sin(theta * x), boardCenter + 30 * cos(theta * x), 0) # put roombas in diagonal vel = Vector(sin(theta * x) / 3, cos(theta * x) / 3, 0) # random velocities (magnitude 1 m/s) rCircle = Circle(Point(pos.x, pos.y), 9.0 / 2) # creating circle object for roomba rLine = Line(Point(pos.x, pos.y), Point(pos.x + vel.x * 50, pos.y + vel.y * 50)) # velcoity vector line self.rC.append( uavRoomba(pos, vel, rCircle, rLine, self.boardTime)) # add new Roomba object to list for i in range( sCount ): # initialize spike roombas at theta = 0, pi/2, pi, and 3pi/2 pos = Vector(30 * width / 2 + 25 + cos(i * pi / 2) * 5 * 30, 30 * height / 2 + 25 + sin(i * pi / 2) * 5 * 30, 0) vel = Vector(-sin(i * pi / 2) / 3, cos(i * pi / 2) / 3, 0) rCircle = Circle(Point(pos.x, pos.y), 9.0 / 2) # creating spike roomba circle object self.srC.append( uavSpike(pos, vel, rCircle, i, self.boardTime)) # add new Spike object to list self.rCsrC = self.rC + self.srC #UAV initialization pos = Vector(boardCenter, boardCenter, 0) vel = Vector(0, 0, 0) rCircle = Circle(Point(pos.x, pos.y), 6.0) maxSpeed = 2 # in m/s self.uav = UAV(pos, vel, rCircle, maxSpeed, self.boardTime, self.rC, self.srC) # Collision check: if distance between roomba centers is less than a threshold, they've collided # 1 for collision, 0 for no collision def collision(self, r, otherPos): threshold = 64 x = r.pos.x + r.vel.x * 12 y = r.pos.y + r.vel.y * 12 dx = x - otherPos.x dy = y - otherPos.y if threshold > dx * dx + dy * dy: return True else: return False # the primary method for running the simulation def run(self): self.draw() lastTime = self.boardTime.getTime() while len(self.srC ) > 0: # while there are still roombas left, keep running timeInterval = self.boardTime.getTime() - lastTime lastTime = self.boardTime.getTime() for r in self.rC: if r.d == 1: # if the roomba is dead, remove it r.circle.undraw() self.rC.remove(r) self.rCsrC.remove(r) if self.uav.d == 1: # remove dead UAV self.uav.circle.undraw() cDetect = [] # list of roombas pairs for x in range(len(self.rCsrC) ): # generates all possible unique pairs of roombas d = range(x, len(self.rCsrC)) e = [d.pop(0)] * len(d) cDetect = cDetect + zip(e, d) for x in cDetect: if self.collision( self.rCsrC[x[0]], self.rCsrC[x[1]].pos ): # if there is a collision, reverse directions of both roombas if self.rCsrC[x[0]] in self.rC and self.rCsrC[ x[0]].turning == False: self.rC[x[0]].flip() if self.collision(self.rCsrC[x[1]], self.rCsrC[x[0]].pos): if self.rCsrC[x[1]] in self.rC and self.rCsrC[ x[1]].turning == False: self.rC[x[1]].flip() for r in self.rCsrC: # draw updated roombas # moves roombas with move function - uses less processing time #r.circle.move(timeInterval*r.vel.x*30, timeInterval*r.vel.y*30) # moves roombas by drawing and undrawing - laggy r.circle.undraw() r.circle.draw(self.win) if r in self.rC: r.velVect.undraw() r.velVect.draw(self.win) r.step() #Point(r.pos.x,r.pos.y).draw(self.win) # traces roomba path - laggy # draw updated UAV #self.uav.circle.move(timeInterval*self.uav.vel.x*30, timeInterval*self.uav.vel.y*30) self.uav.circle.undraw() self.uav.circle.draw(self.win) #Point(self.uav.pos.x,self.uav.pos.y).draw(self.win) #self.uav.update(self.rC,self.srC) self.uav.step() self.win.update() self.stop() # quit the simulation def stop(self): self.win.getMouse()