Пример #1
0
def get_fuel_given_latlng_list(latlngs,
                               addr,
                               backend=None,
                               loose_end_dist_allow=80,
                               nodeslist=[],
                               print_res=False):
    ''' Given list of latlng, return fuel i.e. duration by backend '''
    gas = 0.
    routeUrl = get_route_url_given_latlng_list(latlngs,
                                               addr,
                                               backend=backend,
                                               print_res=print_res)
    ret = requests.get(routeUrl).json()
    gas += collect_duration_nodelist_given_json(
        ret, nodeslist)  # nodeslist: to check result
    if mm_nid2latlng.get_id() != "osm/cache-%s-nodeid-to-lat-lng.txt" % addr:
        mm_nid2latlng.use_cache(
            meta_file_name="osm/cache-%s-nodeid-to-lat-lng.txt" % addr,
            ignore_invalid_mem=True)
    ''' Check ----------- cases where first latlng is not matched '''
    try:
        firstLatlng = mm_nid2latlng.get(nodeslist[0]) or crawl_nid_to_latlng(
            nodeslist[0], silent=True)  # in case of None
    except:
        print("Node", nodeslist[0],
              "does not exist in either mm or overpy! Try 2nd node...")
        firstLatlng = mm_nid2latlng.get(nodeslist[1]) or crawl_nid_to_latlng(
            nodeslist[1], silent=True)
    dist = get_dist_meters_latlng2(latlngs[0], firstLatlng)
    if dist > loose_end_dist_allow:
        routeUrl = get_route_url_given_latlng_list([latlngs[0], firstLatlng],
                                                   addr,
                                                   backend=backend,
                                                   print_res=print_res)
        ret = requests.get(routeUrl).json()
        tmpl = []
        gas += collect_duration_nodelist_given_json(ret, tmpl)
        nodeslist = tmpl + nodeslist
    ''' Check ----------- cases where last latlng is not matched '''
    try:
        lastLatlng = mm_nid2latlng.get(nodeslist[-1]) or crawl_nid_to_latlng(
            nodeslist[-1], silent=True)  # in case of None
    except:
        lastLatlng = mm_nid2latlng.get(nodeslist[-2]) or crawl_nid_to_latlng(
            nodeslist[-2], silent=True)
    dist = get_dist_meters_latlng2(latlngs[-1], lastLatlng)
    if dist > loose_end_dist_allow:
        routeUrl = get_route_url_given_latlng_list([lastLatlng, latlngs[-1]],
                                                   addr,
                                                   backend=backend,
                                                   print_res=print_res)
        ret = requests.get(routeUrl).json()
        tmpl = []
        gas += collect_duration_nodelist_given_json(ret, tmpl)
        nodeslist = nodeslist + tmpl
    return gas
Пример #2
0
def extend_nodes_given_nid_angle(nid, heading, max_angle_diff,
                                 min_extend_dist):
    ''' walk dist heading within angle diff: '''
    cumudist = -1e-10
    extendnids = [nid]
    while cumudist < min_extend_dist:
        nblist = mm_nid2neighbor.get(extendnids[-1])
        lastlatlng = mm_nid2latlng.get(extendnids[-1])
        mindiff = 1e10
        straightNid = None
        for nbn in nblist:
            latlngnb = mm_nid2latlng.get(nbn)
            hdn = get_bearing_latlng2(lastlatlng, latlngnb)
            diff = min_angle_diff(hdn, heading)
            if diff < mindiff and diff <= max_angle_diff:
                mindiff = diff
                straightNid = nbn
                dist = get_dist_meters_latlng2(lastlatlng, latlngnb)
        if straightNid is not None:
            extendnids.append(straightNid)
            cumudist += dist
        else:
            break
    if cumudist < min_extend_dist:
        extendnids = []
    return extendnids
