def dist_in_miles(data, src, dst): '''Given a dict of names and location data, compute mileage between.''' src_pair = lat_long_pair(data[src]) src_loc = geo.xyz(src_pair[0], src_pair[1]) dst_pair = lat_long_pair(data[dst]) dst_loc = geo.xyz(dst_pair[0], dst_pair[1]) return geo.distance(src_loc, dst_loc) * METERS_TO_MILES
def dist_in_miles(g, src, dst): '''Given a NetworkX graph data and node names, compute mileage between.''' src_pair = lat_long_pair(g.node[src]) src_loc = geo.xyz(src_pair[0], src_pair[1]) dst_pair = lat_long_pair(g.node[dst]) dst_loc = geo.xyz(dst_pair[0], dst_pair[1]) return geo.distance(src_loc, dst_loc) * METERS_TO_MILES
def __init__(self, tools): self.mavlink = tools.mavlinkThread self.heading = float('NaN') self.altRel = float('NaN') self.targetHeadingRadians = float('NaN') self.position = geo.xyz(0, 0) self.homePositionSet = False self.homePosition = geo.xyz(0, 0)
def dist_between_crimes(self, crime1, crime2): coord1 = crime1.get_coordinates() coord2 = crime2.get_coordinates() #splat operator * turns fnctn(['p','p']) into fnctn('p1','p2') dist = geo.distance(geo.xyz(*coord1), geo.xyz(*coord2)) #avoid 1/r^2 singularities with 100 m min dist return dist if dist > 100 else 100
def dist_between_crimes(self,crime1,crime2): coord1 = crime1.get_coordinates() coord2 = crime2.get_coordinates() #splat operator * turns fnctn(['p','p']) into fnctn('p1','p2') dist = geo.distance(geo.xyz(*coord1),geo.xyz(*coord2)) #avoid 1/r^2 singularities with 100 m min dist return dist if dist > 100 else 100
def __init__(self): # Grab and parse the client.conf file self.config = ConfigParser.ConfigParser() # If the module is executed as a script __name__ will be '__main__' and sys.argv[0] will be the full path of the module. if __name__ == '__main__': path = os.path.split(sys.argv[0])[0] # Else the module was imported and it has a __file__ attribute that will be the full path of the module. else: path = os.path.split(__file__)[0] self.config.read(os.path.join(os.path.dirname(path), 'client.conf')) if len(self.config.sections()) <= 0: print('Config file not present, copying default') self.config.read(os.path.join(path, 'client.conf')) with open(os.path.join(os.path.dirname(path), 'client.conf'), "w") as conf: self.config.write(conf) # Set variables for host and port self.host = self.config.get("Connection", "host") self.video_port = int(self.config.get("Connection", "video_port")) self.message_port = int(self.config.get("Connection", "message_port")) # Set the message queue self.msg_q = Queue.Queue(maxsize=0) # Something for gps? my_lon = 33.6880290 my_lat = 117.9861210 hb = geo.xyz(my_lat, my_lon) la = geo.xyz(34.0522340, -118.2436850) true_north = geo.great_circle_angle(hb, la, geo.geographic_northpole) print('True North ' + str(true_north)) self.compass_heading = 0 self.pan_angle = 0 self.tilt_angle = 0 self.lidar_dist = 0 self.pointlist = [] self.lidarDict = OrderedDict() self.compassDict = OrderedDict() self.panDict = OrderedDict() self.tiltDict = OrderedDict() # Setup Messaging Connection self.chat = ch.chat_client(self.host, self.message_port) self.chat.connecttoserver() self.chat.receivedata(self) self.msg_q.put("Waiting for messages!") self.update_tele2() # Initialize the tkinter gui self.gui = clientgui.gui(self) print 'Starting Screen Thread' self.screen_thread() print 'Starting Map Thread' self.map_thread()
def getNearestBusStops(self, lat=None, lon=None, radius=1000, limit=10, line=None, via=None): #dados = list(csv.reader(open('circular1.csv'))) #__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))) if line != None and via != None: possible = self.listLinePoints(line, via) else: possible = None if (lat == None or lon == None): return "Missing Lat or Lon" source = geo.xyz(float(lat), float(lon)) txt = str(limit) + " Closest Bus Stops in a " + str( radius) + "m radius: <br/>" ldist = [] doc = xml.dom.minidom.parse("bus_stops.kml") for node in doc.getElementsByTagName("Placemark"): name = node.getElementsByTagName("name")[0].childNodes[0].data sid = node.getElementsByTagName("stopid")[0].childNodes[0].data points = node.getElementsByTagName("Point") coord = points[0].getElementsByTagName("coordinates") lon = float(coord[0].childNodes[0].data.split(",")[0]) lat = float(coord[0].childNodes[0].data.split(",")[1]) point = geo.xyz(lat, lon) dist = float('%.2f' % geo.distance(source, point)) if (float(dist) < float(radius) and (possible == None or possible.index(sid) != -1)): ldist.append({ 'dist': float(dist), 'name': name, 'lat': lat, 'lon': lon, 'sid': sid }) if (ldist == []): return self.getNearestBusStops(lat, lon, radius + 100, limit) return sorted(ldist, key=itemgetter('dist'))[0:int(limit)]
def getBusPath(self, line=0, via=0, start=-1, end=-1): try: doc = xml.dom.minidom.parse("Linha1.kml") except: return [] linepts = self.listLinePoints(line, via) sp = ep = -1 # Point IDs sd = ed = -1 # Distancias start_pt = end_pt = None if start != -1: if linepts.index(start) == -1: start = -1 else: pt = self.getStopPosition(start) start_pt = geo.xyz(float(pt['lat']), float(pt['lon'])) if end != -1: if linepts.index(end) == -1: end = -1 else: pt = self.getStopPosition(end) end_pt = geo.xyz(float(pt['lat']), float(pt['lon'])) plist = [] for node in doc.getElementsByTagName("coordinates"): pts = node.childNodes[0].data.split() for i in range(0, len(pts)): #plist.append(pts[i]) #continue p = pts[i].split(',') pt = geo.xyz(float(p[0]), float(p[1])) plist.append({'lat': p[0], 'lon': p[1]}) if start_pt != None: d = geo.distance(start_pt, pt) if sd == -1 or d < sd: #point = {'lat': p[0], 'lon': p[1], 'dist': sd} sd = d sp = i if end_pt != None: d = geo.distance(end_pt, pt) if ed == -1 or d < ed: #point = {'lat': p[0], 'lon': p[1], 'dist': ed} ed = d ep = i if (ep == -1 or sp == -1): return plist elif ep < sp: return plist[sp:] + plist[:ep] else: return plist[sp:ep]
def getDistanceRaw(self): if self.distanceRaw==None: this=geo.xyz(self.lat,self.lon) distance=int(geo.distance(this,home)) self.distanceRaw=distance return self.distanceRaw
def routeClosestPoint(self, lat=None, lon=None, line=0, via=0): try: doc = xml.dom.minidom.parse("Linha" + (line + 1) + ".kml") except: return [] source = geo.xyz(float(lat), float(lon)) md = -1 point = None for node in doc.getElementsByTagName("coordinates"): pts = node[0].childNodes[0].data.split(" ") for p in pts: p = p.split(',') pt = geo.xyz(float(p[0]), float(p[1])) d = geo.distance(source, pt) if md == -1 or d < md: point = {'lat': p[0], 'lon': p[1], 'dist': d} md = d return point
def genWaypoints(x,y): bbox = [min(y),min(x),max(y),max(x)] response = urllib2.urlopen("http://overpass.osm.rambler.ru/cgi/interpreter?data=[out:json];node[natural~'peak'][name](%(X)s);node[place~'town|city|village|hamlet'](%(X)s);out;" % {'X':','.join(map(str,bbox))}) places = json.loads(response.read()) minplaces = {} for i in range(len(x)): lon,lat = x[i],y[i] pt1 = geo.xyz(lon,lat) mindist = False minplace = False for place in places['elements']: pt2 = geo.xyz(place['lon'],place['lat']) dist = geo.distance(pt1,pt2) if False == mindist or dist < mindist: if (dist < 100 and 'natural' in place['tags'] and place['tags']['natural'] == 'peak') or \ (dist < 150 and 'place' in place['tags'] and place['tags']['place'] == 'hamlet') or \ (dist < 500 and 'place' in place['tags'] and place['tags']['place'] == 'village') or \ (dist < 1500 and 'place' in place['tags'] and place['tags']['place'] == 'place') or \ (dist < 5000 and 'place' in place['tags'] and place['tags']['place'] == 'city'): mindist = dist minplace = place if minplace: minplaces[minplace['tags']['name']] = minplace waypoints = {} for place in minplaces.values(): pt2 = geo.xyz(place['lon'],place['lat']) mindist = False; for i in range(len(x)): lon,lat = x[i],y[i] pt1 = geo.xyz(lon,lat) dist = geo.distance(pt1,pt2) if False == mindist or dist < mindist: mindist = dist mini = i if (mindist < 100 and 'natural' in place['tags'] and place['tags']['natural'] == 'peak') or \ (mindist < 150 and 'place' in place['tags'] and place['tags']['place'] == 'hamlet') or \ (mindist < 500 and 'place' in place['tags'] and place['tags']['place'] == 'village') or \ (mindist < 1500 and 'place' in place['tags'] and place['tags']['place'] == 'place') or \ (mindist < 5000 and 'place' in place['tags'] and place['tags']['place'] == 'city'): waypoints[mini] = (mindist,place['tags']['name']) return waypoints;
def getNearestBusStops(self, lat=None, lon=None, radius=1000, limit=10, line=None, via=None): #dados = list(csv.reader(open('circular1.csv'))) #__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))) if line != None and via != None: possible = self.listLinePoints(line, via) else: possible = None if(lat == None or lon == None): return "Missing Lat or Lon" source = geo.xyz(float(lat), float(lon)) txt = str(limit) + " Closest Bus Stops in a " + str(radius) + "m radius: <br/>" ldist = [] doc = xml.dom.minidom.parse("bus_stops.kml") for node in doc.getElementsByTagName("Placemark"): name = node.getElementsByTagName("name")[0].childNodes[0].data sid = node.getElementsByTagName("stopid")[0].childNodes[0].data points = node.getElementsByTagName("Point") coord = points[0].getElementsByTagName("coordinates") lon = float(coord[0].childNodes[0].data.split(",")[0]) lat = float(coord[0].childNodes[0].data.split(",")[1]) point = geo.xyz(lat, lon) dist = float('%.2f' % geo.distance(source, point)) if(float(dist) < float(radius) and (possible == None or possible.index(sid) != -1)): ldist.append({ 'dist':float(dist), 'name':name, 'lat':lat, 'lon':lon, 'sid':sid }) if(ldist == []): return self.getNearestBusStops(lat, lon, radius + 100, limit) return sorted(ldist, key=itemgetter('dist'))[0:int(limit)]
def parse_raw(raw): result = {} num_regexp = re.compile("\d+(\.\d+)?") last_update = prop_raw_extract("Date et heure du dernier point ", raw, True) # remove "(heure d'été)" last_update = last_update[0:last_update.rfind("(")].strip() result["last_update"] = datetime.strptime(last_update, "%d/%m/%Y %H:%M:%S") course = prop_raw_extract("Cap", raw) result["course"] = float(re.search(num_regexp, course).group(0)) speed = prop_raw_extract("Vitesse", raw) result["speed"] = float(re.search(num_regexp, speed).group(0)) latitude = prop_raw_extract("Latitude", raw) result["str_latitude"] = latitude south = latitude[0] == "S" split = re.findall("\d+", latitude) # N 47 43'30'' numlatitude = float(split[0]) + float(split[1])/60 + float(split[2])/3600 if south: numlatitude = -numlatitude result["latitude"] = numlatitude longitude = prop_raw_extract("Longitude", raw) result["str_longitude"] = longitude est = longitude[0] == "E" split = re.findall("\d+", longitude) # W 003 20'59'' numlongitude = float(split[0]) + float(split[1])/60 + float(split[2])/3600 if est: numlongitude = -numlongitude result["longitude"] = numlongitude pos = geo.xyz(numlatitude, numlongitude) # N 47 42,8 W 3 21,5 finish = geo.xyz(47.7133,3.3583) result["dtf"] = '%0.1f' % (geo.distance(pos, finish) / 1852) return result
def set_dest(self,*args): s=self.dest.get_text() pos=geo.parse_position(s) if pos==None: d = gtk.MessageDialog(type=gtk.MESSAGE_ERROR,buttons=gtk.BUTTONS_OK) d.set_markup("Invalid format.") d.run() d.destroy() else: if HAVE_MAP: self.map.draw_gps(pos[0],pos[1],0.) self.data_dest.set_text("Destination: %f\xc2\xb0 N %f\xc2\xb0 E" % pos) self.dest_pos=geo.xyz(*pos) self.update_data()
def extract_from_gps_logs(directory, rx_pos, offset): """ midpoint is a geo.xyz Returns a hash mapping t -> aoa for a GPS log file generated from the phone """ gps = {} with open("{d}/gps.txt".format(d = directory)) as f: reader = csv.reader(f) for row in reader: # time,lat,lon,elevation,accuracy,bearing,speed if len(row) == 7: dt = dateutil.parser.parse(row[0]) tx_pos = geo.xyz(float(row[1]), float(row[2])) bearing = geo.great_circle_angle(tx_pos, rx_pos, geo.geographic_northpole) bearing = np.radians(bearing) bearing = -bearing + offset bearing = np.arctan2(np.sin(bearing), np.cos(bearing)) # wrap to -pi/pi gps[dt] = bearing return gps
def extract_from_gps_logs(directory, rx_pos, offset): """ midpoint is a geo.xyz Returns a hash mapping t -> aoa for a GPS log file generated from the phone """ gps = {} with open("{d}/gps.txt".format(d=directory)) as f: reader = csv.reader(f) for row in reader: # time,lat,lon,elevation,accuracy,bearing,speed if len(row) == 7: dt = dateutil.parser.parse(row[0]) tx_pos = geo.xyz(float(row[1]), float(row[2])) bearing = geo.great_circle_angle(tx_pos, rx_pos, geo.geographic_northpole) bearing = np.radians(bearing) bearing = -bearing + offset bearing = np.arctan2(np.sin(bearing), np.cos(bearing)) # wrap to -pi/pi gps[dt] = bearing return gps
def handleHomePosition(self, msg): self.homePositionSet = True self.homePosition = geo.xyz(msg.latitude / 1E7, msg.longitude / 1E7)
gpx_file = open(sys.argv[1], 'r') gpx = gpxpy.parse(gpx_file) x = [] y = [] z = [] m = [] lpt = None for track in gpx.tracks: name = track.name for segment in track.segments: for point in segment.points: pt = geo.xyz(point.latitude,point.longitude) x.append(point.longitude) y.append(point.latitude) z.append(point.elevation) if lpt != None: m.append( m[-1] + geo.distance(pt,lpt)) else: m.append(0.0) lpt = pt #print m uphills = getUphills(m,z) waypoints = genWaypoints(x,y) totalm = 0
root.setLevel(logging.INFO) logger = logging.getLogger('main') logger.propagate = False logger.addHandler(handler) logger.setLevel(logging.INFO) parser = argparse.ArgumentParser(description = "Run RMS error simulations") parser.add_argument('--t_start', default=1452841400, type=float) parser.add_argument('--t_stop', default=1452848400, type=float) parser.add_argument('--t_offset', default=None, type=float) parser.add_argument('--aoa_offset', default=136.5, type=float) parser.add_argument('--d', type=str) args = parser.parse_args() rx_pos = geo.xyz(-33.956093444444, 18.467267555556) t_start = datetime.datetime.fromtimestamp(float(args.t_start)) t_start = t_start.replace(tzinfo = pytz.timezone('Etc/GMT-2')) t_stop = datetime.datetime.fromtimestamp(float(args.t_stop)) t_stop = t_stop.replace(tzinfo = pytz.timezone('Etc/GMT-2')) results = extract_from_df_results(args.d) results_freqs = results.keys() results_freqs = sorted(results_freqs, key=lambda freq: len(results[freq]), reverse=True) for freq in results_freqs: results_keys = results[freq].keys() results_keys = [k for k in results_keys if k >= t_start] results_keys = [k for k in results_keys if k <= t_stop] results_keys.sort() results_vals = [results[freq][x] for x in results_keys]
root.setLevel(logging.INFO) logger = logging.getLogger('main') logger.propagate = False logger.addHandler(handler) logger.setLevel(logging.INFO) parser = argparse.ArgumentParser(description="Run RMS error simulations") parser.add_argument('--t_start', default=1452841400, type=float) parser.add_argument('--t_stop', default=1452848400, type=float) parser.add_argument('--t_offset', default=None, type=float) parser.add_argument('--aoa_offset', default=136.5, type=float) parser.add_argument('--d', type=str) args = parser.parse_args() rx_pos = geo.xyz(-33.956093444444, 18.467267555556) t_start = datetime.datetime.fromtimestamp(float(args.t_start)) t_start = t_start.replace(tzinfo=pytz.timezone('Etc/GMT-2')) t_stop = datetime.datetime.fromtimestamp(float(args.t_stop)) t_stop = t_stop.replace(tzinfo=pytz.timezone('Etc/GMT-2')) results = extract_from_df_results(args.d) results_freqs = results.keys() results_freqs = sorted(results_freqs, key=lambda freq: len(results[freq]), reverse=True) for freq in results_freqs: results_keys = results[freq].keys() results_keys = [k for k in results_keys if k >= t_start] results_keys = [k for k in results_keys if k <= t_stop]
def in_range(node, city, radius): node_geo = geo.xyz(float(node[0]), float(node[1])) city_geo = geo.xyz(float(city[0]), float(city[1])) dist = geo.distance(node_geo, city_geo) * METERS_TO_MILES return dist < radius
def getXYZ(self): return geo.xyz(self.lat,self.lon)
def handleGlobalPositionInt(self, msg): self.position = geo.xyz(msg.lat / 1E7, msg.lon / 1E7) self.altRel = msg.relative_alt / 1000 # millimeters to meters
#!/usr/bin/python import xml.sax import xml.sax.handler import geo home=geo.xyz(51.059146, 13.767000) shortType={ u'Earthcache':u'E', u'Virtual Cache':u'V', u'Cache In Trash Out Event':u'CITO', u'Unknown Cache':u'?', u'Multi-cache':u'M', u'Event Cache':u'EV', u'Wherigo Cache':u'WIG', u'Letterbox Hybrid':u'L', u'Traditional Cache':u'T', u'Webcam Cache':u'WEB' } class Cache(object): def __init__(self): self.name="" self.code="" self.found="" self.ctype="" self.hidden="" self.d=""