def test_moves(self): coordinate = Coordinate((1,0,0)) moves = coordinate.moves() self.assertTrue(not moves.__contains__(coordinate)) self.assertEqual(len(moves), 4) self.assertTrue(moves.__contains__(Coordinate((0,1,0)))) self.assertTrue(moves.__contains__(Coordinate((0,-1,0))))
def __init__(self, pos, screen_dims): self.initial_pos = pos self.screen_dims = screen_dims self.displacement = Coordinate(pos, vel=Coordinate.get_empty_coord()) self.origin = Coordinate(Coordinate.get_empty_coord(), Coordinate.get_empty_coord()) self.displacement = Coordinate(Coordinate.get_empty_coord(), Coordinate.get_empty_coord()) self.pitch = math.pi / 2 self.yaw = math.pi / 2 self.facing = None self.up = None self.right = None self.screen_diagonal = math.sqrt(screen_dims[0] ** 2 + screen_dims[1] ** 2) / 2 self.field_of_view = math.pi / 3.0 self.projection_plane_distance = self.screen_diagonal / math.atan(self.field_of_view) self.get_direction_vectors() self.zoom_rate = 200 self.zoom_multiplier = 1.0 self.degrees_per_turn = 5 self.camera_is_moving = False self.initial_mouse_pos = None self.update_background = False self.key_mappings = { pygame.K_DOWN: self.look_down, pygame.K_UP: self.look_up, pygame.K_LEFT: self.look_left, pygame.K_RIGHT: self.look_right, pygame.K_a: self.strafe_left, pygame.K_d: self.strafe_right, pygame.K_w: self.move_forward, pygame.K_s: self.move_backward, pygame.K_z: self.move_up, pygame.K_x: self.move_down }
def generate_background_star_field(num_stars): star_list = [] for _ in range(num_stars): args = {"pos": Coordinate.get_random_coordinate(10000000.0), "vel": Coordinate.get_empty_coord(), "radius": random.randrange(1, 3)} star_list.append(args) return star_list
def calculate_coord_gui(self): c1 = [self.lat1.get(), self.long1.get()] c2 = [self.lat2.get(), self.long2.get()] coord1 = Coordinate(c1) coord2 = Coordinate(c2) distance=coord1.get_distance_between_coordinates(coord2) self.mtext.pack() str1 = "The distance between coordinates in km is " + str(distance)+'\n' self.mtext.insert(END,str1)
def calculate_airport_gui(self): c1 = [self.lat1a, self.long1a] c2 = [self.lat2a, self.long2a] coord1 = Coordinate(c1) coord2 = Coordinate(c2) distance=coord1.get_distance_between_coordinates(coord2) self.mtext.pack() str1 = "Distance between airports in km is " + str(distance)+'\n' self.mtext.insert(END,str1)
class CoordinateTestCase(unittest.TestCase): def setUp(self): self.coord_a = Coordinate((1,2,3)) self.coord_b = Coordinate((3,2,1)) def test_subtraction(self): result = self.coord_a.sub(self.coord_b) self.assertEqual(result, (-2,0,2)) self.assertEqual(type(result), Coordinate) def test_normalize(self): self.assertEqual(Coordinate((2,-3,0)).normalize(), (1,1,0)) def test_moves(self): coordinate = Coordinate((1,0,0)) moves = coordinate.moves() self.assertTrue(not moves.__contains__(coordinate)) self.assertEqual(len(moves), 4) self.assertTrue(moves.__contains__(Coordinate((0,1,0)))) self.assertTrue(moves.__contains__(Coordinate((0,-1,0)))) def test_negative_moves(self): coordinate = Coordinate((-1,0,0)) self.assertTrue(coordinate.moves().__contains__(Coordinate((0,1,0))))
def initialize_parameters(self): ''' We randomly assign values to our parameters. Currently, these parameters are completely random, but can be adjusted to account for some information learned from offline learning. param_pi[k] denotes probability of a datapoint being in cluster k param_mu[k] is the mean value of a coordinate in cluster k param_covariance[k] is the covariance matrix of a cluster k ''' self.param_pi = [] self.param_mu = [] self.param_covariance = [] self.old_pi = [] self.old_mu = [] self.old_covariance = [] for cluster in range(self.clusters): self.param_pi = [1./3,1./3,1./3] self.param_mu.append(Coordinate.get_random_coordinate(self.max_x, self.max_y)) self.param_covariance.append(Covariance.get_random_covariance(self.max_variance)) # Normalize pi values pi_sum = sum(self.param_pi) self.param_pi = map(lambda pi: pi / pi_sum, self.param_pi)
class CellTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testCoordinateCreated(self): self.coordinate = Coordinate() assert self.coordinate.set(1,2) == (1,2), 'Coordinate was created' assert self.coordinate.coordX == 1, 'Coordinate was created' assert self.coordinate.coordY == 2, 'Coordinate was created' def testCellCreated(self): coordinate = Coordinate(1,1) self.cell = Cell(coordinate) assert self.cell.exists() == False, 'Cell was not created' def testCellSetValue(self): coordinate = Coordinate(1,1) self.cell = Cell(coordinate) self.cell.setValue(True) assert self.cell.value == True, 'Cell has invalid value' def testGetNeigbours(self): myNeighbourListe = [(0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1), (2,2)] coordinate = Coordinate(1,1) self.cell = Cell(coordinate) generatedNeigbhourListe = self.cell.getNeighbours() assert generatedNeigbhourListe == myNeighbourListe, 'Cell has invalid value'
def __init__(self): # Used for axis indexing in ObjectCube. #axis_counter = 0 # Keep instance of a coordinate in memory. self.coordinate = Coordinate() # Default values for max image size, max image space and cluster index space. self.max_image_size = 10 self.max_image_space = 5 self.cluster_index_space = 0.2
def print_list_gui(self): self.clear_gui() name_string = " " for name in self.airport_names: name_string += name name_string += " " self.mtext.pack() self.mtext.insert(END,name_string+'\n') for index,value in enumerate(self.airport_names): coord1 = Coordinate(self.airport_coordinates[index]) self.mtext.insert(END,value) for index1, value1 in enumerate(self.airport_names): coord2 = Coordinate(self.airport_coordinates[index1]) distance = coord1.get_distance_between_coordinates(coord2) int_distance = int(distance) self.mtext.insert(END,"{:>7}".format(int_distance)) self.mtext.insert(END,'\n') self.mtext.insert(END,'\n')
def get_direction(self, view): ''' Given the current position it will return which direction will yield the highest probability of finding a plant ''' if len(self.data_points) < self.use_threshold: return random.choice(DIRECTIONS) current_pos = Coordinate(view.GetXPos(), view.GetYPos()) possible_directions= DIRECTIONS possible_coordinates = [] possible_coordinates.append(current_pos.right()) possible_coordinates.append(current_pos.left()) possible_coordinates.append(current_pos.up()) possible_coordinates.append(current_pos.down()) best_move = self.best_move(possible_coordinates) return possible_directions[best_move]
def point_towards_target(self, target_coord): Camera.log.debug("Facing target coordinate {}".format(target_coord.pos)) coord = Coordinate(self.origin.pos + self.displacement.pos, self.origin.vel + self.displacement.vel) distance, target_vector = Coordinate.get_distance_and_radius_vector(coord, target_coord) normalized_vector = target_vector / distance pitch = math.acos(Camera.clean_cos(normalized_vector[2])) yaw = math.acos(Camera.clean_cos(normalized_vector[0] / math.sin(pitch))) self.pitch = pitch self.yaw = yaw Camera.log.debug("New Pitch, Yaw = {}, {}".format(self.pitch, self.yaw)) self.get_direction_vectors() self.update_background = True
def draw_planets(self, surface, camera): log.info("Drawing planets") # build ordered list ordered_list = [] for p in self.planets: dist, _ = Coordinate.get_distance_and_radius_vector(camera.coord, p.coord) ordered_list.append((p, dist)) for p, d in sorted(ordered_list, key=lambda ele: ele[1], reverse=True): p.draw(surface, camera) if self.DRAW_SOI is True: p.draw_sphere_of_influence(surface, camera)
def __init__(self, **kwargs): self.args = kwargs self.name = kwargs["name"] self.coord = Coordinate(kwargs["pos"], kwargs["vel"]) self.mass = kwargs["mass"] self.color = kwargs["color"] self.border = 0 self.kinetic_energy = self.get_kinetic_energy() self.potential_energy = 0 self.radius = 0 self.get_radius(update=True) self.sphere_of_influence = 0 self.get_sphere_of_influence(update=True) self.trail = Trail(40, 1)
def get_apparent_radius_and_draw_pos(self, target_coord, target_radius): # If the target is not visible, return no radius and no position def not_visible(): return 0, None # Calculate the vector that points from the camera to the target coord = Coordinate(self.origin.pos + self.displacement.pos, self.origin.vel + self.displacement.vel) Camera.log.debug("Camera Pos: {} [m]; Target Pos: {} [m]".format(coord.pos, target_coord.pos)) distance, vector_to_coord = Coordinate.get_distance_and_radius_vector(coord, target_coord) Camera.log.debug("Distance: {} Radius: {}".format(distance, vector_to_coord)) # Calculate the component of the target vector that is parallel to the facing vector face_dot_radius = np.dot(self.facing, vector_to_coord) Camera.log.debug("Face.radius: {} [m**2]; distance: {} [m]".format(face_dot_radius, distance)) # If the facing vector dotted with the target vector is negative, # the target is behind the camera. Return to save time. if face_dot_radius < 0: return not_visible() # Calculate the apparent angular distance from the facing vector # to the target vector apparent_angle = math.acos(Camera.clean_cos(face_dot_radius / distance)) Camera.log.debug("Apparent angle away from center: {} [rad]".format(apparent_angle)) # Return if the target is outside the field of view if self.field_of_view < apparent_angle: return not_visible() # Calculate the apparent size of the target object Camera.log.debug("Target Radius: {} [m]".format(target_radius)) if target_radius < distance: apparent_solid_angle = math.asin((target_radius / distance)) else: apparent_solid_angle = math.pi / 3.0 # Determine the apparent size of the target object Camera.log.debug("Apparent Solid Angle: {} [rad]".format(apparent_solid_angle)) apparent_target_radius = (apparent_solid_angle / self.field_of_view) * self.screen_diagonal Camera.log.debug("Target's Screen Radius: {}".format(apparent_target_radius)) # If we've made it this far, calculate the position of the target vector_scale = self.projection_plane_distance / face_dot_radius projection = vector_scale * (vector_to_coord - ((face_dot_radius / distance) * self.facing)) x = (self.screen_dims[0] / 2) + np.dot(projection, self.right) y = (self.screen_dims[1] / 2) + np.dot(projection, self.up) return apparent_target_radius, np.round(np.array([x, y])).astype(int)
def update_distance_and_vectors_for_planets(self): """ builds a dict of radius vectors between planets of format: { (p1, p2): distance from p1 to p2, (p1, p3): distance from p1 to p3, ... (p3, p4): distance from p3 to p4, etc. } """ self.planet_distances = {} for a, b in itertools.combinations(self.planets, 2): dist, vect = Coordinate.get_distance_and_radius_vector(a.coord, b.coord) self.planet_distances[(a, b)] = (dist, vect)
def __init__(self, word, coord): """ Initializes a Move with the given string (only alphabetic characters) and coordinate. Coord can either be a Coordinate or a string, which will be converted to a Coordinate. Word is a string, following the rules of the class doc: lowercase means blank, parentheses mean already played. Example: PORt(MANTEaU)X """ tilelist = self.tiles_from_string(word) self.__all_tiles = tilelist[0] self.__just_played_tiles = tilelist[1] if isinstance(coord, str): self.__coord = Coordinate.initialize_from_string(coord) else: self.__coord = coord
neighbor, self.goal) heappush(self.oheap, (self.fscore[neighbor], neighbor)) return False def is_collision_with_dnfz(self, neighbor): for int_id, dnfz in self.dynamic_no_flight_zones.items(): if dnfz["geometry"] == "circle": coord = dnfz["coordinates"] coord = coord.split(',') dist = self.heuristic(neighbor, Coordinate(lon=coord[0], lat=coord[1])) if (dnfz["valid_from_epoch"] - self.safety_extra_time) < neighbor.time < ( dnfz["valid_to_epoch"] + self.safety_extra_time): if dist <= (coord[2] + self.safety_dist_to_dnfz): return True elif dnfz["geometry"] == "polygon": dist = dnfz["polygon"].distance( geometry.Point(neighbor.easting, neighbor.northing)) if (dnfz["valid_from_epoch"] - self.safety_extra_time) < neighbor.time < ( dnfz["valid_to_epoch"] + self.safety_extra_time): if dist <= self.safety_dist_to_dnfz: return True return False if __name__ == "__main__": start_pos = Coordinate(lat=55.481202, lon=10.344599) goal_pos = Coordinate(lat=55.479860, lon=10.340543)
def createCoordinate(x, y): coordinate = Coordinate() coordinate.X = x coordinate.Y = y return coordinate
def __init__(self, name, latitude, longitude): Coordinate.__init__(self, latitude, longitude) self.name = name
def get_distance_to_other_body(self, other): dist, vect = Coordinate.get_distance_and_radius_vector(self.coord, other.coord) return dist, vect
def compute_astar(self, dynamic=False, ground_speed=5): self.clear_dicts_and_lists() while self.oheap: current = heappop(self.oheap)[1] if self.goal_dist_thresh >= self.heuristic(current, self.goal): data = [] while current in self.came_from: coord = Coordinate(easting=current.easting, northing=current.northing) data.append(coord) current = self.came_from[current] return data current_set = (current.easting, current.northing) self.close_set.add(current_set) for i, j in self.neighbors: if dynamic: new_time = current.time + (self.heuristic( current, TimeCoord(easting=current.easting + i, northing=current.northing + j)) / ground_speed) neighbor = TimeCoord(easting=current.easting + i, northing=current.northing + j, time=new_time) else: neighbor = TimeCoord(easting=current.easting + i, northing=current.northing + j) tentative_g_score = self.gscore[current_set] + self.heuristic( current, neighbor) neighbor_transform = ( int((neighbor.easting - self.lower_left.easting) / self.map_res), int((neighbor.northing - self.lower_left.northing) / self.map_res)) if self.map_image[neighbor_transform[1]][ neighbor_transform[0]] != 0: continue if dynamic and self.is_collision_with_dnfz(neighbor): continue neighbor_set = (neighbor.easting, neighbor.northing) if neighbor_set in self.close_set and tentative_g_score >= self.gscore.get( neighbor_set, 0): continue if tentative_g_score < self.gscore.get( neighbor_set, 0) or neighbor_set not in [ i[1] for i in self.oheap ]: self.came_from[neighbor_set] = current_set self.gscore[neighbor_set] = tentative_g_score self.fscore[ neighbor_set] = tentative_g_score + self.heuristic( neighbor, self.goal) heappush(self.oheap, (self.fscore[neighbor_set], neighbor_set)) return False
def test_last_coordinate(self): self.assertEqual(self.valid_position.last_coordinate(), Coordinate((1, 1, 0)))
def up_coord_func(coord): return Coordinate(coord.x, coord.y - 1)
def shell_function(airport_names, airport_coordinates, airport_codes): #The following while loop will let the user select to print out the list of airports #Calculate the distance between two coordinates #Calculate the distance between two airports based on their codes #Coordinates from here on will be objects (Coordinate type) instead of lists #For each set of coordinates there will be an object #These objects will use their own instance methods to calculate the distance #between themselves and another cooordinate object user = '******' while user != 'q': print("Select one of these options", "p - print airport distance table",\ "c - distance between two coordinates",\ "l - to enter two airport codes and calculate them using lists",\ "a - to enter two airport codes to find the distance", \ "q - quit",sep='\n') user = input("Enter option: ") print() if user == 'p': #user selects print list coord=Coordinate() #Create coordinate object coord.print_airport_distances(airport_names, airport_coordinates) #this method will print the distances elif user == 'c': #user selects coordinates coord1 = Coordinate([29,20]) #Give default values print("The first set of coordinates") coord1.setCoordinates() coord2 = Coordinate([30,39]) #Give default values or else it will create reference to coord1 print("The second set of coordinates") coord2.setCoordinates() distance=coord1.get_distance_between_coordinates(coord2) print("The distance between the coordinates in km is", distance, end='\n') elif user == 'l': #user selects airport distances using lists error = True while error: try: code_one = input("Enter the first airport code: ") code_two = input("Enter the second airport code: ") code_one_index = airport_names.index(code_one) code_two_index = airport_names.index(code_two) coords_one = Coordinate(airport_coordinates[code_one_index]) coords_two = Coordinate(airport_coordinates[code_two_index]) error = False except ValueError: print() print("Error enter valid airport codes") print() error = True distance = coords_one.get_distance_between_coordinates(coords_two) print("The distance between the two airports using list is: ", distance) elif user == 'a': #user selects airport distances error = True while error: #while there is an error with the input keep asking for valid airport codes try: #Try this code code_one = input("Enter the code of the first airport: ") code_two = input("Enter the code of the second airport: ") print() coord1=Coordinate(airport_codes[code_one]) coord2=Coordinate(airport_codes[code_two]) distance = coord1.get_distance_between_coordinates(coord2) error = False except KeyError: #If there is a keyerror (dictionary does not conatin this key) print error message and ask for valid input print() print("You entered a code incorrectly! Prepare for a nuclear strike!!!") print() error = True print("The distance between the two airports in km is", distance, end='\n\n') elif user == 'q': print("Goodbye") else: print("Enter valid character") print("end")
def test_negative_moves(self): coordinate = Coordinate((-1,0,0)) self.assertTrue(coordinate.moves().__contains__(Coordinate((0,1,0))))
class CubeService: """ This class is used operate as a service for a singleton instance that is accessible to other parts. """ def __init__(self): # Used for axis indexing in ObjectCube. #axis_counter = 0 # Keep instance of a coordinate in memory. self.coordinate = Coordinate() # Default values for max image size, max image space and cluster index space. self.max_image_size = 10 self.max_image_space = 5 self.cluster_index_space = 0.2 def get_max_image_size(self): return self.max_image_size def set_max_image_size(self, size): self.max_image_size = size def get_max_image_space(self): return self.max_image_space def set_max_image_space(self, size): self.max_image_space = size def get_cluster_stack_space(self): return self.cluster_index_space def view_on_x(self, dim): if dim is None: self.coordinate.set_x( None ) elif type(dim) == ObjectCubePython.NumericalTagSet or type(dim) == ObjectCubePython.AlphanumericalTagSet or type(dim) == ObjectCubePython.DateTagSet or type(dim) == ObjectCubePython.TimeTagSet: x_ax = browser.cube.axis.AxisTagset( dim, axis=X_AXIS) self.coordinate.set_x( x_ax ) elif type(dim) == ObjectCubePython.PersistentDimension: x_ax = browser.cube.axis.AxisHierarchy( dim, axis=X_AXIS ) self.coordinate.set_x( x_ax ) else: print 'typewas', type(dim) raise Exception('Viewving unknown dimension on X: ' + dim.__str__()) def view_on_y(self, dim): if dim is None: self.coordinate.set_y( None ) elif type(dim) == ObjectCubePython.PersistentDimension: y_ax = browser.cube.axis.AxisHierarchy( dim, axis = Y_AXIS ) self.coordinate.set_y( y_ax ) else: y_ax = browser.cube.axis.AxisTagset( dim, axis = Y_AXIS ) self.coordinate.set_y( y_ax ) def view_on_z(self, dim): if dim is None: self.coordinate.set_z( None ) elif type(dim) == ObjectCubePython.PersistentDimension: z_ax = browser.cube.axis.AxisHierarchy( dim, axis=Z_AXIS ) self.coordinate.set_z( z_ax ) else: z_ax = browser.cube.axis.AxisTagset( dim, axis=Z_AXIS ) # If there is something on x, we must remove it... self.coordinate.set_z( z_ax ) def get_x(self): return self.coordinate.x def get_y(self): return self.coordinate.y def get_z(self): return self.coordinate.z def getCurrentCube(self): return self.coordinate.cube def draw(self): self.dlg = TextDialog(title="CardMode", message="Constructing cube, please wait") self.dlg.draw() # Force repaint for showing the dialog before the images. base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() # Let the coordinate construct new cube. # NOTE: Should this be self.drawing_area instead of coordinate if self.coordinate.x is None and self.coordinate.y is None and self.coordinate.z is None: # we need to clear all filters!!! filterManager.clear(True) messenger.send(CUBE_MENU_RELOAD_FILTERS) self.dlg.Close() return else: self.coordinate.constructCube() # Draw the cord. self.coordinate.draw() # Reload the filter list messenger.send(CUBE_MENU_RELOAD_FILTERS) self.dlg.Close() def reload(self): self.draw()
def setUp(self): self.coord_a = Coordinate((1,2,3)) self.coord_b = Coordinate((3,2,1))
def __init__(self, start: Coordinate = Coordinate(), end: Coordinate = Coordinate()): self.start, self.end = Coordinate.getOrderedList(start, end)
def hill_climb(self, function_to_optimize,step_size,xmin,xmax,ymin,ymax,startx=None,starty=None): if startx == None: startx=xmin if starty == None: starty=ymin currX = startx currY = starty currValue = function_to_optimize(currX,currY) coord = Coordinate(currX,currY,currValue) searching = True while searching: searching = False xPos = currX + step_size #Attempt to increase X by the step if xPos <= xmax: newVal = function_to_optimize(xPos,currY) if newVal < currValue: self.print_flag("CLIMBING BY INC. X "+str(xPos),self.HILL_PROGRESS) currValue = newVal currX = xPos searching = True xNeg = currX - step_size #Attempt instead to decrease X by the step if xNeg >= xmin: newVal = function_to_optimize(xNeg,currY) if newVal < currValue: self.print_flag("CLIMBING BY DEC. X "+str(xNeg),self.HILL_PROGRESS) currValue = newVal currX = xNeg searching = True yPos = currY + step_size #Attempt to increase Y by the step if yPos <= ymax: newVal = function_to_optimize(currX,yPos) if newVal < currValue: self.print_flag("CLIMBING BY INC. Y",self.HILL_PROGRESS) currValue = newVal currY = yPos searching = True yNeg = currY - step_size #Attempt to decrease Y by the step if yNeg >= ymin: newVal = function_to_optimize(currX,yNeg) if newVal < currValue: self.print_flag("CLIMBING BY DEC. Y "+str(yNeg),self.HILL_PROGRESS) currValue = newVal currY = yNeg searching = True coord.addX(currX) coord.addY(currY) coord.addZ(currValue) coord.setX(currX) coord.setY(currY) coord.setValue(currValue) self.print_flag("MIN FOUND X:"+str(currX)+" Y:"+str(currY)+" VALUE:"+str(currValue)+"\n",self.HILL) return coord
def __init__(self): self._structure = [] self._avg_structure = Structure(None, None) self._weakness = Coordinate(None, None, None) self.tersingkap = None
def mainfunc(): # option parser (see http://docs.python.org/library/optparse.html) usage = "%prog [options] --lon LONGITUDE --lat LATITUDE --alt ALTITUDE [--fov FOV | --fovx FOVx --fovy FOVy]" parser = OptionParser(usage=usage, version="%prog "+__VERSION__) parser.add_option("--lon", "--longitude", dest="lon", help="REQUIRED. Geographic coordinate for the Longitude.") parser.add_option("--lat", "--latitude", dest="lat", help="REQUIRED. Geographic coordinate for the Latitude.") parser.add_option("--alt", "--altitude", dest="alt", help="REQUIRED. Altitude from the earth.") parser.add_option("--fov", dest="fov", help="REQUIRED. Field of view. 0 < fov < 180 degrees; 0 < fov < %s radians." % math.pi) parser.add_option("--fovx", dest="fovx", help="If FOV is not passed in, this is REQUIRED. Field of view in X. 0 < fov < 180 degrees; 0 < fov < %s radians." % math.pi) parser.add_option("--fovy", dest="fovy", help="If FOV is not passed in, this is REQUIRED. Field of view in Y. 0 < fov < 180 degrees; 0 < fov < %s radians." % math.pi) parser.add_option("--azi", "--azimuth", dest="azimuth", help="The angle of the azimuth off North, in degrees or radians (per the -a flag) Default is 0. 0 <= azimuth <= 360.0 degrees; 0 <= azimuth <= %s radians." % (2*math.pi)) parser.add_option("-o", "--output", dest="output", help="[dd (default) | dms] -- dd is decimal degrees ([-]123.1234); dms is degrees-minutes-seconds (11d 22m 33.333s [NSEW]).") parser.add_option("-u", "--units", dest="units", help="[m (default) | km | ft | mi] -- Units of altitude. m is meters; km is kilometers; ft is feet; mi is miles.") parser.add_option("-a", "--angle", dest="angle", help="[d (default) | r] -- Units of the field of view angle. d is degrees; r is radians.") (options, args) = parser.parse_args() # Parse arguments if options.lon == None: parser.error("Must pass in the --lon option.") if options.lat == None: parser.error("Must pass in the --lat option.") if options.alt == None: parser.error("Must pass in the --alt option.") if options.fovx != None and options.fovy == None: parser.error("Must pass in the --fovy option.") if options.fovy != None and options.fovx == None: parser.error("Must pass in the --fovx option.") if options.fov == None and not (options.fovx != None and options.fovy != None): parser.error("Must pass in the --fov option.") lon = Coordinate(options.lon, "Lon") lat = Coordinate(options.lat, "Lat") if not lon.isValid(): parser.error("Invalid longitudinal coordinate: %s" % lon.getCoord()) if not lat.isValid(): parser.error("Invalid latitudinal coordinate: %s" % lat.getCoord()) # Center point cp = Point(options.lon, options.lat) try: alt = float(options.alt) except: parser.error("Invalid altitude: %s. Altitude must be a number." % options.alt) if options.fov == None: try: fov_x = float(options.fovx) except: parser.error("Invalid field of view in X: %s. Field of view must be a number." % options.fovx) try: fov_y = float(options.fovy) except: parser.error("Invalid field of view in Y: %s. Field of view must be a number." % options.fovy) else: try: fov_x = float(options.fov) fov_y = float(options.fov) options.fovx = options.fov options.fovy = options.fov except: parser.error("Invalid field of view: %s. Field of view must be a number." % options.fov) if not options.output: options.output = 'dd' if options.output.lower() not in ['dd', 'dms']: parser.error("Invalid option for input: %s" % options.input) if not options.units: options.units = 'm' if options.units.lower() not in ['m', 'km', 'ft', 'mi']: parser.error("Invalid option for units: %s" % options.units) if not options.angle: options.angle = 'd' if options.angle.lower() not in ['d', 'r']: parser.error("Invalid option for angle: %s" % options.angle) if not options.azimuth: options.azimuth = "0" try: options.azimuth = float(options.azimuth) except: parser.error("Invalid option for azimuth: %s" % options.azimuth) if options.angle == 'd': if options.azimuth < 0 or options.azimuth > 360.0: parser.error("Invalid option for azimuth: %s. Azimuth must be between 0 and 360.0 degrees." % options.azimuth) elif options.angle == 'r': if options.azimuth < 0 or options.azimuth > 2*math.pi: parser.error("Invalid option for azimuth: %s. Azimuth must be betweeen 0 and %s radians." % (options.azimuth, 2*math.pi)) options.output = options.output.lower() options.units = options.units.lower() options.angle = options.angle.lower() if alt < 0: parser.error("Invalid altitude: %s. Altitude cannot be negative." % alt) if fov_x <= 0: parser.error("Invalid field of view in X: %s. Field of view cannot be negative or zero." % fov_x) if options.angle == 'd' and fov_x >= 180.0: parser.error("Invalid field of view in X: %s. Field of view must be less than 180.0" % fov_x) if options.angle == 'r' and fov_x >= math.pi: parser.error("Invalid field of view in X: %s. Field of view must be lass than %s" % (fov_x, math.pi)) if fov_y <= 0: parser.error("Invalid field of view in Y: %s. Field of view cannot be negative or zero." % fov_y) if options.angle == 'd' and fov_y >= 180.0: parser.error("Invalid field of view in Y: %s. Field of view must be less than 180.0" % fov_y) if options.angle == 'r' and fov_y >= math.pi: parser.error("Invalid field of view in Y: %s. Field of view must be lass than %s" % (fov_y, math.pi)) if cp.x < -180.0 or cp.x > 180.0: parser.error("Invalid longitudinal coordinate: %s. Longitude must be between -180.0 and 180.0 degrees." % cp.x) if cp.y < -90.0 or cp.y > 90.0: parser.error("Invalid latitudinal coordinate: %s. Latitude must be between -90.0 and 90.0 degrees." % cp.y) if options.angle == 'r': options.azimuth = options.azimuth * RAD2DEG debug(options) if options.angle == 'd': fov_x = fov_x * DEG2RAD fov_y = fov_y * DEG2RAD debug("fov_x in radians is %s, fov_y in radians is %s" % (fov_x, fov_y)) xhalf = fov_x/2.0 yhalf = fov_y/2.0 debug("fov_x half is %s radians, fov_y half is %s radians" % (xhalf, yhalf)) # Calculate the top and bottom edge of the viewing angle, d_vert is in the # `alt' units. d_vert = alt * math.tan( yhalf ) # Calculate the left and right edge of the viewing angle d_horiz = alt * math.tan( xhalf ) debug("d vert: %s" % d_vert) debug("d horiz: %s" % d_horiz) # Calculate corner distance dist = math.sqrt( d_vert * d_vert + d_horiz * d_horiz ) # upper plane (only use the y value) upper = cp.geoWaypoint(d_vert, 0.0, options.units) debug("Upper is: %s" % (upper)) # lower plane (only use the y value) lower = cp.geoWaypoint(d_vert, 180.0, options.units) debug("Lower is: %s" % (lower)) # left plane (only use the x value) left = cp.geoWaypoint(d_horiz, 270.0, options.units) debug("Left is: %s" % (left)) # right plane (only use the x value) right = cp.geoWaypoint(d_horiz, 90.0, options.units) debug("Right is: %s" % (right)) # upper left point ul = Point(left.x, upper.y) # upper right point ur = Point(right.x, upper.y) # lower right point lr = Point(right.x, lower.y) # lower left point ll = Point(left.x, lower.y) debug("UL\t%s\t%s" % (ul.x, ul.y)) debug("LL\t%s\t%s" % (ll.x, ll.y)) debug("UR\t%s\t%s" % (ur.x, ur.y)) debug("LR\t%s\t%s" % (lr.x, lr.y)) debug("CP\t%s\t%s" % (cp.x, cp.y)) ul = ul.rotate(cp, options.azimuth) ur = ur.rotate(cp, options.azimuth) lr = lr.rotate(cp, options.azimuth) ll = ll.rotate(cp, options.azimuth) debug("Rotated:") print "CP\t%13.8f\t%13.8f" % (cp.x, cp.y) print "UL\t%13.8f\t%13.8f" % (ul.x, ul.y) print "LL\t%13.8f\t%13.8f" % (ll.x, ll.y) print "UR\t%13.8f\t%13.8f" % (ur.x, ur.y) print "LR\t%13.8f\t%13.8f" % (lr.x, lr.y) print "DW\t%13.8f %s" % (d_horiz*2, 'm') print "DH\t%13.8f %s" % (d_vert*2, 'm') debug("Azimuth: %s" % options.azimuth) debug("Distance: %s %s" % (dist, options.units)) debug("Upper left distance from center point: %s %s" % (cp.geoDistanceTo(ul, options.units), options.units)) debug("Vertical viewing distance: %s %s" % (cp.geoDistanceTo(upper, options.units) * 2, options.units)) debug("Horizontal viewing distance: %s %s" % (cp.geoDistanceTo(left, options.units) * 2, options.units)) return 0
def set_weakness(self, x, y, z): self._weakness = Coordinate(x, y, z)
class Planet(object): """ Base class for all large objects with gravitational mass! """ @classmethod def handle_collision(cls, a, b): if a.mass <= b.mass: b.collide(a) return a else: a.collide(b) return b @classmethod def get_collision_distance(cls, a, b): return a.get_radius() + b.get_radius() def __init__(self, **kwargs): self.args = kwargs self.name = kwargs["name"] self.coord = Coordinate(kwargs["pos"], kwargs["vel"]) self.mass = kwargs["mass"] self.color = kwargs["color"] self.border = 0 self.kinetic_energy = self.get_kinetic_energy() self.potential_energy = 0 self.radius = 0 self.get_radius(update=True) self.sphere_of_influence = 0 self.get_sphere_of_influence(update=True) self.trail = Trail(40, 1) def get_distance_to_other_body(self, other): dist, vect = Coordinate.get_distance_and_radius_vector(self.coord, other.coord) return dist, vect def get_kinetic_energy(self): return 0.5 * self.mass * self.coord.get_speed() ** 2 def get_potential_energy(self): return self.potential_energy def get_momentum(self): return self.mass * self.coord.vel def get_sphere_of_influence(self, update=False): if update is True: self.sphere_of_influence = (np.math.e ** 1) * np.math.sqrt(self.mass) return self.sphere_of_influence def get_radius(self, update=False): if update is True: self.radius = 2.0 * self.mass ** (1.0/3.0) return self.radius def collide(self, planet): self.coord.vel = (self.get_momentum() + planet.get_momentum())/(self.mass + planet.mass) self.mass += planet.mass self.get_radius(update=True) self.get_sphere_of_influence(update=True) def check_if_visible(self, apparent_radius): if apparent_radius < 1: return False else: return True def clear_planet_trail(self): self.trail.clear_trail() def draw(self, surface, camera): r, pos = camera.get_apparent_radius_and_draw_pos(self.coord, self.get_radius()) if self.check_if_visible(r) is False: log.debug("Planet {} is too small to draw at this scale.".format(self.name)) return False elif pos is not None: self.trail.add_position_and_radius_to_trail(pos, r) log.debug("Drawing circle: coord={}; radius={}; border={}".format(self.coord.pos, self.get_radius(), self.border)) pygame.draw.circle(surface, self.color, pos, np.round(r).astype(int), self.border) trail = self.trail.get_position_and_radius_trail() if trail is not None: plist, _ = zip(*self.trail.get_position_and_radius_trail()) pygame.draw.lines(surface, self.color, False, plist, 1) return True def draw_sphere_of_influence(self, surface, camera): r, pos = camera.get_apparent_radius_and_draw_pos(self.coord, self.get_sphere_of_influence()) if self.check_if_visible(r) is True and pos is not None: pygame.draw.circle(surface, self.color, pos, np.round(r).astype(int), 1)
import math from mathUtil import MathUtil from coordinate import Coordinate from TownListHandler import TownListHandler #TODO: Clean this up and make a function that takes a string and returns a Coordinate currentLocationInput = input("Please enter your current location, in X,Z format (Example: 230,134): ") currentLocationList = currentLocationInput.split(",", 1) currentLocationCoordinate = Coordinate(currentLocationList[0], currentLocationList[1]) currentLocationCoordinate.printCoordinate() targetInput = input("Please enter your target location, in X,Z format (Example: 230,134): ") targetCoordinateList = targetInput.split(",", 1) targetCoordinate = Coordinate(targetCoordinateList[0], targetCoordinateList[1]) targetCoordinate.printCoordinate() #TODO: Move this to it's own class? Just have it return a Coordinate perhaps? while (True): bendingInput = input("\nWhat type of bending do you use? Valid choices are air, water, fire, earth: ") bendingInput = bendingInput.upper() if bendingInput == "FIRE": capitalCoordinate = Coordinate(3950, 9760) break; elif bendingInput == "AIR": capitalCoordinate = Coordinate(10820, 15010) break; elif bendingInput == "WATER": capitalCoordinate = Coordinate(13300, 2030) break; elif bendingInput == "EARTH":
def simulated_annealing(self,function_to_optimize, step_size, max_temp, xmin, xmax, ymin, ymax, startx=None, starty=None): if startx == None: startx=xmin if starty == None: starty=ymin currX = startx currY = starty temp = max_temp currValue = function_to_optimize(currX,currY) searching = True coord = Coordinate(currX,currY,currValue) while searching: progressed = False searching = False xPos = currX + step_size #Attempt to increase X by the step if xPos <= xmax: temp -= self.TEMP_DECREASE newVal = function_to_optimize(xPos,currY) xTemp = self.temp_function(temp,newVal,currValue) if newVal < currValue or xTemp: self.print_flag("CLIMBING BY INC. X "+str(xPos),self.SA_PROGRESS) if xTemp: xPos += step_size currValue = newVal currX = xPos searching = True progressed = True xNeg = currX - step_size #Attempt instead to decrease X by the step if xNeg >= xmin: temp -= self.TEMP_DECREASE newVal = function_to_optimize(xNeg,currY) xTemp = self.temp_function(temp,newVal,currValue) if newVal < currValue: self.print_flag("CLIMBING BY DEC. X "+str(xNeg),self.SA_PROGRESS) currValue = newVal currX = xNeg searching = True progressed = True yPos = currY + step_size #Attempt to increase Y by the step if yPos <= ymax: temp -= self.TEMP_DECREASE newVal = function_to_optimize(currX,yPos) yTemp = self.temp_function(temp,newVal,currValue) if newVal < currValue or yTemp: self.print_flag("CLIMBING BY INC. Y",self.SA_PROGRESS) if yTemp: yPos += step_size currValue = newVal currY = yPos searching = True progressed = True yNeg = currY - step_size #Attempt to decrease Y by the step if yNeg >= ymin: temp -= self.TEMP_DECREASE newVal = function_to_optimize(currX,yNeg) yTemp = self.temp_function(temp,newVal,currValue) if newVal < currValue: self.print_flag("CLIMBING BY DEC. Y",self.SA_PROGRESS) currValue = newVal currY = yNeg searching = True progressed = True #If we don't go anywhere, don't add the same coordinates twice if progressed: coord.addX(currX) coord.addY(currY) coord.addZ(currValue) coord.setX(currX) coord.setY(currY) coord.setValue(currValue) self.print_flag("MIN FOUND X:"+str(currX)+" Y:"+str(currY)+" VALUE:"+str(currValue)+"\n",self.SA) return coord
def testCoordinateCreated(self): self.coordinate = Coordinate() assert self.coordinate.set(1,2) == (1,2), 'Coordinate was created' assert self.coordinate.coordX == 1, 'Coordinate was created' assert self.coordinate.coordY == 2, 'Coordinate was created'
def test_flood_indices(self): grid = [ [empty_color, defined_color, defined_color], [defined_color, empty_color, empty_color], [defined_color, defined_color, defined_color], ] instance = Board.from_grid(grid) self.assertEqual( instance.flood_indices(Coordinate(0, 0)), {Coordinate(0, 0)}, ) self.assertEqual( instance.flood_indices(Coordinate(0, 1)), {Coordinate(0, 1), Coordinate(0, 2)}, ) self.assertEqual( instance.flood_indices(Coordinate(1, 0)), {Coordinate(1, 0), Coordinate(2, 0), Coordinate(2, 1), Coordinate(2, 2)}, ) self.assertEqual( instance.flood_indices(Coordinate(2, 1)), {Coordinate(1, 0), Coordinate(2, 0), Coordinate(2, 1), Coordinate(2, 2)}, )