def sample_OD_latlngs_from_indexed_routes(RoutesEdgesDefXmlFile, num,
                                          accept_rate, minDist, maxDist):
    print("[ sample_OD_latlngs_from_routes ] " + RoutesEdgesDefXmlFile)
    print(num, accept_rate, minDist, maxDist)
    res = {}
    while len(res) < num:
        oddic = sample_OD_edges_from_indexed_routes(RoutesEdgesDefXmlFile, num,
                                                    accept_rate)
        for rid in oddic.keys():
            e1, e2 = oddic[rid]
            ret = query_sumo_edge(e1, Server_IP_Port)
            j1, j2 = ret['to'], ret['from']
            ret1 = query_sumo_junction(j1, Server_IP_Port)
            ret2 = query_sumo_junction(j2, Server_IP_Port)
            latlng1 = [
                0.1 * ret1['lat'] + 0.9 * ret2['lat'],
                0.1 * ret1['lng'] + 0.9 * ret2['lng']
            ]
            ret = query_sumo_edge(e2, Server_IP_Port)
            j1, j2 = ret['to'], ret['from']
            ret1 = query_sumo_junction(j1, Server_IP_Port)
            ret2 = query_sumo_junction(j2, Server_IP_Port)
            latlng2 = [
                0.9 * ret1['lat'] + 0.1 * ret2['lat'],
                0.9 * ret1['lng'] + 0.1 * ret2['lng']
            ]
            dist = get_dist_meters_latlng2(latlng1, latlng2)
            if dist >= minDist and dist <= maxDist:
                print("sampled frE %s to %s" % (e1, e2) +
                      " air-dist %.1f " % dist)
                res[rid] = [latlng1, latlng2]
                if len(res) == num: break
    return res
def sample_OD_latlngs_from_routes(routeFile,
                                  num=20,
                                  accept_rate=1,
                                  minDist=1000,
                                  maxDist=4000):
    # - accept_rate: prob accepting OD from routes in routeFile= .rou.xml
    # - minDist maxDist: air dist between OD.
    print("[ sample_OD_latlngs_from_routes ] " + routeFile)
    print(num, accept_rate, minDist, maxDist)
    res = []
    while len(res) < num:
        ode = sample_OD_edges_from_routes(routeFile, num, accept_rate)
        for e1, e2 in ode:
            ret = query_sumo_edge(e1, Server_IP_Port)
            j1, j2 = ret['to'], ret['from']
            ret1 = query_sumo_junction(j1, Server_IP_Port)
            ret2 = query_sumo_junction(j2, Server_IP_Port)
            latlng1 = [(ret1['lat'] + ret2['lat']) / 2,
                       (ret1['lng'] + ret2['lng']) / 2]  # mid of edge
            ret = query_sumo_edge(e2, Server_IP_Port)
            j1, j2 = ret['to'], ret['from']
            ret1 = query_sumo_junction(j1, Server_IP_Port)
            ret2 = query_sumo_junction(j2, Server_IP_Port)
            latlng2 = [(ret1['lat'] + ret2['lat']) / 2,
                       (ret1['lng'] + ret2['lng']) / 2]
            dist = get_dist_meters_latlng2(latlng1, latlng2)
            if dist >= minDist and dist <= maxDist:
                print("sampled frE %s to %s" % (e1, e2) +
                      " air-dist %.1f " % dist)
                res.append([latlng1, latlng2])
                if len(res) == num: break
    return res
Пример #5
0
def search_along_path(path, last_path_pos, mlatlng0, mlatlng1):
    Rough_dist_tolerate = 52
    Rough_angle_tolerate = 80
    mhead = get_bearing_latlng2(mlatlng0, mlatlng1)
    mindist = 1e6
    mindistline = 1e6
    minangle = 1e6
    for i in range(last_path_pos, len(path) - 1):
        dic = path[i]
        splatlng = [dic[KeyGPSLat], dic[KeyGPSLng]]
        dist1 = get_dist_meters_latlng2(splatlng, mlatlng1)
        if dist1 > 300: continue
        dist12 = dist_point_to_line_of_2pts(splatlng, mlatlng0, mlatlng1)
        if KeyGPSBearing in dic:
            sphead = dic[KeyGPSBearing]
        else:
            ''' find truly moved two pts to get heading'''
            j = i + 1
            sphead = None
            while j < len(path) and get_dist_meters_latlng2(
                    splatlng, [path[j][KeyGPSLat], path[j][KeyGPSLng]]) < 5:
                if iprint >= 3:
                    print(
                        "search_along_path find truly moved dist to get heading",
                        i, j)
                if KeyGPSBearing in path[j] and sphead is None:
                    sphead = path[j][KeyGPSBearing]
                j += 1
            if j == len(path): j = i + 1
            if sphead is None:
                sphead = get_bearing_latlng2(
                    splatlng, [path[j][KeyGPSLat], path[j][KeyGPSLng]])
        if mindist > dist1: mindist = dist1
        if mindistline > dist12: mindistline = dist12
        if min_angle_diff(sphead, mhead) < minangle:
            minangle = min_angle_diff(sphead, mhead)
        if dist1 < Rough_dist_tolerate and dist12 < Rough_dist_tolerate and min_angle_diff(
                sphead, mhead) < Rough_angle_tolerate:
            return i
    if iprint >= 3:
        print("search_along_path fail: mhead", mhead, "min dist", mindist,
              "min distline", mindistline, "min angle d", minangle)
    return -1
