def vincentyDis(self): origin = geopy.Point(self.lat, self.lon) # left: 270 left_destination = VincentyDistance(kilometers=self.dist_left_x) \ .destination(origin, 270) # up: 0 up_destination = VincentyDistance(kilometers=self.dist_up_y) \ .destination(origin, 0) # right: 90 right_destination = VincentyDistance(kilometers=self.dist_right_x) \ .destination(origin, 90) # down: 180 down_destination = VincentyDistance(kilometers=self.dist_down_y) \ .destination(origin, 180) left_lon = left_destination.longitude up_lat = up_destination.latitude right_lon = right_destination.longitude down_lat = down_destination.latitude upleft = ','.join((str(up_lat), str(left_lon))) downright = ','.join((str(down_lat), str(right_lon))) return upleft, downright
def get_circle_centers(b1, b2, radius): """ the function covers the area within the bounds with circles :param b1: south-west bounds [lat, lng] :param b2: north-east bounds [lat, lng] :param radius: specified radius, adapt for high density areas :return: list of circle centers that cover the area between lower/upper """ sw = Point(b1) ne = Point(b2) # north/east distances dist_lat = vincenty(Point(sw[0], sw[1]), Point(ne[0], sw[1])).meters dist_lng = vincenty(Point(sw[0], sw[1]), Point(sw[0], ne[1])).meters circles = cover_rect_with_cicles(dist_lat, dist_lng, radius) cords = [ VincentyDistance(meters=c[0]).destination( VincentyDistance(meters=c[1]).destination(point=sw, bearing=90), bearing=0)[:2] for c in circles ] return cords
def getCellB(self, x, y): ang90 = 90 ang0 = 0 # calculus of the X coordinate # dx = distance on x edge if x > 0: dx = self.s * x origin = geopy.Point(self.blLoc) destination = VincentyDistance(kilometers=dx).destination( origin, ang0) lata = destination.latitude elif x == 0: lata = self.blLoc[0] # calculus of the Y coordinate # dy = distance on y edge if y > 0: dy = self.s * y origin = geopy.Point(self.blLoc) destination = VincentyDistance(kilometers=dy).destination( origin, ang90) lona = destination.longitude elif y == 0: lona = self.blLoc[1] return (lata, lona)
def GetCircleBound(center): # lat, lon circle = [] last_val = 0 shutdown = 0 add_val = step_latlon difference = 0 while shutdown == 0: # lon dis = VincentyDistance(center, (center[0], center[1]+add_val)).km if dis >= RADIUS: difference = add_val shutdown = 1 add_val += step_latlon bound_lat = (center[0]-difference, center[0]+difference) bound_lon = (center[1]-difference, center[1]+difference) bound_lat = np.arange(bound_lat[0], bound_lat[1], step_ten_meter) bound_lon = np.arange(bound_lon[0], bound_lon[1], step_ten_meter) #print bound_lat #print bound_lon for lat in bound_lat: for lon in bound_lon: if VincentyDistance(center, (lat,lon)).km <= RADIUS: latlon = [lat,lon] circle.append(latlon) circle = np.array(circle) return circle
def generate_4_coordinates(): global center_lat, center_lon, iteration, flag origin = geopy.Point(center_lat, center_lon) destination1 = VincentyDistance(meters=4.94974746831).destination( origin, 315) lat1, lon1 = destination1.latitude, destination1.longitude destination2 = VincentyDistance(meters=4.94974746831).destination( origin, 45) lat2, lon2 = destination2.latitude, destination2.longitude destination3 = VincentyDistance(meters=4.94974746831).destination( origin, 135) lat3, lon3 = destination3.latitude, destination3.longitude destination4 = VincentyDistance(meters=4.94974746831).destination( origin, 225) lat4, lon4 = destination4.latitude, destination4.longitude origin_c1 = geopy.Point(lat1, lon1) origin_c2 = geopy.Point(lat2, lon2) origin_c3 = geopy.Point(lat3, lon3) origin_c4 = geopy.Point(lat4, lon4) hex_coordinates_c1(origin_c1) hex_coordinates_c2(origin_c2) hex_coordinates_c3(origin_c3) hex_coordinates_c4(origin_c4) for iteration in range(0, 18): #rotate_360() correct_heading(array_of_waypoints[iteration][0], array_of_waypoints[iteration][1]) flag = 0
def make_box(self,nLat,sLat,eLon,wLon,di): nwCorner = VincentyDistance(kilometers = di).destination(geopy.Point(nLat,wLon),-45) swCorner = VincentyDistance(kilometers = di).destination(geopy.Point(sLat,wLon),-135) seCorner = VincentyDistance(kilometers = di).destination(geopy.Point(sLat,eLon),135) neCorner = VincentyDistance(kilometers = di).destination(geopy.Point(nLat,eLon),45) return path.Path([(nwCorner.latitude, nwCorner.longitude),(swCorner.latitude, swCorner.longitude), \ (seCorner.latitude, seCorner.longitude), (neCorner.latitude, neCorner.longitude)])
def calc_azimuth(self, from_crestnode_index, to_crestnode_index): # convenience function to calculate the azimuth between two crestnodes # note: this has to be done with rather elaborate vincenty distance # calculations as latitude and longitude are not equal measures # Get the locations as lon, lat, z lon_A, lat_A, z_A = self.crestnodes[ from_crestnode_index].geom.GetPoint() lon_B, lat_B, z_B = self.crestnodes[to_crestnode_index].geom.GetPoint() # Calculate A to B azimuth by setting a fake point to calc x and y fakepoint = Point(longitude=lon_A, latitude=lat_B) realpoint_A = Point(longitude=lon_A, latitude=lat_A) realpoint_B = Point(longitude=lon_B, latitude=lat_B) distance_x = VincentyDistance(fakepoint, realpoint_B).m distance_y = VincentyDistance(fakepoint, realpoint_A).m # correct distances with positive and negative signs if (lon_B - lon_A) < 0.0: distance_x = -1.0 * distance_x if (lat_B - lat_A) < 0.0: distance_y = -1.0 * distance_y azimuth = math.atan2(distance_x, distance_y) azimuth = math.degrees(azimuth) # correct azimuths to 0-360 scale if azimuth < 0.0: azimuth = azimuth + 360.0 return azimuth
def get_circle_centers(b1, b2, radius): """ the function covers the area within the bounds with circles this is done by calculating the lat/lng distances and the number of circles needed to fill the area as these circles only intersect at one point, an additional grid with a (+radius,+radius) offset is used to cover the empty spaces :param b1: bounds :param b2: bounds :param radius: specified radius, adapt for high density areas :return: list of circle centers that cover the area between lower/upper """ sw = Point(b1) ne = Point(b2) # north/east distances dist_lat = int(vincenty(Point(sw[0], sw[1]), Point(ne[0], sw[1])).meters) dist_lng = int(vincenty(Point(sw[0], sw[1]), Point(sw[0], ne[1])).meters) def cover(p_start, n_lat, n_lng, r): _coords = [] for i in range(n_lat): for j in range(n_lng): v_north = VincentyDistance(meters=i * r * 2) v_east = VincentyDistance(meters=j * r * 2) _coords.append( v_north.destination(v_east.destination(point=p_start, bearing=90), bearing=0)) return _coords def _calc_base(dist): """ Calculation for base cover """ return math.ceil((dist - radius) / (2 * radius)) + 1 def _calc_offset(dist): """ Calculation for offset cover """ return math.ceil((dist - 2 * radius) / (2 * radius)) + 1 coords = [] # get circles for base cover coords += cover(sw, _calc_base(dist_lat), _calc_base(dist_lng), radius) # update south-west for second cover vc_radius = VincentyDistance(meters=radius) sw = vc_radius.destination(vc_radius.destination(point=sw, bearing=0), bearing=90) # get circles for offset cover coords += cover(sw, _calc_offset(dist_lat), _calc_offset(dist_lng), radius) # only return the coordinates return [c[:2] for c in coords]
def get_malls(): ifpath = opath.join(dpath['geo'], 'mall-data.csv') ofpath = opath.join(dpath['home'], 'mallsInfo(%.2f).pkl' % ZONE_UNIT_KM) if opath.exists(ofpath): with open(ofpath, 'rb') as fp: malls = pickle.load(fp) return malls malls = {} mover = VincentyDistance(kilometers=ZONE_UNIT_KM) with open(ifpath) as r_csvfile: reader = csv.DictReader(r_csvfile) for row in reader: name = row['name'] lat, lon = map(float, [row[cn] for cn in ['latitude', 'longitude']]) p0 = [lat, lon] # moved_points = [] for d1, d2 in [(WEST, NORTH), (EAST, NORTH), (EAST, SOUTH), (WEST, SOUTH)]: mp = mover.destination(point=p0, bearing=d1) mp = mover.destination(point=mp, bearing=d2) moved_points.append(mp) # polygon_LatLon = [(mp.latitude, mp.longitude) for mp in moved_points] polygon_LatLon.append( (moved_points[0].latitude, moved_points[0].longitude)) malls[name] = (lat, lon, polygon_LatLon) with open(ofpath, 'wb') as fp: pickle.dump(malls, fp) return malls
def make_grid(zone_unit_km, min_long, max_long, min_lat, max_lat, consider_visualization=False): W_end_gps, E_end_gps = (min_long, (min_lat + max_lat) / float(2)), (max_long, (min_lat + max_lat) / float(2)) S_end_gps, N_end_gps = ((min_lat + max_lat) / float(2), min_lat), ((min_lat + max_lat) / float(2), max_lat) width_km = (vincenty(W_end_gps, E_end_gps).meters) / float(METER1000) height_km = (vincenty(S_end_gps, N_end_gps).meters) / float(METER1000) num_cols, num_rows = map(int, map(ceil, [v / float(zone_unit_km) for v in [height_km, width_km]])) # hl_length_gps, vl_length_gps = max_long - min_long, max_lat - min_lat xaxis_unit, yaxis_unit = hl_length_gps / float(num_cols), vl_length_gps / float(num_rows) x_points = [min_long + i * xaxis_unit for i in xrange(num_cols)] y_points = [min_lat + j * yaxis_unit for j in xrange(num_rows)] p0, p1 = (y_points[0], x_points[0]), (y_points[0], x_points[1]) x_dist = (vincenty(p0, p1).meters) / float(METER1000) p0, p1 = (y_points[0], x_points[0]), (y_points[1], x_points[0]) y_dist = (vincenty(p0, p1).meters) / float(METER1000) d = VincentyDistance(kilometers=zone_unit_km) print p0, d.destination(point=p0, bearing=0).latitude, d.destination(point=p0, bearing=0).longitude # print x_dist, y_dist, len(x_points), len(y_points) assert False return xaxis_unit, yaxis_unit, x_points, y_points
def isIntoTheCell_withPercentual(loc, s, bl, tr): s = s / 2 origin = geopy.Point(loc) # TODO cellEst = geopy.Point(tr[0], loc[1]) cellWest = geopy.Point(bl[0], loc[1]) cellNorth = geopy.Point(loc[0], tr[1]) cellSouth = geopy.Point(loc[0], bl[1]) # East distance dEst = VincentyDistance(kilometers=s).destination(origin, 0) # North distance dNorth = VincentyDistance(kilometers=s).destination(origin, 90) # West distance dWest = VincentyDistance(kilometers=s).destination(origin, 180) # South distance dSouth = VincentyDistance(kilometers=s).destination(origin, 270) #calculus of the area of the main cell area1 = haversine(bl, (bl[0], tr[1])) * haversine(bl, (tr[0], bl[1])) area2 = haversine((dWest[0], dSouth[1]), (dWest[0], dNorth[1])) * haversine((dWest[0], dSouth[1]), (dEst[0], dNorth[1])) if area2 > area1: return (True, float(area1) / float(area2)) else: return (True, 1)
def next(self, field): from geopy.distance import VincentyDistance longitude = random.randint(-179, 179) if self.longitude is None else self.longitude latitude = random.randint(-179, 179) if self.latitude is None else self.latitude radius = random.randint(100, 6000) if self.radius is None else self.radius d = VincentyDistance(kilometers=radius) bearing = random.randint(0, 359) p = d.destination((latitude, longitude), bearing) return Point(x=p.longitude, y=p.latitude)
def get_distance_vincenty(gps_data): distance = 0 last_trkpt = [gps_data[0]['latitude'],gps_data[0]['longitude']] for trkpt in gps_data: curr_trkpt = [trkpt['latitude'],trkpt['longitude']] dist = VincentyDistance() distance = distance + dist.measure(last_trkpt,curr_trkpt) last_trkpt = curr_trkpt return distance
def Circle_Geolocations(df): lat = df['Lat'] long = df['Long'] degree = df['Degree'] center = geopy.Point(lat, long) mile_distance = df['Max Travel'] d = Vincenty(miles=mile_distance) destination = d.destination(point=center, bearing=degree) return destination.latitude, destination.longitude
def hex_coordinates_c4(org): global array_of_waypoints dest_c4_1 = VincentyDistance(meters=3.5).destination(org, 300) lat_c4_1, lon_c4_1 = dest_c4_1.latitude, dest_c4_1.longitude array_of_waypoints.append([lat_c4_1, lon_c4_1]) dest_c4_2 = VincentyDistance(meters=3.5).destination(org, 240) lat_c4_2, lon_c4_2 = dest_c4_2.latitude, dest_c4_2.longitude array_of_waypoints.append([lat_c4_2, lon_c4_2]) dest_c4_3 = VincentyDistance(meters=3.5).destination(org, 180) lat_c4_3, lon_c4_3 = dest_c4_3.latitude, dest_c4_3.longitude array_of_waypoints.append([lat_c4_3, lon_c4_3])
def interpolation_radius(self, lat, lon): distance = VincentyDistance() d = distance.measure((np.amin(lat), np.amin(lon)), (np.amax(lat), np.amax(lon))) * 1000 / 8.0 if d == 0: d = 50000 d = np.clip(d, 20000, 50000) return d
def gen_points(upper_left=(47.733600, -122.403532), lower_right=(47.644154, -122.275468), radius=500): q = queue.Queue() p = upper_left while p[0] > lower_right[0]: while p[1] < lower_right[1]: p = VincentyDistance(meters=radius*0.71).destination(p, 90.0) # print(p.latitude, p.longitude, sep=", ") q.put((p[0], p[1], radius)) p = VincentyDistance(meters=radius*0.71).destination(p, 180.0) p = Point(p[0], upper_left[1]) return q
def get_coordinates(origin,nmbr_sqrt,dist): for i in np.arange(1,nmbr_sqrt): for j in np.arange(1,nmbr_sqrt): print(j) destination = VincentyDistance(miles=dist*j).destination(origin, 180) lat2, lon2 = destination.latitude, destination.longitude dest.append((lat2,lon2)) print(i) print(dist) origin_horizontal = VincentyDistance(miles=dist*i).destination(origin, 90) origin_horizontal_lat, origin_horizontal_lon = origin_horizontal.latitude, origin_horizontal.longitude origin = (origin_horizontal_lat,origin_horizontal_lon)
def getNeighbors(loc, level=15, spread=700): distance = VincentyDistance(meters=spread) center = (loc[0], loc[1], 0) p1 = distance.destination(point=center, bearing=45) p2 = distance.destination(point=center, bearing=225) p1 = s2sphere.LatLng.from_degrees(p1[0], p1[1]) p2 = s2sphere.LatLng.from_degrees(p2[0], p2[1]) rect = s2sphere.LatLngRect.from_point_pair(p1, p2) region = s2sphere.RegionCoverer() region.min_level = level region.max_level = level cells = region.get_covering(rect) return sorted([c.id() for c in cells])
def getNeighbors(loc, level=15, spread=700): distance = VincentyDistance(meters=spread) center = (loc.latitude, loc.longitude, 0) p1 = distance.destination(point=center, bearing=45) p2 = distance.destination(point=center, bearing=225) p1 = s2sphere.LatLng.from_degrees(p1[0], p1[1]) p2 = s2sphere.LatLng.from_degrees(p2[0], p2[1]) rect = s2sphere.LatLngRect.from_point_pair(p1, p2) region = s2sphere.RegionCoverer() region.min_level = level region.max_level = level cells = region.get_covering(rect) return sorted([c.id() for c in cells])
def interpolation_radius(self, lat, lon): distance = VincentyDistance() d = distance.measure( (np.amin(lat), np.amin(lon)), (np.amax(lat), np.amax(lon)) ) * 1000 / 8.0 if d == 0: d = 50000 d = np.clip(d, 20000, 50000) return d
def getBox(loc, s): s = s / 2 origin = geopy.Point(loc) dEst = VincentyDistance(kilometers=s).destination(origin, 0) dNorth = VincentyDistance(kilometers=s).destination(origin, 90) dWest = VincentyDistance(kilometers=s).destination(origin, 180) dSouth = VincentyDistance(kilometers=s).destination(origin, 270) bl = dWest[0], dSouth[1] tr = dEst[0], dNorth[1] return [bl, tr]
def finer_points(point): lat, lon, radius = point center = Point(lat, lon) third_radius = radius / 3 locations = [] east_center = VincentyDistance(meters=third_radius).destination(center, 90.0) # east_center locations.append(east_center) locations.append(VincentyDistance(meters=third_radius).destination(east_center, 0.0)) # east_north locations.append(VincentyDistance(meters=third_radius).destination(east_center, 180.0)) # east_south locations.append(VincentyDistance(meters=third_radius).destination(center, 0.0)) # center_north locations.append(VincentyDistance(meters=third_radius).destination(center, 180.0)) # center_south west_center = VincentyDistance(meters=third_radius).destination(center, 270.0) # west_center locations.append(west_center) locations.append(VincentyDistance(meters=third_radius).destination(west_center, 0.0)) # west_north locations.append(VincentyDistance(meters=third_radius).destination(west_center, 180.0)) # west_south points = [] new_raidus = radius / 3 * 1.4 for loc in locations: points.append((loc[0], loc[1], new_raidus)) return points
def test_get_circle_centers(): # test if circles fully cover the rect for sw, ne, w, h, r, circles in generate_testcases(): # test with 1000 random points for tst in range(1000): # choose random point within rect p = (random.uniform(0,w), random.uniform(0,h)) # translate to lat/lng pp = VincentyDistance(meters=p[0]).destination( VincentyDistance(meters=p[1]) .destination(point=sw, bearing=90), bearing=0 ) # check if point is contained in any of the calculated circles assert any([vincenty(pp, Point(c[0], c[1])).meters <= r for c in circles])
def defineBorders(coordinate): latitude = coordinate[0] longitude = coordinate[1] #Sqare around the big circle coordinates: 45 degree jump is 1 km for r = 0.707km BORDERS = {} BORDERS['NE'] = VincentyDistance(kilometers=1).destination( Point(latitude, longitude), 45) BORDERS['SE'] = VincentyDistance(kilometers=1).destination( Point(latitude, longitude), 135) BORDERS['SW'] = VincentyDistance(kilometers=1).destination( Point(latitude, longitude), 225) BORDERS['NW'] = VincentyDistance(kilometers=1).destination( Point(latitude, longitude), 315) return BORDERS
def generate_testcases(): # origin (south-west) sw = [48.132986, 11.566126] # width, height, radius in meters for w in [1, 10, 80, 200, 1000, 5000]: for h in [1, 20, 300, 1000, 20000]: for r in [180, 500]: # north-east (se + width/height) ne = VincentyDistance(meters=w).destination( VincentyDistance(meters=h) .destination(point=sw, bearing=90), bearing=0 )[:2] circles = get_circle_centers(sw, ne, r) yield (sw, ne, w, h, r, circles)
def NewCoords(vector, timeDelay=1 / 3600): speed = vector[0] direction = vector[3] distance_km = speed * timeDelay distance_miles = distance_km * 0.621371 return VincentyDistance(miles=distance_miles).destination( Point(vector[2], vector[1]), direction)
def move(self, distance, az): # a convenience method to actually move the crestnode through space # distance = distance to move in meters # az = azimuth to move the node lon1, lat1, z1 = self.geom.GetPoint(0) # set a geopy 'point' object and convert distance geopy_point1 = Point(longitude = lon1, latitude = lat1) distance = distance / 1000.0 #TEMPORARY TEST! # Make the dune go backwards! #az = az + 180.0 #if az > 360.0: # az = az - 360.0 # limit distance #if distance > 0.0002: # distance = 0.0002 #END TEMPORARY TEST! # compute 'vincenty' distance geopy_point2 = VincentyDistance(kilometers = distance).destination(geopy_point1, az) # assign new geometry to self.geom self.geom.SetPoint(0, x = geopy_point2.longitude, y = geopy_point2.latitude, z = z1) return
def newPoint(self, point, mDist, bearing): kmDist = mDist / 1000 origin = Point(point[0][0], point[0][1]) destination = VincentyDistance(kilometers=kmDist).destination( origin, bearing) return ((destination.latitude, destination.longitude), point[1] + timedelta(0, 4))
def find_new_lat_lng_geopy( lat, lng, b, dist ): #b in degrees (0 is north, 90 is east), dist=distance in kilometers ''' Uses geopy to find a point an 'as-the-crow-flies' distance from a given origin point ''' origin = geopy.Point(lat, lng) destination = VincentyDistance(kilometers=dist).destination(origin, b) return (destination.latitude, destination.longitude)
def radial_zip_data(self, out, session, **params): if params.get('radius'): res = ZipcodeSearchEngine().by_coordinate(self.center["Latitude"], self.center["Longitude"], radius=int( params['radius']), returns=0) out.writerow([ '# of Attendees', 'City', 'State', 'Zipcode', 'Miles from Event', '% of Total Attendees' ]) if len(res) > 0: keys = self.zips.keys() center_coord = (self.center["Latitude"], self.center["Longitude"]) filter = Attendee.badge_status.in_( [c.NEW_STATUS, c.COMPLETED_STATUS]) attendees = session.query(Attendee).filter(filter) total_count = attendees.count() for x in res: if x['Zipcode'] in keys: out.writerow([ self.zips_counter[x['Zipcode']], x['City'], x['State'], x['Zipcode'], VincentyDistance((x["Latitude"], x["Longitude"]), center_coord).miles, "%.2f" % float(self.zips_counter[x['Zipcode']] / total_count * 100) ])
def locationDistanceBearing(lon, lat, d, brng): import geopy from geopy.distance import VincentyDistance # given: lat1, lon1, b = bearing in degrees, d = distance in kilometers origin = geopy.Point(lat, lon) destination = VincentyDistance(kilometers=d).destination(origin, brng) return destination[1], destination[0]
def set_from_vincenty_formulae(self, initial_coordinates, distance): azimuth = abs((initial_coordinates.azimuth - 360.0) - 90) point = VincentyDistance(kilometers=distance).destination( Point(initial_coordinates.latitude, initial_coordinates.longitude), azimuth) self.latitude = point.latitude self.longitude = point.longitude
def global_to_local(lat, lon): # TODO: refactor position_global = rospy.wait_for_message('mavros/global_position/global', NavSatFix, timeout=5) pose = rospy.wait_for_message('mavros/local_position/pose', PoseStamped, timeout=5) d = math.hypot(pose.pose.position.x, pose.pose.position.y) bearing = math.degrees( math.atan2(-pose.pose.position.x, -pose.pose.position.y)) if bearing < 0: bearing += 360 cur = geopy.Point(position_global.latitude, position_global.longitude) origin = VincentyDistance(meters=d).destination(cur, bearing) _origin = origin.latitude, origin.longitude olat_tlon = origin.latitude, lon tlat_olon = lat, origin.longitude N = vincenty(_origin, tlat_olon) if lat < origin.latitude: N = -N E = vincenty(_origin, olat_tlon) if lon < origin.longitude: E = -E return E.meters, N.meters
def points_between(start, end, numpoints): distance = VincentyDistance() distances = [] latitudes = [] longitudes = [] lat0 = start.latitude lon0 = start.longitude lat1 = end.latitude lon1 = end.longitude if np.isclose(lat0, lat1): # Constant latitude latitudes = np.ones(numpoints) * lat0 longitudes = np.linspace(lon0, lon1, num=numpoints) for lon in longitudes: distances.append(distance.measure(start, geopy.Point(lat0, lon))) if lon1 > lon0: b = 90 else: b = -90 elif np.isclose(lon0, lon1): # Constant longitude latitudes = np.linspace(lat0, lat1, num=numpoints) longitudes = np.ones(numpoints) * lon0 for lat in latitudes: distances.append(distance.measure(start, geopy.Point(lat, lon0))) if lat1 > lat0: b = 0 else: b = 180 else: # Great Circle total_distance = distance.measure(start, end) distances = np.linspace(0, total_distance, num=numpoints) b = bearing(lat0, lon0, lat1, lon1) for d in distances: p = distance.destination(start, b, d) latitudes.append(p.latitude) longitudes.append(p.longitude) return distances, latitudes, longitudes, b
def make_grid(zone_unit_km, min_long, max_long, min_lat, max_lat): mover = VincentyDistance(kilometers=zone_unit_km) x = min_long x_points = [] while x < max_long: x_points.append(x) # p0 = [min_lat, x] moved_point = mover.destination(point=p0, bearing=EAST) x = moved_point.longitude y = min_lat y_points = [] while y < max_lat: y_points.append(y) # p0 = [y, min_long] moved_point = mover.destination(point=p0, bearing=NORTH) y = moved_point.latitude return x_points, y_points
def _path_to_points(points, n, intimes=None): if intimes is None: intimes = [0] * len(points) tuples = zip(points, points[1::], intimes, intimes[1::]) d = VincentyDistance() dist_between_pts = [] for pair in tuples: dist_between_pts.append(d.measure(pair[0], pair[1])) total_distance = np.sum(dist_between_pts) distances = [] target_lat = [] target_lon = [] bearings = [] times = [] for idx, tup in enumerate(tuples): npts = int(np.ceil(n * (dist_between_pts[idx] / total_distance))) if npts < 2: npts = 2 p0 = geopy.Point(tup[0]) p1 = geopy.Point(tup[1]) p_dist, p_lat, p_lon, b = points_between(p0, p1, npts) if len(distances) > 0: distances.extend(np.add(p_dist, distances[-1])) else: distances.extend(p_dist) target_lat.extend(p_lat) target_lon.extend(p_lon) bearings.extend([b] * len(p_dist)) times.extend([tup[2] + i * (tup[3] - tup[2]) / (npts - 1) for i in range(0, npts)]) return distances, times, target_lat, target_lon, bearings
def _transect_plot(self, values, depths, name, vmin, vmax): self.__fill_invalid_shift(values) dist = np.tile(self.transect_data['distance'], (values.shape[0], 1)) c = plt.pcolormesh(dist, depths.transpose(), values, cmap=self.cmap, shading='gouraud', vmin=vmin, vmax=vmax) ax = plt.gca() ax.invert_yaxis() if self.depth_limit is None or ( self.depth_limit is not None and self.linearthresh < self.depth_limit ): plt.yscale('symlog', linthreshy=self.linearthresh) ax.yaxis.set_major_formatter(ScalarFormatter()) # Mask out the bottom plt.fill_between( self.bathymetry['x'], self.bathymetry['y'] * -1, plt.ylim()[0], facecolor='dimgray', hatch='xx' ) ax.set_axis_bgcolor('dimgray') plt.xlabel(gettext("Distance (km)")) plt.ylabel(gettext("Depth (m)")) plt.xlim([self.transect_data['distance'][0], self.transect_data['distance'][-1]]) # Tighten the y-limits if self.depth_limit: plt.ylim(self.depth_limit, 0) else: deep = np.amax(self.bathymetry['y'] * -1) l = 10 ** np.floor(np.log10(deep)) plt.ylim(np.ceil(deep / l) * l, 0) ticks = sorted(set(list(plt.yticks()[0]) + [self.linearthresh, plt.ylim()[0]])) if self.depth_limit is not None: ticks = filter(lambda y: y <= self.depth_limit, ticks) plt.yticks(ticks) # Show the linear threshold plt.plot([self.transect_data['distance'][0], self.transect_data['distance'][-1]], [self.linearthresh, self.linearthresh], 'k:', alpha=0.5) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) bar = plt.colorbar(c, cax=cax) bar.set_label( name + " (" + utils.mathtext(self.transect_data['unit']) + ")") if len(self.points) > 2: station_distances = [] current_dist = 0 d = VincentyDistance() for idx, p in enumerate(self.points): if idx == 0: station_distances.append(0) else: current_dist += d.measure( p, self.points[idx - 1]) station_distances.append(current_dist) ax2 = ax.twiny() ax2.set_xticks(station_distances) ax2.set_xlim([self.transect_data['distance'][0], self.transect_data['distance'][-1]]) ax2.tick_params( 'x', length=0, width=0, pad=-3, labelsize='xx-small', which='major') ax2.xaxis.set_major_formatter(StrMethodFormatter(u"$\u25bc$")) cax = make_axes_locatable(ax2).append_axes( "right", size="5%", pad=0.05) bar2 = plt.colorbar(c, cax=cax) bar2.remove() return divider
def load_data(self): if self.projection == 'EPSG:32661': blat = min(self.bounds[0], self.bounds[2]) blat = 5 * np.floor(blat / 5) self.basemap = basemap.load_map('npstere', (blat, 0), None, None) elif self.projection == 'EPSG:3031': blat = max(self.bounds[0], self.bounds[2]) blat = 5 * np.ceil(blat / 5) self.basemap = basemap.load_map('spstere', (blat, 180), None, None) else: distance = VincentyDistance() height = distance.measure( (self.bounds[0], self.centroid[1]), (self.bounds[2], self.centroid[1]) ) * 1000 * 1.25 width = distance.measure( (self.centroid[0], self.bounds[1]), (self.centroid[0], self.bounds[3]) ) * 1000 * 1.25 self.basemap = basemap.load_map( 'lcc', self.centroid, height, width ) if self.basemap.aspect < 1: gridx = 500 gridy = int(500 * self.basemap.aspect) else: gridy = 500 gridx = int(500 / self.basemap.aspect) self.longitude, self.latitude = self.basemap.makegrid(gridx, gridy) with open_dataset(get_dataset_url(self.dataset_name)) as dataset: if self.time < 0: self.time += len(dataset.timestamps) self.time = np.clip(self.time, 0, len(dataset.timestamps) - 1) self.variable_unit = self.get_variable_units( dataset, self.variables )[0] self.variable_name = self.get_variable_names( dataset, self.variables )[0] scale_factor = self.get_variable_scale_factors( dataset, self.variables )[0] if self.cmap is None: if len(self.variables) == 1: self.cmap = colormap.find_colormap(self.variable_name) else: self.cmap = colormap.colormaps.get('speed') if len(self.variables) == 2: self.variable_name = self.vector_name(self.variable_name) if self.depth == 'bottom': depth_value = 'Bottom' else: self.depth = np.clip( int(self.depth), 0, len(dataset.depths) - 1) depth_value = dataset.depths[self.depth] data = [] allvars = [] for v in self.variables: var = dataset.variables[v] allvars.append(v) if self.filetype in ['csv', 'odv', 'txt']: d, depth_value = dataset.get_area( np.array([self.latitude, self.longitude]), self.depth, self.time, v, return_depth=True ) else: d = dataset.get_area( np.array([self.latitude, self.longitude]), self.depth, self.time, v ) d = np.multiply(d, scale_factor) self.variable_unit, d = self.kelvin_to_celsius( self.variable_unit, d) data.append(d) if self.filetype not in ['csv', 'odv', 'txt']: if len(var.dimensions) == 3: self.depth_label = "" elif self.depth == 'bottom': self.depth_label = " at Bottom" else: self.depth_label = " at " + \ str(int(np.round(depth_value))) + " m" if len(data) == 2: data[0] = np.sqrt(data[0] ** 2 + data[1] ** 2) self.data = data[0] quiver_data = [] if self.quiver is not None and \ self.quiver['variable'] != '' and \ self.quiver['variable'] != 'none': for v in self.quiver['variable'].split(','): allvars.append(v) var = dataset.variables[v] quiver_unit = get_variable_unit(self.dataset_name, var) quiver_name = get_variable_name(self.dataset_name, var) quiver_lon, quiver_lat = self.basemap.makegrid(50, 50) d = dataset.get_area( np.array([quiver_lat, quiver_lon]), self.depth, self.time, v ) quiver_data.append(d) self.quiver_name = self.vector_name(quiver_name) self.quiver_longitude = quiver_lon self.quiver_latitude = quiver_lat self.quiver_unit = quiver_unit self.quiver_data = quiver_data if all(map(lambda v: len(dataset.variables[v].dimensions) == 3, allvars)): self.depth = 0 contour_data = [] if self.contour is not None and \ self.contour['variable'] != '' and \ self.contour['variable'] != 'none': d = dataset.get_area( np.array([self.latitude, self.longitude]), self.depth, self.time, self.contour['variable'] ) contour_unit = get_variable_unit( self.dataset_name, dataset.variables[self.contour['variable']]) contour_name = get_variable_name( self.dataset_name, dataset.variables[self.contour['variable']]) contour_factor = get_variable_scale_factor( self.dataset_name, dataset.variables[self.contour['variable']]) contour_unit, d = self.kelvin_to_celsius(contour_unit, d) d = np.multiply(d, contour_factor) contour_data.append(d) self.contour_unit = contour_unit self.contour_name = contour_name self.contour_data = contour_data self.timestamp = dataset.timestamps[self.time] if self.variables != self.variables_anom: self.variable_name += " Anomaly" with open_dataset( get_dataset_climatology(self.dataset_name) ) as dataset: data = [] for v in self.variables: var = dataset.variables[v] d = dataset.get_area( np.array([self.latitude, self.longitude]), self.depth, self.timestamp.month - 1, v ) data.append(d) if len(data) == 2: data = np.sqrt(data[0] ** 2 + data[1] ** 2) else: data = data[0] u, data = self.kelvin_to_celsius( dataset.variables[self.variables[0]].unit, data) self.data -= data # Load bathymetry data self.bathymetry = overlays.bathymetry( self.basemap, self.latitude, self.longitude, blur=2 ) if self.depth != 'bottom' and self.depth != 0: if len(quiver_data) > 0: quiver_bathymetry = overlays.bathymetry( self.basemap, quiver_lat, quiver_lon) self.data[np.where(self.bathymetry < depth_value)] = np.ma.masked for d in self.quiver_data: d[np.where(quiver_bathymetry < depth_value)] = np.ma.masked for d in self.contour_data: d[np.where(self.bathymetry < depth_value)] = np.ma.masked else: mask = maskoceans(self.longitude, self.latitude, self.data).mask self.data[~mask] = np.ma.masked for d in self.quiver_data: mask = maskoceans( self.quiver_longitude, self.quiver_latitude, d).mask d[~mask] = np.ma.masked for d in contour_data: mask = maskoceans(self.longitude, self.latitude, d).mask d[~mask] = np.ma.masked if self.area and self.filetype in ['csv', 'odv', 'txt', 'geotiff']: area_polys = [] for a in self.area: rings = [LinearRing(p) for p in a['polygons']] innerrings = [LinearRing(p) for p in a['innerrings']] polygons = [] for r in rings: inners = [] for ir in innerrings: if r.contains(ir): inners.append(ir) polygons.append(Poly(r, inners)) area_polys.append(MultiPolygon(polygons)) points = [Point(p) for p in zip(self.latitude.ravel(), self.longitude.ravel())] indicies = [] for a in area_polys: indicies.append(np.where( map( lambda p, poly=a: poly.contains(p), points ) )[0]) indicies = np.unique(np.array(indicies).ravel()) newmask = np.ones(self.data.shape, dtype=bool) newmask[np.unravel_index(indicies, newmask.shape)] = False self.data.mask |= newmask self.depth_value = depth_value
from geopy.distance import vincenty, VincentyDistance p1 = (1.276772,103.612184) p2 = (1.383266,103.965440) NORTH, EAST, SHOUTH, WEST = 0, 90, 180, 270 mover = VincentyDistance(kilometers=1) p3 = mover.destination(point=p1, bearing=EAST) p4 = mover.destination(point=p1, bearing=SHOUTH) import folium cp = ((p1[0] + p2[0]) / float(2), (p1[1] + p2[1]) / float(2)) map_osm = folium.Map(location=[cp[0], cp[1]], zoom_start=11) map_osm.add_children(folium.PolyLine(locations=[(p1[0], p1[1]), (p2[0], p2[1])], weight=0.5)) for p, label in [(p1, 'p1'), (p2, 'p2'), (cp, 'Distance (p1, p2): %f m' % vincenty(p1, p2).meters), (p3,'p3 (1km East from p1)'), (p4,'p4 (1km South from p1)')]: folium.Marker((p[0], p[1]), popup=label).add_to(map_osm) map_osm.save('geopy_example.html')