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): # 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 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 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 __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 getDimensionBigNeighbours(self, from_, dim): coord = Coordinates(from_) val = coord.getDimension(dim) bigger = Coordinates(from_) bigger.setDimension(dim, val + 1) if bigger in self.gridList: return bigger return coord
def getDimensionSmallNeighbours(self, from_, dim): coord = Coordinates(from_) val = coord.getDimension(dim) smaller = Coordinates(from_) smaller.setDimension(dim, val - 1) if smaller in self.gridList: return smaller return coord
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 parseXml(node): field = Field() for child in node.childNodes: if child.tagName == Coordinates.getXmlName(): field.addBoundary(Coordinates.parseXml(child)) if child.tagName == Network.getXmlName(): field.addNetwork(Network.parseXml(child)) if child.tagName == District.getXmlName(): field.addDistrict(District.parseXml(child)) return field
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 parseXml(node): district = District() district.districtType = int(node.getAttribute("type")) for child in node.childNodes: if child.tagName == Coordinates.getXmlName(): district.addBoundary(Coordinates.parseXml(child)) if child.tagName == Network.getXmlName(): district.addNetwork(Network.parseXml(child)) if child.tagName == Block.getXmlName(): district.addBlock(Block.parseXml(child)) return district
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 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 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 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 drawLine(): if pointsA.get_size() > 1: for i in range(1, pointsA.get_size()): temp = i - 1 pygame.draw.line( screen, rgb, Coordinates.get_coordinates(pointsA.get_coordinates(i)), Coordinates.get_coordinates(pointsA.get_coordinates(temp)), 3) #pygame.time.delay(1000) if i == pointsA.get_size() - 1: pygame.draw.line( screen, rgb, Coordinates.get_coordinates(pointsA.get_coordinates(i)), Coordinates.get_coordinates(pointsA.get_coordinates(0)), 3)
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 __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 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 createRover(stringDirection="N"): x = 12 y = 5 startingPoint = Coordinates(x, y) direction = Direction(stringDirection) return Rover(startingPoint, direction)
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 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 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, 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 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, 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 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()
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 getNeighbours(self, from_): neighbours = list() dim = 0 while dim < from_.getSize(): val = from_.getDimension(dim) bigger = Coordinates(from_) bigger.setDimension(dim, val + 1) if bigger in self.gridList: neighbours.append(bigger) smaller = Coordinates(from_) smaller.setDimension(dim, val - 1) if smaller in self.gridList: neighbours.append(smaller) dim += 1 return neighbours
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!")
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))
# coding=utf-8 import cv2 from Perspective import Perspective from Coordinates import Coordinates if __name__ == "__main__": path = "book1.jpg" sourceImg = cv2.imread(path) persp = Perspective(sourceImg) persp.handle() # 预处理 edges = persp.edgesDetectCanny() # Canny hull = persp.contourMethod(edges) # 轮廓处理,获得符合要求的凸包 hullCoord = Coordinates(hull) # 检测凸包的坐标性质 if hull is not None and hullCoord.quadCheck(): # 如果凸包不为空,且能近似构成四边形 corners = hullCoord.calculateTRTLBRBL() correctedImg = persp.transform(corners) cv2.imshow("corrected Image", correctedImg) print "Yes. Correct the image successfully" cv2.waitKey(0) else: print "Laplacian" edges = persp.edgesDetectLaplacian() # 拉普拉斯算子 hull = persp.contourMethod(edges) hullCoord = Coordinates(hull) # 检测凸包的坐标性质 if hull is not None and hullCoord.quadCheck(): # 如果凸包不为空,且能近似构成四边形 corners = hullCoord.calculateTRTLBRBL() correctedImg = persp.transform(corners)
class Observation(GObject.Object): 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 get_properties(self): """Get Dictionary containing propserties Variable value is returned if exists else concrete is returned""" ps = {}; #print "Props: ", self.props, self.props_var for p in self.props.keys(): #print "In props_var: ", p if self.props_var.has_key(p) and self.props_var[p] != None: ps[p] = self.props_var[p] else: ps[p] = self.props[p] return ps def get_var_properties(self): """Returns variable properties of the observation""" ps = {} for p in self.props_var.keys(): ps[p] = self.props_var[p] return ps def get_concrete_properties(self): """Returns concrete properties, having concrete value not generalised""" props = {} for p in self.props.keys(): #print "Getting concrete props:", p, self.props[p] if self.props[p] != None: props[p] = self.props[p] else: props[p] = self.props_var[p] return props #Is self in others' lsit def __eq__(self, other): return self.equals(other) def equals(self, o2, ignore = False): """Returns True if two observations are equal""" props = self.get_concrete_properties(); props2 = o2.get_concrete_properties() #print "Testing if observations equal:",props, props2 if self.name != o2.name or self.self_flag != o2.self_flag: return False #print "Props Match:", self.get_concrete_properties(), o2.get_concrete_properties(), self.get_concrete_properties() == o2.get_concrete_properties(), self.get_similarity(o2) for p2 in props2.keys(): if not(props.has_key(p2)): return False #print "Observation prop type: ", type(props[p2]),type(props2[p2]) if (type(props[p2]) == type(props2[p2]) == type(float())): if self.name == "touching:": print "#######touching props:",props[p2], props2[p2] if abs(abs(props[p2]) - abs(props2[p2])) > 0: return False elif (props[p2] != props2[p2]): return False T = self.coords.equals(o2.coords) #print "\nMatching coords", self.coords.get_coords(), o2.coords.get_coords(), T if not T: #print "Coordinates don't match" return False return True def similar(self, o2, coords = True): """Returns True if two observations are equal""" #print "Testing if observations equal:",props, props2 if self.name != o2.name or self.self_flag != o2.self_flag: return False props = self.get_concrete_properties(); props2 = o2.get_concrete_properties() #print "Concrete_props_similar:", props, props2 for p2 in props2.keys(): if not(props.has_key(p2)): #print "Property not found:", p2 return False if(props[p2] != props2[p2]): #print "Property value not found:",p2,props[p2],type(props[p2]), props2[p2],type(props2[p2]), (props[p2] != props2[p2]) return False if coords and props[p2] != props2[p2]: return False #print "Observation equals: ", props, props2 return True def equivalents(self, o2, ignore = False): """Returns True if two observations are equal""" #print "Testing if observations equal:",props, props2 if self.name != o2.name or self.self_flag != o2.self_flag: return False props = self.get_properties(); props2 = o2.get_properties() for p2 in props2.keys(): if not(props.has_key(p2)): return False #print "Observation equals: ", props, props2 return True def copy(self): """Create copy of the observation""" o2 = Observation() o2.memory_limit = 100.0 o2.transitory = self.transitory o2.props = dict(self.props) o2.props_var = dict(self.props_var) o2.name = "%s"%self.name o2.self_flag = bool(self.self_flag) o2.activations = float(self.activations) o2.successes = float(self.successes) o2.id = int(self.id) o2.coords = self.coords.copy() o2.excitation = float(self.excitation) #print "Observation: Successes: ", self.successes #o2.set_property("sensor_id", self.sensor_id) #print "O.copy():", o2.props, self.props, inspect.stack()[1][3] return o2 def set_property_var(self, name, val): """Set value for the variable properties""" try: value = float(val) except: try: value = int(val) except: value = str(val) #print "Setting value: ", name, type(value), value if name == "x" or name == "y": self.coords.set_variable_coords(name, value) return self.props_var[str(name)] = value self.props[str(name)] = None #print "Value set: ", name, self.props_var[name] return def set_concrete_var(self, name, val): """Set value for the concrete property""" try: value = float(val) except: try: value = int(val) except: value = str(val) if name == "x" or name == "y": #print "setting concrete values for id:", self.id, name , value self.coords.set_concrete_coords(name, value) return #print "Seeting value: ", name, type(value), value self.props[str(name)] = value return # Override default similarity calculation because X, Y need to be considered together def get_similarity(self, o2, coords_include = False): """Returns similarity between two observations, scalled to 1.0""" similarity = 1.0; m_p = 0.0 o_props = self.get_concrete_properties(); o2_props = o2.get_concrete_properties() len_props = len(o2_props.keys()) len_coords = len(o2.coords.concrete_coords.keys()) m = 1.0/(1+len_props+len_coords) #print "Similarity Check:", self.id,self.props,self.coords.concrete_coords, o2.id, o2.props,o2.coords.concrete_coords if self.name != o2.name: similarity -= m if len_props == 0: if len(o_props.keys()) == 0: if coords_include: if len_coords > 0: similarity -= ((1-self.coords.get_similarity(o2.coords))*m*len_coords) return similarity if coords_include and len_coords > 0: m_p = 0.75*similarity/len_props sim = self.coords.get_similarity(o2.coords) weight = 0.25*(similarity-m) similarity = similarity - weight + (sim*weight) #print "Obs:", self.props,self.coords.concrete_coords, o2.props,o2.coords.concrete_coords, similarity, m_p #print "Similarity till corrds: ",sim, similarity elif len_props > 0: m_p = 0.9*similarity/len_props sim = self.coords.get_similarity(o2.coords) weight = 0.1*(similarity -m) similarity = similarity - weight + (sim*weight) #print "Similarity till Coords here:", similarity for p in o2_props.keys(): if o_props.has_key(p): if (type(o2_props[p]) == type(o_props[p]) == type(float())): p1 = o_props[p]; p2 = o2_props[p] diff = abs(o2_props[p] - o_props[p]) if bool(diff): similarity = similarity + ( (m_p/(2.0+diff)) - (m_p/2.0) ) continue elif (o2_props[p] != o_props[p]): similarity -= m_p/2.0 continue else: similarity -= m_p #similarity /= (1+total_mismtach) #print "Similarity obtained:", self.props, self.coords.get_coords(),o2.props, o2.coords.get_coords(), sim, similarity return similarity def to_string(self): """Returns observation as string to print""" builder = "" #builder += "%s, "%type(self).__name__ builder += "<observation ='%s' self_flag = '%r' "%(self.name, self.self_flag) prop = self.get_properties() for p in prop.keys(): builder += "%s: %s, "%(p,prop[p]) coords = self.coords.get_coords() for prop in coords.keys(): builder += "%s ='%s' "%(prop, coords[prop]) builder += "id= '%i' />\n"%self.id return builder def to_concrete_string(self): """Returns observation as string to print""" builder = "" #builder += "%s, "%type(self).__name__ builder += "<observation ='%s' self_flag = '%r' "%(self.name, self.self_flag) prop = self.get_concrete_properties() for p in prop.keys(): builder += "%s: %s, "%(p,prop[p]) coords = self.coords.get_concrete_coords() for prop in coords.keys(): builder += "%s ='%s' "%(prop, coords[prop]) builder += "id= '%i' />\n"%self.id #print "Concrete_to_string: Props,", prop," Coords", coords return builder def to_xml(self): """Returns observation in XML format""" #print "@o.to_xml type:", self.to_string() builder = "" #builder += "<observation type='%s' "%type(self).__name__ builder += "<observation type= '%s' name='%s' self_flag= '%r' "%(type(self).__name__, self.name, self.self_flag) properties = self.get_properties() for prop in properties.keys(): builder += "%s ='%s' "%(prop, properties[prop]) coords = self.coords.get_coords() for prop in coords.keys(): builder += "%s ='%s' "%(prop, coords[prop]) builder += "successes='%f' activations='%f' "%(self.successes, self.activations) builder += "id= '%i' />\n"%self.id #print "Observation successes: ", self.successes return builder def get_probability(self): """Returns probaility of observation New observation has probability of 1.0""" if (self.activations == 0.0): return 1.0 return self.successes/self.activations def parse_node(self, node): """Create elememts of the observation from XML format""" for child in node.iter(): for grand in child.attrib.keys(): try: value = float(child.attrib[grand]) except: try: value = int(child.attrib[grand]) except: try: value = str(child.attrib[grand]) except: value = bool(child.attrib[grand]) #print "Child, grand:",grand, child.attrib[grand], type(value) if (grand == "activations"): self.activations = float(value); continue elif (grand == "name"): self.name = str(value); continue elif (grand == "self_flag"): #print "@parse_node Self_flag:", value, bool(value), type(value) if value == "False": self.self_flag = False; continue else: self.self_flag = True elif (grand == "successes"): self.successes = float(value); continue elif (grand == "id"): self.id = int(value); continue elif (grand == "parent"): self.parentId = int(value); continue elif (grand != "type"): #print "@parse_node Grand at set: ", grand, value, type(value), type(value) == type(str())#, value[0] == '$' if type(value) == type(str()): if value[0] == '$': self.set_property_var(grand, value); continue else: self.set_concrete_var(grand, value); continue else: self.set_concrete_var(grand, value); continue #print "Parse_node: ", self.to_string(), self.self_flag def occurred(self, success): """Observation successes and activations are recorded""" #print "Observation occourences~: ", success, self.to_string(), self.activations, self.successes self.activations +=1 if success: self.successes +=1 #print "Observation occoured~: ", success, self.to_string(), self.activations, self.successes def instantiate_var(self, variable, value): """Instantiates the property (variable) with given value """ props = self.get_properties() coords = self.coords.get_coords() props.update(coords) #print "@intantiate_var Instantiating: ",props, self.coords.get_coords(), variable, value for p in props.keys(): if p != variable: continue try: p_val = float(props[p]) except: try: p_val = int(props[p]) except: p_val = str(props[p]) #print "Values to be instantiated:", p, props[p], p_val, type(p_val) #!= type(str()) and "$" in p_val, (p_val == variable and len(p_val)<3) (len(p_val)>2 and p == variable) if type(p_val) != type(str()) or not("$" in p_val): continue #print "$ sign found:", "$" in p_val, p_val #if not("$" in p_val): # continue if (not "-" in p_val) and (not "+" in p_val): #print "Setting concrete_values: ", p, value self.set_concrete_var(p, value) else:#elif(str(p_val) != str(variable) and len(p_val)>2): #print "Property with function to be changed:", p, p_val, value if type(value) != type(float()): return try: sym = p_val[p_val.index("-")] except: sym = p_val[p_val.index("+")] #sym = p_val[2] q = float(value); reply = None # s = "0%c"%p_val[3]; w = float(s) w = float(p_val[p_val.index(sym)+1:]) if (sym =='-'): reply = q-w else: reply = q+w ss = abs(reply) #print "setting concrete Value with function created: ",p, ss self.set_concrete_var(p, ss) def hash(self): """Create string of the Observation""" #print "@o_has:", self.get_concrete_properties() builder = "" builder +="%s"%str(self.name) builder +="%r"%str(self.self_flag) properties = self.get_properties() for prop in properties.keys(): builder += "%s%s, "%(prop, properties[prop]) return builder def is_generalised(self): """Returns True if any of the variable is generalised""" props = self.get_properties() #print "@is_generalised:", props for p in props.keys(): if("$" in str(props[p])): return True coords = self.coords.get_coords() #print "@is_generalised:", coords for p in coords.keys(): if("$" in str(coords[p])): return True return False
class Action(GObject.Object): #__metaclass__ = abc.ABCMeta __gsignals__ = { "abstract_signal" : (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ( GObject.TYPE_OBJECT,)) } def __init__(self): GObject.Object.__init__(self) self.props = {} self.props_var = {} self.name = None self.coords = Coordinates() def get_properties(self): """Get Dictionary containing propserties Variable value is returned if exists else concrete is returned""" props = {} for p in self.props.keys(): if self.props_var.has_key(p) and self.props_var[p] != None: props[p] = self.props_var[p] else: props[p] = self.props[p] return props def get_var_properties(self): """Returns variable properties of the observation""" props = {} for p in self.props_var.keys(): if self.props_var[p] != None: props[p] = self.props_var[p] else: props[p] = self.props[p] return props def get_concrete_properties(self): """Returns concrete properties, having concrete value not generalised""" props = {} for p in self.props.keys(): if self.props[p] != None: props[p] = self.props[p] else: props[p] = self.props_var[p] return props def equals(self, a2,ignore = False): """Returns True if two actions are equal""" if self.name != a2.name: return False props = self.get_concrete_properties(); props2 = a2.get_concrete_properties() for p2 in props2.keys(): if not(props.has_key(p2)): return False if (type(props[p2]) == type(props2[p2]) == type(float())): if abs(abs(props[p2]) - abs(props2[p2])) > 0: return False elif (props[p2] != props2[p2]): return False if ignore: return True if not self.coords.equals(a2.coords): return False return True def similar(self, a2): """Returns True if two actions have same name""" if a2.name != self.name: return False props = self.get_concrete_properties(); props2 = a2.get_concrete_properties() for p2 in props2.keys(): if not(props.has_key(p2)): return False if props[p2] != props2[p2]: return False #print "Observation equals: ", props, props2 return True def execute(self): """Execute action with abstract signal""" #print "Emitting action signal:", self.name, self.props,self.coords.concrete_coords self.emit("abstract_signal", self) def repeat(self): """Emit abstract signal""" self.emit("abstract_signal", self) print "Repeating abstract signal with parameters: ", self.props, self.coords.concrete_coords def set_concrete_prop(self, name, val): """Set value for the concrete property""" try: value = float(val) except: try: value = int(val) except: value = str(val) if name == "x" or name == "y": self.coords.set_concrete_coords(name, value) return self.props[name] = value #print "Setting in action: ", name, self.props[name], self.props_var[name] def set_property_var(self, name, val): """Set value for the variable properties""" try: value = float(val) except: try: value = int(val) except: value = str(val) #print "@set_priop_val:", name, value if name == "x" or name == "y": self.coords.set_variable_coords(name, value) return self.props_var[name] = value self.props[name] = None def copy(self): """Create copy of the action""" a2 = Action() a2.name = str(self.name) a2.props = self.props.copy() a2.props_var = self.props_var.copy() a2.coords = self.coords.copy() #a2.connect("abstract_signal") return a2 def to_string(self): """Returns action as string to print""" act = "<action type='%s' name='%s' "%(str(type(self).__name__), self.name) prop = self.get_properties() for p in prop.keys(): act += " %s= '%s' "%(p, prop[p]) coords = self.coords.get_coords() for prop in coords.keys(): act += "%s= '%s' "%(prop, coords[prop]) act += " /> \n" return act def to_concrete_string(self): """Returns action as string to print""" act = "<action type='%s' name='%s' "%(str(type(self).__name__), self.name) prop = self.get_concrete_properties() for p in prop.keys(): act += " %s= '%s' "%(p, prop[p]) coords = self.coords.get_concrete_coords() #print "Concrete Action:", self.get_concrete_properties(), self.coords.get_concrete_coords() for prop in coords.keys(): act += "%s= '%s' "%(prop, coords[prop]) act += " /> \n" return act def to_xml(self): """Returns action in XML format""" builder = "" builder += "<action name='%s' "%(self.name) #str(type(self).__name__), properties = self.get_properties() for prop in properties.keys(): builder += "%s='%s' "%(prop, properties[prop]) coords = self.coords.get_coords() for prop in coords.keys(): builder += "%s= '%s' "%(prop, coords[prop]) builder += " />\n" return builder def parse_node(self, node): """Create elememts of the action from XML format""" for k in node.attrib.keys(): value = node.attrib[k] if k == "type": continue if k == "name": self.name = str(value) elif k !="type": if type(value) == type(str()): if value[0] == '$': self.set_property_var(k, value); continue else: self.set_concrete_prop(k, value); continue else: self.set_concrete_prop(k, value); continue def instantiate_var(self, variable, value): """Instantiates the property (variable) with given value """ #print "@intantiate_var Instantiating: ",self.sensor_id, variable, value props = self.get_properties() coords = self.coords.get_coords() props.update(coords) #print "@intantiate_var Instantiating: ",props, self.coords.get_coords(), variable, value for p in props.keys(): if p != variable: continue try: p_val = float(props[p]) except: try: p_val = int(props[p]) except: p_val = str(props[p]) #print "Values to be instantiated:", p, props[p], p_val, type(p_val) #!= type(str()) and "$" in p_val, (p_val == variable and len(p_val)<3) (len(p_val)>2 and p == variable) if type(p_val) != type(str()) or not("$" in p_val): continue #print "$ sign found:", "$" in p_val, p_val #if not("$" in p_val): # continue if (not "-" in p_val) and (not "+" in p_val): #print "Setting concrete_values: ", p, value self.set_concrete_prop(p, value) else:#elif(str(p_val) != str(variable) and len(p_val)>2): #print "Property with function to be changed:", p, p_val, value if type(value) != type(float()): return try: sym = p_val[p_val.index("-")] except: sym = p_val[p_val.index("+")] #sym = p_val[2] q = float(value); reply = None # s = "0%c"%p_val[3]; w = float(s) w = float(p_val[p_val.index(sym)+1:]) if (sym =='-'): reply = q-w else: reply = q+w ss = abs(reply) #print "setting concrete Value with function created: ",p, ss self.set_concrete_prop(p, ss)
def __init__(self): GObject.Object.__init__(self) self.props = {} self.props_var = {} self.name = None self.coords = Coordinates()