Пример #6
0
def find_osm_bbox(addr, geo_lookup_file=True):
    ''' You need to specify bbox in geo.py if you do not trust auto bbox below. '''
    res = mm_addr_bbox_snwe.get(addr)
    if res is None and geo_lookup_file:  # look up pickled file
        if addr in dic_mm_addr_bbox_snwe:  # gen by geo.py
            res = dic_mm_addr_bbox_snwe[addr]
    if iprint: print("mm_addr_bbox_snwe:", addr, res)
    isFromMM = 0
    if res is not None:
        lats, latn, lngw, lnge = res
        isFromMM = 1
    else:
        urladdr = urllib.quote_plus(addr)
        url = "http://nominatim.openstreetmap.org/search?format=json&limit=1&dedupe=0&polygon_geojson=1&q=%s" % (
            urladdr)
        if iprint >= 2: print(url)
        ret = requests.get(url).json()
        try:
            lats, latn, lngw, lnge = ret[0]["boundingbox"]
            use_google = 0
        except:
            use_google = 1

        if use_google == 1:
            if iprint >= 2: print("Using gmaps for bbox")
            gmaps = GoogleMaps()
            viewport = gmaps.address2bbox(addr)
            lats = viewport["southwest"]["lat"]
            latn = viewport["northeast"]["lat"]
            lngw = viewport["southwest"]["lng"]
            lnge = viewport["northeast"]["lng"]
    if iprint > 0:
        print(__file__, lats, latn, lngw, lnge)
        print(
            get_dist_meters_latlng2([lats, lngw], [latn, lngw]) / 1000,
            "km  height")
        print(
            get_dist_meters_latlng2([latn, lngw], [latn, lnge]) / 1000,
            "km  width")
    return float(lats), float(latn), float(lngw), float(lnge), isFromMM
Пример #7
0
 def get_target_bbox(self, addr, extend=True):
     meterPerDeg = 111000
     lats, latn, lngw, lnge, isFromMM = find_osm_bbox(addr)
     width = get_dist_meters_latlng2([lats, lngw], [lats, lnge])
     height = get_dist_meters_latlng2([latn, lngw], [lats, lngw])
     print("width", width, "height", height)
     if width > 60000:  # if not from memcache, then do extend.
         extendMeters = -width / 6.0
     elif width > 40000:
         extendMeters = -5000
     elif width < 10000:
         extendMeters = 3000
     else:
         extendMeters = 0
     extendLng = 0.0
     if isFromMM == 0:
         extendLng = float(extendMeters) / max(
             1e-10, meterPerDeg * math.cos(math.pi / 180 * latn))
     print("extendLng", extendLng)
     lngw = max(-179.9, min(179.9, lngw - extendLng))
     lnge = max(-179.9, min(179.9, lnge + extendLng))
     if height > 60000:
         extendMeters = -height / 6.0
     elif height > 40000:
         extendMeters = -5000
     elif height < 10000:
         extendMeters = 3000
     else:
         extendMeters = 0
     extendLat = 0.0
     if isFromMM == 0:
         extendLat = float(extendMeters) / meterPerDeg
     print("extendLat", extendLat)
     lats = max(-89.9, min(89.9, lats - extendLat))
     latn = max(-89.9, min(89.9, latn + extendLat))
     return lats, latn, lngw, lnge
