def readVertices(self): nodes = self.nodeService.getAllNodes() for i in range(0, nodes.count()): for j in range(0, nodes.count()): nodesEdge = None if i == j: self.graph[i, j] = 0 else: edge = self.wayService.fetchWayforNodes( [nodes[i]['osmId'], nodes[j]['osmId']]) if edge != None and edge.count( ) > 0 and 'osmId' in edge[0]: nodesEdge = edge[0] self.graph[i, j] = Haversian.getInstance().calculateDistance( Coordinates(nodes[i]['lng'], nodes[i]['lat']), Coordinates(nodes[j]['lng'], nodes[j]['lat'])) graphNode = {} graphNode['index'] = (i, j) graphNode['from'] = nodes[i]['osmId'] graphNode['to'] = nodes[j]['osmId'] graphNode['distance'] = self.graph[i, j] graphNode['edge'] = nodesEdge self.storeGraph(graphNode)
def __init__(self): super(CoordinatesList, self).__init__() self.selectIndex = 0 self.append(Coordinates('test', 10, 10)) self.append(Coordinates('test2', 20, 20)) self.append(Coordinates('test3', 30, 30)) self.append(Coordinates('test4', 40, 40)) self.append(Coordinates('test5', 50, 50))
def __move(self, direction): if (direction == 'UP' and self.head().y() > self.__topLimit): self.prepend(Coordinates(self.head().x(), self.head().y() - 1)) self.removeLast() elif (direction == 'DOWN' and self.head().y() + self.__length - 1 < self.__bottomLimit): self.append( Coordinates(self.head().x(), self.head().y() + self.__length)) self.removeFirst()
def initializeGameField(self): self.__ball = Ball( Coordinates(round(self.__width / 2), round(self.__height / 2))) self.__xDirectionBall = 'LEFT' self.__yDirectionBall = 'UP' self.__snake = Snake(4, round(self.__width * 2 / 3), round(self.__height / 2)) self.__snakeDirection = 'LEFT' self.__pong = Pong(4, Coordinates(2, round(self.__height / 2) - 1), 1, self.__height - 2)
def newCoordinates(self, direction): lastHeadCoordinates = self.head() newCoordinates = lastHeadCoordinates if(direction=='UP'): newCoordinates = Coordinates(lastHeadCoordinates.x(),lastHeadCoordinates.y()-1) elif(direction=='DOWN'): newCoordinates = Coordinates(lastHeadCoordinates.x(),lastHeadCoordinates.y()+1) elif(direction=='LEFT'): newCoordinates = Coordinates(lastHeadCoordinates.x()-1,lastHeadCoordinates.y()) elif(direction=='RIGHT'): newCoordinates = Coordinates(lastHeadCoordinates.x()+1,lastHeadCoordinates.y()) return newCoordinates
def get_occupied_sectors(self, y, x, orientation): squares = [] if orientation == "H": squares.insert(0, Coordinates(y, x)) for i in range(1, self.size): squares.insert(i, Coordinates(y, x + i)) return squares else: squares.insert(0, Coordinates(y, x)) for i in range(1, self.size): squares.insert(i, Coordinates(y + i, x)) return squares
def moveBall(self): # check if ball hits wall (left or right) --> add point to player1/player2 if (self.__ball.x() == 1 and self.__xDirectionBall == 'LEFT'): self.__player1.addPoint() self.resetField() elif (self.__ball.x() == self.__width - 2 and self.__xDirectionBall == 'RIGHT'): self.__player2.addPoint() self.resetField() # check if ball hits wall (top or bottom) if (self.__ball.y() == 1 and self.__yDirectionBall == 'UP'): self.__yDirectionBall = 'DOWN' elif (self.__ball.y() == self.__height - 2 and self.__yDirectionBall == 'DOWN'): self.__yDirectionBall = 'UP' # check if ball hits pong if (self.__pong.contains( Coordinates(self.__ball.x() - 1, self.__ball.y())) and self.__xDirectionBall == 'LEFT'): self.__xDirectionBall = 'RIGHT' # check if ball hits snake if (self.__snake.contains( Coordinates(self.__ball.x() - 1, self.__ball.y())) and self.__xDirectionBall == 'LEFT'): self.__xDirectionBall = 'RIGHT' elif (self.__snake.contains( Coordinates(self.__ball.x() + 1, self.__ball.y())) and self.__xDirectionBall == 'RIGHT'): self.__xDirectionBall = 'LEFT' if (self.__snake.contains( Coordinates(self.__ball.x(), self.__ball.y() - 1)) and self.__yDirectionBall == 'UP'): self.__yDirectionBall = 'DOWN' elif (self.__snake.contains( Coordinates(self.__ball.x(), self.__ball.y() + 1)) and self.__yDirectionBall == 'DOWN'): self.__yDirectionBall = 'UP' # move ball self.__ball.move(self.__xDirectionBall, self.__yDirectionBall)
def createRover(stringDirection="N"): x = 12 y = 5 startingPoint = Coordinates(x, y) direction = Direction(stringDirection) return Rover(startingPoint, direction)
def __init__(self): # initialize the node named image_processing rospy.init_node('image_processing', anonymous=True) # initialize a publisher to send images from camera1 to a topic named image_topic1 # initialize a publisher to send joints' angular position to a topic called joints_pos self.joints_pub = rospy.Publisher("joints_pos", Float64MultiArray, queue_size=10) self.target_pub = rospy.Publisher("target_pos", Float64MultiArray, queue_size=10) # initialize a subscriber to recieve messages rom a topic named /robot/camera1/image_raw and use callback function to recieve data self.image_sub1 = message_filters.Subscriber("/image_topic1", Image) self.image_sub2 = message_filters.Subscriber("/image_topic2", Image) sync = message_filters.TimeSynchronizer( [self.image_sub1, self.image_sub2], 10) sync.registerCallback(self.callback_sync) #rospy.TimeSynchronizer # initialize the bridge between openCV and ROS self.bridge = CvBridge() # iterator to capture images self.iterator = 0 # use class for object detection self.coord = Coordinates() self.od = ObjectDetection() self.svm = classifer([['obj0', 8], ['obj1', 8]]) self.svm.addTrainSamples('images_train') self.svm.train('svm.xml') self.pix2meter0 = 0 self.pix2meter1 = 0
def test_getPong(): list = Pong(4,Coordinates(2,2),1,20) array = list.getPong() assert array[0].x() == 2 and array[0].y() == 2 assert array[1].x() == 2 and array[1].y() == 3 assert array[2].x() == 2 and array[2].y() == 4 assert array[3].x() == 2 and array[3].y() == 5
def __init__(self, b_or_w): self.grid = [] for row in range(8): self.grid.append([]) for col in range(8): coordinates = Coordinates(row, col) cell = Cell(coordinates, "-") self.grid[row].append(cell) self.AI_symbol = "" if b_or_w == "B": self.grid[3][3].setSymbol("B") self.grid[3][4].setSymbol("W") self.grid[4][4].setSymbol("B") self.grid[4][3].setSymbol("W") self.AI_symbol = "W" if b_or_w == "W": self.grid[3][3].setSymbol("W") self.grid[3][4].setSymbol("B") self.grid[4][4].setSymbol("W") self.grid[4][3].setSymbol("B") self.AI_symbol = "B" self.current_moves = [] self.weight_grid = [[1616, -303, 99, 43, 43, 99, -303, 1616], [-412, -581, -8, -27, -27, -8, -581, -412], [133, -4, 51, 7, 7, 51, -4, 133], [63, -18, -4, -1, -1, -4, -18, 63], [63, -18, -4, -1, -1, -4, -18, 63], [133, -4, 51, 7, 7, 51, -4, 133], [-412, -581, -8, -27, -27, -8, -581, -412], [1616, -303, 99, 43, 43, 99, -303, 1616]] self.late_tree = {} self.mid_tree = {} self.node_list = []
def drawPoints(): coordinates = Coordinates(x_mouse, y_mouse) pointsA.add_coordinates(coordinates) for i in range(0, pointsA.get_size()): pygame.draw.circle( screen, rgb, Coordinates.get_coordinates(pointsA.get_coordinates(i)), 7)
def __init__(self, b_or_w): self.grid = [] for row in range(8): self.grid.append([]) for col in range(8): coordinates = Coordinates(row, col) cell = Cell(coordinates, "-") self.grid[row].append(cell) self.AI_symbol = "" if b_or_w == "B": self.grid[3][3].setSymbol("B") self.grid[3][4].setSymbol("W") self.grid[4][4].setSymbol("B") self.grid[4][3].setSymbol("W") self.AI_symbol = "W" if b_or_w == "W": self.grid[3][3].setSymbol("W") self.grid[3][4].setSymbol("B") self.grid[4][4].setSymbol("W") self.grid[4][3].setSymbol("B") self.AI_symbol = "B" self.graph = {} self.weight_grid = [ [16.16, -3.03, 0.99, 0.43, 0.43, 0.99, -3.03, 16.16], [-4.12, -5.81, -0.08, -0.27, -0.27, -0.08, -5.81, -4.12], [1.33, -0.04, 0.51, 0.07, 0.07, 0.51, -0.04, 1.33], [0.63, -0.18, -0.04, -0.01, -0.01, -0.04, -0.18, 0.63], [0.63, -0.18, -0.04, -0.01, -0.01, -0.04, -0.18, 0.63], [1.33, -0.04, 0.51, 0.07, 0.07, 0.51, -0.04, 1.33], [-4.12, -5.81, -0.08, -0.27, -0.27, -0.08, -5.81, -4.12], [16.16, -3.03, 0.99, 0.43, 0.43, 0.99, -3.03, 16.16] ]
def notifications(): di = Distance() lat = curr_df.loc[0]["Lat"] long = curr_df.loc[0]["Long"] spd = curr_df.loc[0]["Spd"] angle = curr_df.loc[0]["Angle"] alt = curr_df.loc[0]["Alt"] for i in range(0, len(alert_df)): alat = alert_df.loc[i]["Lat"] along = alert_df.loc[i]["Long"] aSpeed = alert_df.loc[i]["Spd"] aAngle = alert_df.loc[i]["Angle"] aAlt = alert_df.loc[i]["Alt"] d = di.getDistFeet(lat, long, alat, along) counter = 0 prevMainPlane = [lat, long] prevAlertPlane = [alat, along] newMainPlane = [] newAlertPlane = [] prevDistance = d newDistance = 0 altDiff = di.heightDist(alt, aAlt) c = Coordinates() diverging_flg = 0 min_dist_flg = 0 bad_alt_flg = 0 msg = '' if (altDiff > 1000): msg = "Altitude difference (" + str(altDiff) + "ft) in safe zone, no current possibility of collision." bad_alt_flg = 1 else: while (1): newMainPlane = c.get_next_point(spd, angle, prevMainPlane[0], prevMainPlane[1]) newAlertPlane = c.get_next_point(aSpeed, aAngle, prevAlertPlane[0], prevAlertPlane[1]) newDistance = di.getDistFeet(newMainPlane[0], newMainPlane[1], newAlertPlane[0], newAlertPlane[1]) print(newDistance) counter += 1 if (newDistance > prevDistance): diverging_flg = 1 break; elif (newDistance < 9260): min_dist_flg = 1 break; else: prevMainPlane = newMainPlane prevAlertPlane = newAlertPlane if (diverging_flg): msg = "Flight path not intersecting. No possibility of collision." elif (min_dist_flg): msg = "Altitude in bad zone (" + str(altDiff) + "ft), flight paths intersect in " + str(counter) + "mins." elif(bad_alt_flg): msg="Altitude difference (" + str(altDiff) + "ft) in safe zone, no current possibility of collision." alert_df['Warning'] = msg current=curr_df.to_dict(orient='records') alerts=alert_df.to_dict(orient='records') global selected_Icao return render_template('notifications.html',current=current,alerts=alerts,selected_Icao=selected_Icao)
def get_average_location(self): return Coordinates( sum(loc.x for loc in self.get_player_locations()) / len(self.get_player_locations()), sum(loc.y for loc in self.get_player_locations()) / len(self.get_player_locations()), sum(loc.z for loc in self.get_player_locations()) / len(self.get_player_locations()))
def __init__(self): self.laneList = list() url = 'https://datosabiertos.malaga.eu/recursos/transporte/trafico/da_carrilesBici-4326.geojson' response = urllib.request.urlopen(url) if response.status >= 400: raise RuntimeError( 'Error with the request. Error code:' + response.status_code, response.status_code) self.data = response.read() features = json.loads(self.data)['features'] for feature in features: id = feature['id'] ogc_fid = feature['properties']['ogc_fid'] name = feature['properties']['name'] description = Description( feature['properties']['description']).getDescriptionLane() coordinates = list() #Malaga longitud=-4 latitud=36 geometries = feature['geometry']['coordinates'] if feature['geometry']['type'] == 'Point': coordenadas = Coordinates(latitud=geometries[0], longitud=geometries[1]) coordinates.append({ 'latitud': coordenadas.getLatitud(), 'longitud': coordenadas.getLongitud() }) elif feature['geometry']['type'] == 'LineString': for geometry in geometries: coordenadas = Coordinates(geometry[0], geometry[1]) coordinates.append({ 'latitud': coordenadas.getLatitud(), 'longitud': coordenadas.getLongitud() }) self.laneList.append({ 'name': name, 'id': id, 'ogc_fid': ogc_fid, 'description': description, 'coordinates': coordinates, 'type': feature['geometry']['type'] })
def calcPossibleMoves(self): possibleMoves = [] if self.hasWon(CIRCLE) or self.hasWon(CROSS): return possibleMoves for i in range(DIMENSION): for j in range(DIMENSION): if self.mapMatrix.matrix[i][j] == EMPTY: temp = Coordinates(i, j) possibleMoves.append(temp) return possibleMoves
def __init__(self): GObject.Object.__init__(self) self.activations = 0.0 self.successes = 0.0 self.transitory = False self.memory_limit = 10000.0 self.props = {} self.props_var = {} #self.self_flag = False self.id = -1 self.coords = Coordinates() self.excitation = 0.0
def __init__(self, name): if name == "yokohama.egg": myDictClass = Coordinates() oldDict = myDictClass.coords self.newDict = dict() for key in oldDict: coordX = key[0] coordY = key[1] zValue = myDictClass.coords[key] coordX = coordX // 100 * 100 coordY = coordY // 100 * 100 self.newDict[(coordX, coordY)] = int(zValue)
def run(self): L2_reg = self.L2_reg activations = self.activations step_size = self.step_size y_type = self.y_type loss_type = self.loss_type # Initial neural net parameters init_params = initialize_parameters(self.layer_sizes, var=self.w_var) print("Loading training data...") X_train, X_test, y_train, y_test = load_data(self.y_type) self.store(X_train, X_test, y_train, y_test) self.Coordinates = Coordinates( np.concatenate((y_train, y_test), axis=0)) num_batches = int(ceil(X_train.shape[0] / BATCH_SIZE)) def batch_indices(iter): if iter % num_batches == 0: # Shuffle the data X_train, X_test, y_train, y_test = load_data(self.y_type) self.store(X_train, X_test, y_train, y_test) idx = iter % num_batches return slice(idx * BATCH_SIZE, (idx + 1) * BATCH_SIZE) def objective(parameters, iter): idx = batch_indices(iter) return loss(parameters, X_train[idx], y_train[idx], L2_reg, activations, y_type, loss_type) objective_grad = grad(objective) def print_perf(parameters, iter, gradient): if iter % num_batches == 0: train_acc = error(parameters, X_train, y_train, activations, y_type, loss_type) test_acc = error(parameters, X_test, y_test, activations, y_type, loss_type) reg = reg_loss(parameters, L2_reg) print("{:15}|{:20}|{:20}|{:20}".format(iter // num_batches, train_acc, test_acc, reg)) print("Training the neural network ...") self.optimized_params = adam(objective_grad, init_params, step_size=step_size, num_iters=EPOCHS * num_batches, callback=print_perf) return self.results(self.optimized_params, activations, L2_reg, X_train, X_test, y_train, y_test)
def __init__(self, tag_id, timestamp=0, coordinates=Coordinates(0, 0, 0), speed=0, direction=0, acceleration=0, distance=0, high_filtered_speed=0, high_filtered_direction=0, high_filtered_acceleration=0, high_filtered_distance=0): self.tag_id = tag_id self.location = coordinates self.speed = speed self.direction = direction self.acceleration = acceleration self.distance = distance self.timestamp = timestamp self.high_filtered_speed = high_filtered_speed self.high_filtered_direction = high_filtered_direction self.high_filtered_acceleration = high_filtered_acceleration self.high_filtered_distance = high_filtered_distance
def test_move(): list = Pong(4,Coordinates(2,2),1,20) list.move(Coordinates(10,10)) assert list.head().x() == 2 and list.head().y() == 3 list.move(Coordinates(10,10)) assert list.head().x() == 2 and list.head().y() == 4 # Test limits top list.move(Coordinates(10,1)) assert list.head().x() == 2 and list.head().y() == 3 list.move(Coordinates(10,1)) assert list.head().x() == 2 and list.head().y() == 2 list.move(Coordinates(10,1)) assert list.head().x() == 2 and list.head().y() == 1 list.move(Coordinates(10,1)) assert list.head().x() == 2 and list.head().y() == 1 # Test limits bottom secondList = Pong(4,Coordinates(2,16),1,20) secondList.move(Coordinates(10,20)) assert secondList.head().x() == 2 and secondList.head().y() == 17 secondList.move(Coordinates(10,20)) assert secondList.head().x() == 2 and secondList.head().y() == 17
def __init__(self): self.parkList = list() url = "https://datosabiertos.malaga.eu/recursos/transporte/trafico/da_aparcamientosBici-4326.geojson" response = urllib.request.urlopen(url) self.data = response.read() features = json.loads(self.data)['features'] for feature in features: id_parking = feature['id'] ogc_fid = feature['properties']['ogc_fid'] desc = Description(feature['properties']['description']) description = desc.getDescriptionParking() name = desc.getNameParking() coordinates = list() geometries = feature['geometry']['coordinates'] if feature['geometry']['type'] == 'Point': coordenadas = Coordinates(latitud=geometries[1], longitud=geometries[0]) coordinates.append({ 'latitud': coordenadas.getLatitud(), 'longitud': coordenadas.getLongitud() }) elif feature['geometry']['type'] == 'LineString': for geometry in geometries: coordenadas = Coordinates(geometry[1], geometry[0]) coordinates.append({ 'latitud': coordenadas.getLatitud(), 'longitud': coordenadas.getLongitud() }) self.parkList.append({ 'name': name, 'id': id_parking, 'ogc_fid': ogc_fid, 'description': description, 'coordinates': coordinates })
def __init__(self): self.laneList = list() url = "https://datosabiertos.malaga.eu/recursos/transporte/trafico/da_carrilesBici-25830.geojson" response = urllib.request.urlopen(url) self.data = response.read() features = json.loads(self.data)['features'] for feature in features: id = feature['id'] ogc_fid = feature['properties']['ogc_fid'] name = feature['properties']['name'] description = Description( feature['properties']['description']).getDescription() coordinates = list() #Málaga longitud=4 latitud=36 geometries = feature['geometry']['coordinates'] if feature['geometry']['type'] == 'Point': coordenadas = Coordinates(geometries[0], geometries[1]) coordinates.append({ 'latitud': coordenadas.getLatitud(), 'longitud': coordenadas.getLongitud() }) elif feature['geometry']['type'] == 'LineString': for geometry in geometries: coordenadas = Coordinates(geometry[0], geometry[1]) coordinates.append({ 'latitud': coordenadas.getLatitud(), 'longitud': coordenadas.getLongitud() }) self.laneList.append({ 'name': name, 'id': id, 'ogc_fid': ogc_fid, 'description': description, 'coordinates': coordinates })
def main(): gameMatrix = MapMatrix(DIMENSION) view = View() view.draw(gameMatrix.matrix) ai = MinMaxStrategy(gameMatrix) view.draw(gameMatrix.matrix) while True: i = pygame.event.wait() if i.type == pygame.QUIT: sys.exit(0) if pygame.mouse.get_pressed()[LEFT_MOUSE]: pos = pygame.mouse.get_pos() wsp_x = int(pos[POS_X] / (SMALL_BOX_LENGTH + SPACE_LENGTH)) wsp_y = int(pos[POS_Y] / (SMALL_BOX_LENGTH + SPACE_LENGTH)) if pos[POS_X] > BOX_LENGTH or pos[POS_X] < 0 or pos[ POS_Y] > BOX_LENGTH or pos[POS_Y] < 0 or gameMatrix.matrix[ wsp_y][wsp_x] != EMPTY: continue else: gameMatrix.markCrossOn(Coordinates(wsp_y, wsp_x)) view.draw(gameMatrix.matrix) SoundService.playCrossSound() if ai.hasWon(CROSS): sys.exit("Wygrales!") elif (not ai.hasWon(CROSS)) and gameMatrix.checkIfMapFull(): sys.exit("Remis!") ai.doBestMove(gameMatrix) view.draw(gameMatrix.matrix) SoundService.playCircleSound() if ai.hasWon(CIRCLE): sys.exit("Przegrales!") elif (not ai.hasWon(CIRCLE)) and gameMatrix.checkIfMapFull(): sys.exit("Remis!")
def main(): MotorObject = Motor() CoordinatesObject = Coordinates() CalculationsObject = Calculations() SaveToSD_Object = SaveToSD() forceStopped = False waitForInput() time.sleep(2) for i in range(73): # alleen voor debugging if GPIO.input(buttonPin) == GPIO.LOW: # Force stop print("Force stopping!") forceStopped = True changeColor('red') break MotorObject.turnMotor(i) CoordinatesObject.calculate_coordinates(i) if not forceStopped: CalculationsObject.run() SaveToSD_Object.save()
from Coordinates import Coordinates from Tower import Tower TOTAL_TASKS = 4 TOTAL_TIME_LIMIT = 5000 INIT_BALL_LIMIT = 100 INIT_BLOCK_LIMIT = 100 INIT_FLOWER_LIMIT = 100 INIT_SWITCH_LIMIT = 100 BUILDING_HEIGHT = 3 BLOCK_CAPACITY = 10 # placeholder # Important Locations first_recup_location = Coordinates(0, 0, 0) # placeholder second_recup_location = Coordinates(1, 1, 1) # placeholder BLOCK_LOCATION = Coordinates(1, 1, 1) # placeholder BUILDING_PLAN_LOCATION = Coordinates(1, 1, 1) # placeholder ASSEMBLY_LOCATION = Coordinates(1, 1, 1) # placeholder our_tower = Tower(2, 2, 2) # placeholder their_tower = Tower(2, 2, 2) # placeholder
#Attributes loop = True loop_shoot = True player_turn = 1 number_of_ships = 5 #Player1 and Player2 are Ships and can use the Ships and Place functions player1 = Ships() player2 = Ships() #Player1 shoot grid and Player2 shoot grid are Shoot and can use the Shoot and ShotLocation functions player1_shoot_grid = Shoot() player2_shoot_grid = Shoot() #coordinate map is of class Coordinates which prints the coordinate grid coordinate_map = Coordinates() #Asking the user to input grid size while loop: try: user_input = input( "Please enter a number for the size of the grid between 5 and 10 ") user_input = user_input.lower() if user_input == "exit battleships": sys.exit() grid_size = int(user_input) if grid_size >= 5 and grid_size <= 10: break else: print("Input must be between 5 and 10 \n")
def createPong(self, startCoordinates): self.prepend(startCoordinates) for offset in range(1, self.__length): self.append( Coordinates(startCoordinates.x(), startCoordinates.y() + offset))
for i in range(0,len(alert_df)): alat = alert_df.loc[i]["Lat"] along = alert_df.loc[i]["Long"] aSpeed= alert_df.loc[i]["Spd"] aAngle=alert_df.loc[i]["Angle"] aAlt=alert_df.loc[i]["Alt"] d=di.getDistFeet(lat,long,alat,along) counter=0 prevMainPlane=[lat,long] prevAlertPlane=[alat,along] newMainPlane=[] newAlertPlane=[] prevDistance=d newDistance=0 altDiff=di.heightDist(alt, aAlt) c=Coordinates() diverging_flg = 0 min_dist_flg = 0 bad_alt_flg = 0 msg='' if((altDiff)>1000): msg="Altitude difference ("+str(altDiff)+"ft) in safe zone, no current possibility of collision." bad_alt_flg=1 continue else: while(1): newMainPlane = c.get_next_point(spd,angle,prevMainPlane[0],prevMainPlane[1]) newAlertPlane= c.get_next_point(aSpeed,aAngle,prevAlertPlane[0],prevAlertPlane[1]) newDistance = di.getDistFeet(newMainPlane[0],newMainPlane[1],newAlertPlane[0],newAlertPlane[1]) print(newDistance) counter+=1