def _create_drones(num_of_clients, drone_capacity): drones_needed = num_of_clients // drone_capacity if num_of_clients % drone_capacity == 0: drones = [ Drone(i + 1, drone_capacity) for i in range(drones_needed) ] else: drones_needed += 1 drones = [ Drone(i + 1, drone_capacity) for i in range(drones_needed) ] return drones, drones_needed
def __init__(self): self.x_max = 50 self.y_max = 50 self.world = World(self.x_max, self.y_max) #self.world.random() #self.world.generate_with_roads(resource_points=True, drop_points = True, recharge_points=True) self.world.generate_city(resource_points=True, drop_points=True, recharge_points=True) # drones may have different charaterisics, battery size, max lift, max weight carrying capacity, turning abilities? some might make only right turns? self.drones = [] self.drone_world_plots = [] self.message_dispatcher = MessageDispatcher() self.drone_alpha = Drone('URBAN0X1', self.world, self.message_dispatcher, cooperate=True) self.drones.append(self.drone_alpha) self.drone_beta = Drone('URBAN0X2', self.world, self.message_dispatcher, cooperate=True) self.drones.append(self.drone_beta) #self.drone_gamma = Drone('URBAN0X3', self.world,self.message_dispatcher, cooperate=False) #self.drones.append(self.drone_gamma) #self.fig = plt.figure(figsize=(1, 2))#, dpi=80, facecolor='w', edgecolor='k') self.drop_point_marker = 'o' #self.world.drop_point_locations = [random.sample(range(self.world.x_max), 10), random.sample(range(self.world.y_max), 10)] self.drop_point_plot = None #reacharge point self.recharge_point_marker = 's' #square self.recharge_point_plot = None #resources #self.fig = plt.figure(figsize=(1, 2))#, dpi=80, facecolor='w', edgecolor='k') #self.world.resource_locations = [[5,10,20,40,45],[5,10,20,40,45]] self.resource_plot = None self.resource_marker = 'v' self.markers = ['|', '+', 'x', '*'] self.colors = ['r', 'k', 'g', 'c', 'm', 'b'] self.init_figures()
def __init__(self, config_file): with open(config_file, 'r') as f: self.rows, self.cols, self.num_drones, self.num_turns, self.max_payload = get_line(f.readline()) self.num_product_types = get_line_first(f.readline()) weights = get_line(f.readline()) self.products = [] for idx in range(self.num_product_types): self.products.append(Product(idx, weights[idx])) self.num_warehouses = get_line_first(f.readline()) self.warehouses = [] for warehouse_idx in range(self.num_warehouses): loc = tuple(get_line(f.readline())) warehouse = Warehouse(warehouse_idx, loc) for prod_idx, prod_quant in enumerate(get_line(f.readline())): prod = self.products[prod_idx] warehouse.add_product(prod, prod_quant) self.warehouses.append(warehouse) self.num_orders = get_line_first(f.readline()) self.orders = [] for order_idx in range(self.num_orders): loc = tuple(get_line(f.readline())) order = Order(order_idx, loc) f.readline() #just skip cause we know it from the next line for prod_id in get_line(f.readline()): prod = self.products[prod_id] order.add_product(prod) self.orders.append(order) self.drones = [Drone(drone_idx, self.warehouses[0].location, self.max_payload) \ for drone_idx in range(self.num_drones)]
def lorenz(self, x_1, y_1, z_1): s = 10 r = 28 b = 2.667 ''' Given: x, y, z: a point of interest in three dimensional space s, r, b: parameters defining the lorenz attractor Returns: x_dot, y_dot, z_dot: values of the lorenz attractor's partial derivatives at the point x, y, z ''' dt = 0.01 dro = Drone(self) dro.x[0], dro.y[0], dro.z[0] = x_1, y_1, z_1 for i in range(self): x_dot = s * (y_1 - x_1) y_dot = r * x_1 - y_1 - x_1 * z_1 z_dot = x_1 * y_1 - b * z_1 """ traj = Chaotic(num_steps) x_dot, y_dot, z_dot = traj.lorenz(dro.x[i], dro.y[i], dro.z[i]) """ dro.x[i + 1] = dro.x[i] + (x_dot * dt) dro.y[i + 1] = dro.y[i] + (y_dot * dt) dro.z[i + 1] = dro.z[i] + (z_dot * dt) x_1, y_1, z_1 = dro.x[i + 1], dro.y[i + 1], dro.z[i + 1] #print(dro.x,dro.y,dro.z) return dro.x, dro.y, dro.z
def connect(self): print('[+] Connection') self.s.settimeout(3) self.s.connect((self.host, self.port)) next_cmd = 'waiting_welcome' for line in self.recv_line(): print(' |-- %s' % line) if next_cmd == 'waiting_welcome': if line == 'BIENVENUE': self.send_msg(self.team) next_cmd = 'waiting_nbconnect' continue raise Exception('It seems we are not welcome... :(') if next_cmd == 'waiting_nbconnect': if line != 'ko': self.nbconnect = int(line) next_cmd = 'waiting_mapinfo' continue raise Exception('Invalid team') if next_cmd == 'waiting_mapinfo': (self.map_x, self.map_y) = [int(i) for i in line.split()] self.drone = Drone(self, self.map_x, self.map_y, self.team) break assert (self.drone) self.s.settimeout(None) print(' `-- Connection OK\n')
def test_read_file(self): ''' =================== test_ok.txt =================== plane1 1 1 1 plane1 1 1 1 1 2 3 plane1 2 3 4 1 1 1 plane1 3 4 5 1 1 1 plane1 4 5 6 1 2 3 =================== test_singal.txt: =================== plane1 1 1 1 plane1 1 1 1 1 2 3 plane1 2 3 4 1 1 1 plane1 3 4 5 plane1 1 1 1 1 2 3 ''' path0 = 'testcase/test_ok.txt' path1 = 'testcase/test_signal.txt' path2 = 'testcase/test_error_format.txt' path3 = 'testcase/test_error_location.txt' path4 = 'testcase/wrongpath.txt' drone = Drone() self.assertEqual(drone.read_file(path0), True) self.assertEqual(drone.read_file(path1), False) self.assertEqual(drone.read_file(path2), False) self.assertEqual(drone.read_file(path3), False) with self.assertRaises(FileNotFoundError): drone.read_file(path4)
def generateDrone(self): while True: x,y=randint(0,self.GRIDS_X-1),randint(0,self.GRIDS_Y-1) if self.grid[y][x] == 0: self.drone = Drone(x,y) self.grid[y][x] = self.drone break
def setEnemy(self, enum, x, y): if (enum == 0): return Drone(x, y) elif (enum == 1): return Fighter(x, y) elif (enum == 2): return Diver(x, y)
def main(): drone1 = Drone() user_input = 5 while user_input != 0: user_input = int( input("Enter 1 for accelerate, 2 for decelerate, " "3 for ascend, 4 for descend, 0 for exit: ")) if user_input == 1: drone1.accelerate() print("Speed ", drone1.speed, "Height", drone1.height) elif user_input == 2: drone1.decelerate() print("Speed ", drone1.speed, "Height", drone1.height) elif user_input == 3: drone1.ascend() print("Speed ", drone1.speed, "Height", drone1.height) elif user_input == 4: drone1.descend() print("Speed ", drone1.speed, "Height", drone1.height) else: print("Error please input 1, 2, 3, 4, or 0") user_input = int( input( "Enter 1 for accelerate, 2 for decelerate, 3 for ascend, 4 for descend, 0 for exit: " )) print("Speed ", drone1.speed, "Height", drone1.height)
def __init__(self): # Configure the four correctors for each coordinate self._pid_x = SpeedCorrector() self._pid_y = SpeedCorrector() self._pid_z = SpeedCorrector() self._pid_yaw = SpeedCorrector() # kalman filter is used for the drone state estimation self._estimate = StateEstimate() # Used to process images and backproject them # this._camera = new Camera(); TODO # Ensure that we don't enter the processing loop twice self._busy = False self._goal = None self.inFlight = None # The last known state self._state = {"x": 0, "y": 0, "z": 0, "yaw": 0} # The last time we have reached the goal (all control commands = 0) self._last_ok = 0 # Register the listener on navdata for our control loop def navdataListener(navdata): #print("seconds:", navdata.header.stamp.secs) self._processNavdata(navdata) self._control(navdata) # drone to manipulate self._drone = Drone(navdataListener)
def populate_drones(drones, max_payload, warehouse): id_ = -1 items = [] for i in xrange(drones): id_ += 1 items.append(Drone(id_, max_payload, warehouse.position)) return items
def __init__(self, host="", port=9000): threading.Thread.__init__(self) self.host = host self.port = port self.drone = Drone() self.socket = None self.start()
def main(): drone1 = Drone() oper = 1 while oper != 0: oper = int( input('Enter 1 for accelerate, 2 for decelerate, ' '3 for ascend, 4 for descend, 0 for exit: ')) if oper == 1: drone1.accelerate() print('Speed:', drone1.speed, 'Height:', drone1.height) print() elif oper == 2: drone1.decelerate() print('Speed:', drone1.speed, 'Height:', drone1.height) print() elif oper == 3: drone1.ascend() print('Speed:', drone1.speed, 'Height:', drone1.height) print() elif oper == 4: drone1.descend() print('Speed:', drone1.speed, 'Height:', drone1.height) print()
def registerNewCallSign(self, ssid): assert isinstance(ssid, str) i = len(self.managedDrones) + 1 callsign = "%s-%i" % (self.squadronPrefix, i) self.managedDrones[ssid] = Drone(ssid, callsign) self.saveDroneList() return callsign
def main(): # create Drone object drone = Drone() # set choice to 5 choice = 5 while(choice != 0): # input choice choice = int(input( "Enter 1 for accelerate, 2 for decelerate, 3 for ascend, 4 for descend, 0 for exit: ")) # if choice is 1, call accelerate method of drone object if(choice == 1): drone.accelerate() # if choice is 2, call decelerate method of drone object if(choice == 2): drone.decelerate() # if choice is 3, call ascend method of drone object if(choice == 3): drone.ascend() # if choice is 4, call descend method of drone object if(choice == 4): drone.descend() if(choice == 0): exit() # display speed and height of drone object print(drone.__str__())
def __init__(self, path): self.path = path input_data = self._get_input(path) self.deadline = input_data["deadline"] self.rows = input_data["rows"] self.columns = input_data["columns"] self.num_products = input_data["num_products"] self.num_drones = input_data["num_drones"] self.num_orders = input_data["num_orders"] self.num_warehouses = input_data["num_warehouses"] self.max_load = input_data["max_load"] self.products = [ Product(weight) for weight in input_data["product_weights"] ] self.warehouses = [ Warehouse(wh["row"], wh["column"], wh["stock"]) for wh in input_data["warehouses"] ] self.drones = [ Drone(i, self.warehouses, input_data["max_load"]) for i in range(input_data["num_drones"]) ] self.orders = [ Order(i, order["row"], order["column"], order["product_ids"]) for i, order in enumerate(input_data["orders"]) ]
def __init__(self): self.config_parser = ConfigObj('../config/config') self.droneNum = int(self.config_parser.get('NUMBER_OF_DRONES')) self.drones = [] for drone_id in range(1, self.droneNum): self.drones.append( Drone(drone_id, self.getWorkerNode('worker-1')['ipv4'][0]))
def test_fly(self): file1 = 'testcase/test_check.txt' # regular test: a drone with wrong position d0 = Drone(filepath=file1) self.assertEqual(d0.paths[-1], ('NA', 'NA', 'NA')) # regular test with float number and negtive number d1 = Drone() self.assertEqual(tuple(d1.pos), (0, 0, 0)) d1._fly((1, 2, 3)) self.assertEqual(tuple(d1.pos), (1, 2, 3)) d1._fly((-1.5, 2.0, 3)) self.assertEqual(tuple(d1.pos), (-0.5, 4, 6)) # test invalid 'offset' with self.assertRaises(AssertionError): d1._fly((1, 2, 3, 4))
def __init__(self, droneCount, capacity, warehouses, orders, productTypeWeights): self.drones = [] for i in range(0, droneCount): d = Drone(i, capacity, warehouses[0]['location']) self.drones.append(d) self.warehouses = warehouses self.orders = orders self.productTypeWeights = productTypeWeights
def __init__(self, max_weight, drone_count, x0, y0, max_turn): self.drones = [] self.max_weight = max_weight self.max_turn = max_turn self.current_turn = 0 for i in range(0, drone_count): self.drones.append(Drone(i, x0, y0)) Drone.max_weight = max_weight Drone.max_turn = max_turn
def load(self, name: str): """load a save of environment with json compatible Args: name (str): name of the folder Returns: [type]: [description] """ if name[-5:] != ".json": name += ".json" try: f = open(name, 'r') dic = json.load(f) except: print("Unable to open file, invalid file!") print("nom : ", name) return None try: drones = [] for drone in dic['drones']: position = Vector(drone["position"]["x"], drone["position"]["y"]) vitesse = Vector(drone["speed"]["vx"], drone["speed"]["vy"]) radius = drone["radius"] color = (drone["color"][0], drone["color"][1], drone["color"][2]) name = drone["name"] drones.append(Drone(position, vitesse, radius, name, color)) objs = [] for obj in dic['objects']: points = [] for point in obj["points"]: points.append(Vector(point["x"], point["y"])) objs.append(Object(points)) try: points = [] for point in dic['goal']["points"]: points.append(Vector(point["x"], point["y"])) self.goal = Object(points) except: self.goal = None self.objects = objs self.drones = drones self.nb_drones = len(drones) self.nb_objects = len(objs) except: print("invalid file type!") return None
def main(DEBUG=False): m = Map(imagePath, scale=100, sampleResolution=26) d = Drone(m) pf = ParticleFilter(m, d, numParticles=1000) pf.calculateLikelihood() pf.drawParticles() # embed() finish = False manualMoveIncrement = m.scale_percent while not finish: update = False dp = (0, 0) util.drawCircle(m.image, m.positionToPixel(d.pos)) m.show() m.clearImage() # cv.imshow('image', m.sample(d.pos, sample_resolution=sampleWidth)) key = cv.waitKey(0) if (key == ord('q')): finish = True elif (key == ord('w')): dp = (0, -manualMoveIncrement) d.move(dp) update = True elif (key == ord('s')): dp = (0, manualMoveIncrement) d.move(dp) update = True elif (key == ord('a')): dp = (-manualMoveIncrement, 0) d.move(dp) update = True elif (key == ord('d')): dp = (manualMoveIncrement, 0) d.move(dp) update = True elif (key == 13): #enter dp = d.generateRandomMovementVector_map() d.move(dp) update = True else: print("Unrecognized key") if (DEBUG): distance = sum([util.distance(p.pos, d.pos) for p in pf.particles]) / len(pf.particles) print("true: ", d.pos) [ print("{:01.2f} : {:01.2f}".format(p.pos[0], p.pos[1])) for p in pf.particles ] print("distance: ", distance) pf.fullUpdate(dp)
def parse(inFileName): with open(inFileName, "r") as inFile: header = inFile.readline() rows, columns, nr_drones, nr_turns, max_payload = list( map(int, header.strip().split(" "))) # read product types nr_products = int(inFile.readline()) products = list(map(int, inFile.readline().strip().split(" "))) assert len(products) == nr_products # read warehouses nr_warehouses = int(inFile.readline()) warehouses = [] for i in range(nr_warehouses): pos = tuple(map(int, inFile.readline().strip().split(" "))) items = list(map(int, inFile.readline().strip().split(" "))) assert len(items) == nr_products warehouses.append(Warehouse(i, pos, items)) assert len(warehouses) == nr_warehouses # read orders nr_orders = int(inFile.readline()) orders = [] lines = inFile.readlines() for i, (pos, nr_items, items) in enumerate(zip(lines[::3], lines[1::3], lines[2::3])): pos = tuple(map(int, pos.split(" "))) items = list(map(int, items.strip().split(" "))) assert int(nr_items) == len(items) orders.append(Order(id=i, pos=pos, items=items)) assert len(orders) == nr_orders # init drones to simulate drones = [] first_warehouse = warehouses[0] for i in range(nr_drones): drone = Drone(pos=first_warehouse.pos, id=i, max_payload=max_payload) drones.append(drone) return State(rows=rows, columns=columns, nr_turns=nr_turns, max_payload=max_payload, products=products, warehouses=warehouses, orders=orders, drones=drones)
def make_3d_lattice(side_num, sep_len): # create a 3d lattice (cube) of drones # with side_num drones per edge, sepearted by a distance of sep_len # Means you will have side_num^3 many drones. ds = [] for i in range(side_num): for j in range(side_num): for k in range(side_num): d = Drone() d.position = np.array([i * sep_len, j * sep_len, k * sep_len]) ds.append(d) return ds
def create_objects(): environment = Environment() environment.load_environment("assets/test2.map") detected_map = DetectedMap() row = randint(0, 19) column = randint(0, 19) drone = Drone(row, column, detected_map) return environment, detected_map, drone
def loadDroneList(self): if self.droneListPath is None: self.managedDrones = {} else: with open(self.droneListPath, 'r') as f: raw = f.read() self.managedDrones = { d.split(":")[0]: Drone(d.split(":")[0], d.split(":")[1]) for d in raw.split("\n") } print self.managedDrones
def __init__(self, w=WIDTH, h=HEIGHT): self.w = w self.h = h self.display = pygame.display.set_mode((self.w, self.h)) pygame.display.set_caption('BLOCKS_AI') self.drone = Drone(20, RED) self.man = Man(20, BLUE1) self.reset() self.clock = pygame.time.Clock() self.time = 0
def init_drone(self) -> Drone: """Creates a Drone object initialised with a deterministic set of target coordinates. Returns: Drone: An initial drone object with some programmed target coordinates. """ drone = Drone() drone.add_target_coordinate((0.35, 0.3)) drone.add_target_coordinate((-0.35, 0.4)) drone.add_target_coordinate((0.5, -0.4)) drone.add_target_coordinate((-0.35, 0)) return drone
def on_init(self): pygame.init() self.drone_sprites = pygame.sprite.Group() self.shape_sprites = pygame.sprite.Group() self.display_surf = pygame.display.set_mode(win_size) pygame.display.set_caption(GAME_TITLE) for i in range(0, SWARM_SIZE): self.drone_array.append( Drone(self, random.randint(0, WIDTH - DRONE_SIZE), random.randint(0, HEIGHT - DRONE_SIZE))) pygame.display.update() self.load_data()
def reset(self): """ Reset the Level """ self.completionRating = CompletionRating(self) self.moveRating = MoveRating(self) self.powerRating = PowerRating(self.getPowerRating(), self) self.minefield = Minefield(self.rows, self.columns) self.drone = Drone(self.minefield, self.moveRating, self.powerRating) self.defenseItems = [] for defenseClass in self.defenses: for i in range(self.defenses[defenseClass]): self.addDefense(defenseClass)