Пример #8
0
def get_route_url_given_latlng_list(latlngs,
                                    addr,
                                    insert_every_num=None,
                                    backend=None,
                                    print_res=False):
    ''' Return URL with via waypoints in it, given a list of latlngs. 
	GET http://172.22.68.71:5000/route/v1/driving/-88.22219,40.114936;-88..,40..;-88.235836,40.101568?annotations=true&steps=true
	- insert_every_num: insert mid way point every this gps pts.
	'''
    dist = get_dist_meters_latlng2(latlngs[0], latlngs[-1])
    if insert_every_num is None:
        if len(latlngs) < 4:
            insert_every_num = 1
        elif len(latlngs) >= 4 and len(latlngs) < 10:
            insert_every_num = 2
        elif len(latlngs) >= 10 and len(latlngs) < 500:
            insert_every_num = max(2, int(len(latlngs) / 10.0))
        elif len(latlngs) >= 500:
            insert_every_num = 50  # skip mid pts to avoid long url.
    pcnt = 0
    i = 0
    locs = ""
    # rad=""
    while i < len(latlngs):
        if i == len(latlngs) - 1:
            locs += str(latlngs[i][LngFirst]) + "," + str(
                latlngs[i][1 - LngFirst])
            # rad+="20"
        elif i % insert_every_num == 0:
            locs += str(latlngs[i][LngFirst]) + "," + str(
                latlngs[i][1 - LngFirst]) + ";"
            # rad+="20;"
            pcnt += 1
        i += 1
    if backend is None:
        backend = addr2ip[addr]
    distPerPt = dist / pcnt  #  way point every this meters.
    if len(latlngs) == 2 or dist > 40000 or distPerPt > 2000:
        routeUrl = URL_Route.format(Backend=backend, Loc=locs)  # route API
        routeUrl += '&steps=true'
    else:
        routeUrl = URL_Match.format(Backend=backend, Loc=locs)  # match API
        routeUrl += '&steps=true'  #'&steps=true&radiuses='+rad
    return routeUrl
Пример #9
0
def get_pass_by_trips(AddTlsNetfile, TaxiStorageFile):
    netObj = sumolib.net.readNet(AddTlsNetfile)
    bbox = netObj.getBBoxXY()
    minX, minY = bbox[0]
    maxX, maxY = bbox[1]
    minLon, minLat = netObj.convertXY2LonLat(minX, minY)
    maxLon, maxLat = netObj.convertXY2LonLat(maxX, maxY)
    bufD = 150. * 0.00001  # boundary shrink
    minLon, minLat, maxLon, maxLat = minLon + bufD, minLat + bufD, maxLon - bufD, maxLat - bufD
    print("osm bbox", minLat, minLon, maxLat, maxLon)
    data = {}
    cnt, thresh, badline = 0, 1, 0
    afn = mypydir + mapFolder + os.sep + "taxi" + os.sep + 'taxi-pass-append.txt'

    def _write(wstr):
        with open(afn, 'a') as f:
            f.write(wstr)

    with open(TaxiStorageFile, "r") as f:
        for l in f:
            st = l.split('"')
            assert len(st) <= 3, l
            if len(st) > 1:
                l = st[0] + st[2]  # get rid of ',' in between ""
            st = l.split(",")
            try:
                slat = float(st[hindex("Pickup Centroid Latitude")])
                slng = float(st[hindex("Pickup Centroid Longitude")])
                elat = float(st[hindex("Dropoff Centroid Latitude")])
                elng = float(st[hindex("Dropoff Centroid Longitude")])
            except:
                badline += 1
                continue
            # init filter by min/max lat/lon
            vertm = dist_point_to_line_of_2pts([minLat, minLon], [slat, slng],
                                               [elat, elng])
            vertx = dist_point_to_line_of_2pts([maxLat, maxLon], [slat, slng],
                                               [elat, elng])
            # too far away
            if vertm > 4000 or vertx > 4000:
                continue
            # filter out inside bbox, already generated
            if in_bbox_latlng(slat, slng, minLat, minLon, maxLat,
                              maxLon) and in_bbox_latlng(
                                  elat, elng, minLat, minLon, maxLat, maxLon):
                continue
            # get route as list of latlngs
            try:
                res = requests.post(config.GreenRoute_IP_Port + '/html/route',
                                    data={
                                        'startLat': slat,
                                        'startLng': slng,
                                        'endLat': elat,
                                        'endLng': elng
                                    }).json()
            except:
                print("Err requests.post " + config.GreenRoute_IP_Port +
                      '/html/route')
                continue
            latlnglst = []
            for latlngStr in str(res['gpstrace']).split("~|"):
                tmp = latlngStr.split(",")
                latlnglst.append([float(tmp[0]), float(tmp[1])])
            # find 1st pt to be in bbox:
            i = 0
            while i < len(latlnglst):
                lat, lng = latlnglst[i]
                if in_bbox_latlng(lat, lng, minLat, minLon, maxLat, maxLon):
                    break
                i += 1
            starti = i
            if starti == len(latlnglst):
                continue
            while i < len(latlnglst):
                lat, lng = latlnglst[i]
                if not in_bbox_latlng(lat, lng, minLat, minLon, maxLat,
                                      maxLon):
                    break
                i += 1
            endi = i - 1
            airDist = get_dist_meters_latlng2(latlnglst[starti],
                                              latlnglst[endi])
            if airDist < 1200:
                continue  # air-dist too small
            slat, slng = latlnglst[starti]
            elat, elng = latlnglst[endi]

            if 1:  # Note: duration/seconds/dist/miles info is invalid
                try:
                    seconds = int(st[hindex("Trip Seconds")])
                except:
                    seconds = 0.
                airDist = get_dist_meters_latlng2([slat, slng], [elat, elng])
                try:
                    miles = float(st[hindex("Trip Miles")])
                except:
                    miles = 0.
                if airDist < 10 or miles < 0.01 or seconds < 1:
                    continue

                speed = miles * MetersPerMile / seconds
                hd = get_bearing_latlng2([slat, slng], [elat, elng])
                date = st[hindex("Trip Start Timestamp")].strip()
                weekday = get_weekday_index_given_mdyhms12(
                    date)  # 09/18/2013 07:45:00 AM
                hour = get_hour_index_given_str(date)
                minute = get_minute_given_str(date)
                month, day, year = date.split(' ')[0].split('/')
                month, day, year = int(month), int(day), int(year)

                if year != 2017: continue
                if month != 4: continue
                if year not in data: data[year] = {}
                if month not in data[year]: data[year][month] = []

                x1, y1 = netObj.convertLonLat2XY(slng, slat)
                x2, y2 = netObj.convertLonLat2XY(elng, elat)
                dic = {
                    'lat1': slat,
                    'lng1': slng,
                    'lat2': elat,
                    'lng2': elng,
                    'weekday': weekday,
                    'speed': speed,
                    'x1': x1,
                    'y1': y1,
                    'x2': x2,
                    'y2': y2,
                    'hd': hd,
                    'year': year,
                    'month': month,
                    "day": day,
                    "hour": hour,
                    "minute": minute
                }
                data[year][month].append(dic)
                _write(json.dumps(dic) + '\n')
                cnt += 1
                if cnt >= thresh:
                    thresh *= 2
                    print(cnt)
                    print(dic)
    print("cnt", cnt, "badline", badline)
    if cnt > 0:
        fn = mypydir + mapFolder + os.sep + "taxi" + os.sep + 'taxi-pass.txt'
        print("pickle dump to " + fn)
        pickle.dump(data, open(fn, "wb"))
def get_google_latlngs_given_2latlng(latlng1,
                                     latlng2,
                                     overwrite=False,
                                     show=False,
                                     RouteStatsDir=None,
                                     index=None,
                                     html_show=None,
                                     print_res=False):
    key = "g%.5f,%.5f,%.5f,%.5f" % (latlng1[0], latlng1[1], latlng2[0],
                                    latlng2[1])
    if isinstance(index, int): index = str(index)
    cache_file = _Cache_Dir + key
    if not overwrite and os.path.exists(cache_file):
        with open(cache_file, "r") as f:
            print("read from cache " + cache_file)
            return f.readline()
    ret = gmaps.get_route_given_2latlng(
        latlng1, latlng2)  # [[latlng, dist, duration ],] sparse steps
    # convert google's sparse latlng into dense latlng using osrm server.
    latlngs = []
    for stt in ret:
        latlngs.append([stt[0][0], stt[0][1]])
    nodeslist, addr = [], config.addr
    get_fuel_given_latlng_list(latlngs,
                               addr,
                               addr2ip[addr],
                               URL_Match,
                               mm_nid2latlng,
                               loose_end_dist_allow=20,
                               nodeslist=nodeslist,
                               print_res=print_res)
    if mm_nid2latlng.get_id() != "osm/cache-%s-nodeid-to-lat-lng.txt" % addr:
        mm_nid2latlng.use_cache(
            meta_file_name="osm/cache-%s-nodeid-to-lat-lng.txt" % addr,
            ignore_invalid_mem=True)
    # convert node ids into latlng list
    ret = []
    for nid in nodeslist:
        latlng = mm_nid2latlng.get(nid)
        if latlng is None: print("mm_nid2latlng get None", nid)
        ret.append([latlng, 0, 0])  # same format [[latlng, dist, duration ],]

    gps, distances, gmapTrace, sumDist = [], [], "", 0.
    lastDx, lastDy = None, None
    for i in range(len(ret) - 1):
        latlng, dist, duration = ret[i]
        latlng2, dist2, duration2 = ret[i + 1]
        hd = get_bearing_latlng2(latlng, latlng2)
        sumDist += get_dist_meters_latlng2(latlng, latlng2)
        lng, lat = get_moved_xy(latlng[1], latlng[0], (hd + 90) % 360,
                                0.0000)  # 0.0 means not moving
        if lastDx is None:
            lastDx, lastDy = (lng - latlng[1]), (lat - latlng[0])
        else:
            Dx, Dy = (lng - latlng[1]), (lat - latlng[0])
            lng, lat = (Dx + lastDx) / 2. + latlng[1], (
                Dy + lastDy) / 2. + latlng[0]
            lastDx, lastDy = Dx, Dy
        gps.append([lat, lng])
        distances.append(dist)
        gmapTrace += "new google.maps.LatLng(%.5f,%.5f)," % (lat, lng)
    latlng, dist, duration = ret[-1]
    lng, lat = get_moved_xy(latlng[1], latlng[0], (hd + 90) % 360, 0.0000)
    Dx, Dy = (lng - latlng[1]), (lat - latlng[0])
    lng, lat = (Dx + lastDx) / 2. + latlng[1], (Dy + lastDy) / 2. + latlng[0]
    gps.append([lat, lng])
    distances.append(dist)
    strlist, gmapTrace, path = [], '', []
    xs, ys = [], []
    for i in range(len(gps) - 1):
        latlng1, latlng2 = gps[i], gps[i + 1]
        inter = interpolate_points(latlng1, latlng2,
                                   max(2, int(distances[i + 1] / 30)))
        for latlng in inter:
            strlist.append("%.5f,%.5f" % (latlng[1], latlng[0]))
            xs.append(latlng[1])
            ys.append(latlng[0])
            gmapTrace += "new google.maps.LatLng(%.5f,%.5f)," % (latlng[0],
                                                                 latlng[1])
            path.append(latlng)
    strlist.append("%.5f,%.5f" % (latlng2[1], latlng2[0]))
    gmapTrace += "new google.maps.LatLng(%.5f,%.5f)," % (latlng2[0],
                                                         latlng2[1])
    path.append(latlng2)
    if RouteStatsDir:
        gen_map_html_from_path_list([path],
                                    RouteStatsDir + "%s-gg.html" % index,
                                    '',
                                    disturb=False,
                                    right_col_disp_list=[
                                        html_show if html_show else "",
                                        "Dist %.1f" % sumDist
                                    ])
    xs.append(latlng2[1])
    ys.append(latlng2[0])
    if show:
        plt.plot(xs, ys, '-ko')
        plt.show()
    wstr = " ".join(strlist)
    if overwrite or not os.path.exists(cache_file):
        with open(cache_file, "w") as f:
            f.write(wstr)
    return wstr
def get_green_latlngs_given_2latlng(latlng1,
                                    latlng2,
                                    overwrite=False,
                                    show=False,
                                    RouteStatsDir=None,
                                    index=None,
                                    html_show=None):
    key = "f%.5f,%.5f,%.5f,%.5f" % (latlng1[0], latlng1[1], latlng2[0],
                                    latlng2[1])
    if isinstance(index, int): index = str(index)
    fn = _Cache_Dir + key
    if not overwrite and os.path.exists(fn):
        with open(fn, "r") as f:
            return f.readline()
    res = requests.post(config.GreenRoute_IP_Port + '/html/route',
                        data={
                            'startLat': latlng1[0],
                            'startLng': latlng1[1],
                            'endLat': latlng2[0],
                            'endLng': latlng2[1]
                        }).json()
    ret = []
    for latlngStr in str(res['gpstrace']).split("~|"):
        st = latlngStr.split(",")
        ret.append([float(st[0]), float(st[1])])
    gps, gmapTrace, sumDist, lastDx, lastDy = [], '', 0., None, None
    for i in range(len(ret) - 1):
        latlng = ret[i]
        latlng2 = ret[i + 1]
        sumDist += get_dist_meters_latlng2(latlng, latlng2)
        gps.append(latlng)
        gmapTrace += "new google.maps.LatLng(%.5f,%.5f)," % tuple(latlng)
    latlng = ret[-1]
    gps.append(latlng)
    strlist, gmapTrace, path = [], '', []
    xs, ys = [], []
    for i in range(len(gps) - 1):
        latlng1, latlng2 = gps[i], gps[i + 1]
        inter = interpolate_points(latlng1, latlng2, 2)
        for latlng in inter:
            strlist.append("%.5f,%.5f" % (latlng[1], latlng[0]))
            xs.append(latlng[1])
            ys.append(latlng[0])
            gmapTrace += "new google.maps.LatLng(%.5f,%.5f)," % (latlng[0],
                                                                 latlng[1])
            path.append(latlng)
    strlist.append("%.5f,%.5f" % (latlng2[1], latlng2[0]))
    gmapTrace += "new google.maps.LatLng(%.5f,%.5f)," % (latlng2[0],
                                                         latlng2[1])
    path.append(latlng2)
    if RouteStatsDir:
        gen_map_html_from_path_list([path],
                                    RouteStatsDir + "%s-gf.html" % index,
                                    '',
                                    disturb=False,
                                    right_col_disp_list=[
                                        html_show if html_show else "",
                                        "Dist %.1f" % sumDist
                                    ])
    xs.append(latlng2[1])
    ys.append(latlng2[0])
    if show:
        plt.plot(xs, ys, '-ko')
        plt.show()
    wstr = " ".join(strlist)
    if overwrite or not os.path.exists(fn):
        with open(fn, "w") as f:
            f.write(wstr)
    return wstr
Пример #12
0
                Data_minLon, Data_minLat, Data_maxLon, Data_maxLat = min(
                    slng, elng), min(slat, elat), max(slng,
                                                      elng), max(slat, elat)
            if Data_minLon > min(slng, elng): Data_minLon = min(slng, elng)
            if Data_minLat > min(slat, elat): Data_minLat = min(slat, elat)
            if Data_maxLon < max(slng, elng): Data_maxLon = max(slng, elng)
            if Data_maxLat < max(slat, elat): Data_maxLat = max(slat, elat)

            if in_bbox_latlng(slat, slng, minLat, minLon, maxLat,
                              maxLon) and in_bbox_latlng(
                                  elat, elng, minLat, minLon, maxLat, maxLon):
                try:
                    seconds = int(st[ind("Trip Seconds")])
                except:
                    seconds = 0.
                airDist = get_dist_meters_latlng2([slat, slng], [elat, elng])
                try:
                    miles = float(st[ind("Trip Miles")])
                except:
                    miles = 0.
                if airDist < 10 or miles < 0.01 or seconds < 1:
                    continue

                speed = miles * MetersPerMile / seconds
                hd = get_bearing_latlng2([slat, slng], [elat, elng])
                date = st[ind("Trip Start Timestamp")].strip()
                weekday = get_weekday_index_given_mdyhms12(
                    date)  # 09/18/2013 07:45:00 AM
                hour = get_hour_index_given_str(date)
                minute = get_minute_given_str(date)
                month, day, year = date.split(' ')[0].split('/')
Пример #13
0
                            angleMatched = 0
                            distMatched = 0

                            dic = path[ind]
                            splat = dic[KeyGPSLat]
                            splng = dic[KeyGPSLng]
                            if not osm.within_bbox([splat, splng]):
                                outsideBbox = 1
                                break
                            sphead = None
                            if KeyGPSBearing in dic:
                                sphead = dic[KeyGPSBearing]
                            else:
                                j = ind + 1
                                while j < len(path) and get_dist_meters_latlng2(
                                    [splat, splng],
                                    [path[j][KeyGPSLat], path[j][KeyGPSLng]
                                     ]) < 5:
                                    if KeyGPSBearing in path[j]:
                                        sphead = path[j][KeyGPSBearing]
                                        break
                                    j += 1
                                if j == len(path): j = ind + 1
                                if sphead is None:
                                    sphead = get_bearing_latlng2(
                                        [splat, splng], [
                                            path[j][KeyGPSLat],
                                            path[j][KeyGPSLng]
                                        ])
                            # angle of matched nodes with GPS sample:
                            angle1 = get_bearing_latlng2(
                                latlng0, [splat, splng])