Beispiel #1
0
def get_notampoints_on_line(latlon1,latlon2,dist_nm):
    zoomlevel=13
    distmax=mapper.approx_scale(mapper.latlon2merc(latlon1,zoomlevel),zoomlevel,dist_nm)
    px1,py1=mapper.latlon2merc(latlon1,zoomlevel)
    px2,py2=mapper.latlon2merc(latlon2,zoomlevel)
    a=Vertex(int(px1),int(py1))
    b=Vertex(int(px2),int(py2))
    line=Line(a,b)    
    crosses=[]
    for kind,items in get_notam_objs_cached().items():
        if kind!="areas":
            for item in items:
                x,y=mapper.latlon2merc(mapper.from_str(item['pos']),zoomlevel)
                d=line.approx_dist(Vertex(int(x),int(y)))
                clo=line.approx_closest(Vertex(int(x),int(y)))
                alongd=(clo-a).approxlength()
                totd=(a-b).approxlength()
                #print "AlongD: %s, totd: %s"%(alongd,totd)
                #print "Line: %s, notam coord: %s, closest: %s"%((a,b),(x,y),clo)
                #print "Item %s, d: %s, distmax: %s"%(item,d,distmax)
                if totd<1e-6:
                    perc=0
                else:                    
                    perc=alongd/totd
                if d<distmax:
                    #print "Yielding item."
                    yield dict(item=item,alongperc=perc)
Beispiel #2
0
def follow_along(context,start,end,longwayround=False):
    out=[]
    for merc in follow_along13(context,
            mapper.latlon2merc(start,13),
            mapper.latlon2merc(end,13),longwayround=longwayround):
        out.append( mapper.merc2latlon(merc,13) )
    return out
Beispiel #3
0
 def set_pos_zoom(self,latlon=None,zoom=None):
     #print "Setting pos to %s"%(latlon,)
     if latlon==None:
         assert zoom==None
         zoomlevel=session.get('zoom',None)
         if zoomlevel==None:
             zoomlevel=5
             merc_x,merc_y=mapper.latlon2merc((58,18),zoomlevel)
         else:
             merc_x,merc_y=session['last_pos']
     else:
         assert zoom!=None            
         zoomlevel=zoom
         if zoomlevel<5:
             zoomlevel=5
         if session.get('mapvariant',None)=='elev':
             if zoomlevel>8: zoomlevel=8
         else:            
             if zoomlevel>13: zoomlevel=13
         merc_x,merc_y=mapper.latlon2merc(latlon,zoomlevel)
         
     merc_limx1,merc_limy1,merc_limx2,merc_limy2=merc_limits(zoomlevel,conservative=False,hd=True)
     if merc_x>merc_limx2: merc_x=merc_limx2
     if merc_y>merc_limy2: merc_y=merc_limy2
     if merc_x<merc_limx1: merc_x=merc_limx1
     if merc_y<merc_limy1: merc_y=merc_limy1
 
     session['last_pos']=(merc_x,merc_y)
     session['zoom']=zoomlevel
     
     print "Setting pos to %s, zoom = %d"%(mapper.merc2latlon(session['last_pos'],zoomlevel),zoomlevel)
     session.save()
Beispiel #4
0
    def weather(self):
        dummy,routes=get_route(tripuser(),request.params['tripname'])

        ret=[]
        alts=request.params.get('alts','')
        if alts==None:
            altvec=[]
        else:
            altvec=alts.split(",")
        for route,altitude in zip(routes,altvec):
             #print("Looking for waypoint: %s"%(way.pos,))
             try:
                mapper.parse_elev(altitude)
             except mapper.NotAnAltitude,cause:
                 ret.append(['',''])                 
                 continue #skip this alt
             #N+1 selects....
             merc1=mapper.latlon2merc(mapper.from_str(route.a.pos),14)
             merc2=mapper.latlon2merc(mapper.from_str(route.a.pos),14)
             center=(0.5*(merc1[0]+merc2[0]),0.5*(merc1[1]+merc2[1]))
             lat,lon=mapper.merc2latlon(center,14)
             #print "Fetching weather for %s,%s, %s"%(lat,lon,route.altitude)
             when=route.depart_dt+(route.arrive_dt-route.depart_dt)/2
             dummy1,dummy2,we=gfs_weather.get_prognosis(when)
             if we==None:
                 return ""; #Fail completely we don't have the weather here. We only succeed if we have weather for all parts of the journey.
             else:
                 try:
                     wi=we.get_wind(lat,lon,mapper.parse_elev(altitude))
                 except:
                     print traceback.format_exc()
                     return ""
                 #print "Got winds:",wi
                 ret.append([wi['direction'],wi['knots']])
Beispiel #5
0
    def weather(self):
        dummy, routes = get_route(tripuser(), request.params['tripname'])

        ret = []
        alts = request.params.get('alts', '')
        if alts == None:
            altvec = []
        else:
            altvec = alts.split(",")
        for route, altitude in zip(routes, altvec):
            #print("Looking for waypoint: %s"%(way.pos,))
            try:
                mapper.parse_elev(altitude)
            except mapper.NotAnAltitude, cause:
                ret.append(['', ''])
                continue  #skip this alt
            #N+1 selects....
            merc1 = mapper.latlon2merc(mapper.from_str(route.a.pos), 14)
            merc2 = mapper.latlon2merc(mapper.from_str(route.a.pos), 14)
            center = (0.5 * (merc1[0] + merc2[0]), 0.5 * (merc1[1] + merc2[1]))
            lat, lon = mapper.merc2latlon(center, 14)
            #print "Fetching weather for %s,%s, %s"%(lat,lon,route.altitude)
            when = route.depart_dt + (route.arrive_dt - route.depart_dt) / 2
            dummy1, dummy2, we = gfs_weather.get_prognosis(when)
            if we == None:
                return ""
                #Fail completely we don't have the weather here. We only succeed if we have weather for all parts of the journey.
            else:
                try:
                    wi = we.get_wind(lat, lon, mapper.parse_elev(altitude))
                except:
                    print traceback.format_exc()
                    return ""
                #print "Got winds:",wi
                ret.append([wi['direction'], wi['knots']])
Beispiel #6
0
 def draw_cmds():
     for d in ad['physical']:
         yield (mapper.latlon2merc(mapper.from_str(getpos(d[0])),
                                   20),
                mapper.latlon2merc(mapper.from_str(getpos(d[1])),
                                   20), d[0]['name'], d[1]['name'],
                d[0]['threshold'], d[1]['threshold'])
Beispiel #7
0
    def set_pos_zoom(self, latlon=None, zoom=None):
        #print "Setting pos to %s"%(latlon,)
        if latlon == None:
            assert zoom == None
            zoomlevel = session.get('zoom', None)
            if zoomlevel == None:
                zoomlevel = 5
                merc_x, merc_y = mapper.latlon2merc((58, 18), zoomlevel)
            else:
                merc_x, merc_y = session['last_pos']
        else:
            assert zoom != None
            zoomlevel = zoom
            if zoomlevel < 5:
                zoomlevel = 5
            if session.get('mapvariant', None) == 'elev':
                if zoomlevel > 8: zoomlevel = 8
            else:
                if zoomlevel > 13: zoomlevel = 13
            merc_x, merc_y = mapper.latlon2merc(latlon, zoomlevel)

        merc_limx1, merc_limy1, merc_limx2, merc_limy2 = merc_limits(
            zoomlevel, conservative=False, hd=True)
        if merc_x > merc_limx2: merc_x = merc_limx2
        if merc_y > merc_limy2: merc_y = merc_limy2
        if merc_x < merc_limx1: merc_x = merc_limx1
        if merc_y < merc_limy1: merc_y = merc_limy1

        session['last_pos'] = (merc_x, merc_y)
        session['zoom'] = zoomlevel

        print "Setting pos to %s, zoom = %d" % (mapper.merc2latlon(
            session['last_pos'], zoomlevel), zoomlevel)
        session.save()
Beispiel #8
0
def get_airspaces_on_line(latlon1,latlon2):
    px1,py1=mapper.latlon2merc(latlon1,13)
    px2,py2=mapper.latlon2merc(latlon2,13)
    bb0=BoundingBox(min(px1,px2),min(py1,py2),max(px1,px2),max(py1,py2))
    airsp=list(cache.get_airspaces_in_bb(bb0))
    #print "Intsersecting with",list([a[1]['name'] for a in airsp])
    spaces=get_polygons_on_line2(latlon1,latlon2,airsp)
    return spaces
Beispiel #9
0
def follow_along(context, start, end, longwayround=False):
    out = []
    for merc in follow_along13(context,
                               mapper.latlon2merc(start, 13),
                               mapper.latlon2merc(end, 13),
                               longwayround=longwayround):
        out.append(mapper.merc2latlon(merc, 13))
    return out
Beispiel #10
0
def get_sigpoints(lat,lon,zoomlevel):
    clickx,clicky=mapper.latlon2merc((lat,lon),13)
    rad=8<<(13-zoomlevel)
    bb=BoundingBox(clickx-rad,clicky-rad,clickx+rad,clicky+rad)
    out=[]
    for sigp in cache.get_sig_points_in_bb(bb):
        x,y=mapper.latlon2merc(mapper.from_str(sigp['pos']),zoomlevel)
        d=(clickx-x)**2+(clicky-y)**2
        out.append((d,sigp))
    return [sigp for d,sigp in sorted(out)]
Beispiel #11
0
def get_notampoints(lat,lon,zoomlevel):
    clickx,clicky=mapper.latlon2merc((lat,lon),zoomlevel)
    for kind,items in get_notam_objs_cached().items():
        if kind!="areas":
            for item in items:            
                x,y=mapper.latlon2merc(mapper.from_str(item['pos']),zoomlevel)
                radius=10
                d=(clickx-x)**2+(clicky-y)**2
                if d<=(radius)**2:
                   yield item
Beispiel #12
0
def get_polygons_on_line2(latlon1,latlon2,polyspaces):
    zoomlevel=13
    px1,py1=mapper.latlon2merc(latlon1,zoomlevel)
    px2,py2=mapper.latlon2merc(latlon2,zoomlevel)
    line=Line(Vertex(int(px1),int(py1)),Vertex(int(px2),int(py2)))
    crosses=[]
    for poly,space in polyspaces:                
        if len(poly.intersect_line(line))>0:
            crosses.append(space)
            #print "Is crossing"
        else:
            pass#print "Is NOT crossing"
    return crosses
Beispiel #13
0
def get_airfields(lat,lon,zoomlevel):
    clickx,clicky=mapper.latlon2merc((lat,lon),13)
    rad=10
    if zoomlevel>=10:
        rad<<=(zoomlevel-10)      
    rad<<=(13-zoomlevel)
    bb=BoundingBox(clickx-rad,clicky-rad,clickx+rad,clicky+rad)
    out=[]
    for airp in cache.get_airfields_in_bb(bb):
        x,y=mapper.latlon2merc(mapper.from_str(airp['pos']),zoomlevel)
        d=(clickx-x)**2+(clicky-y)**2
        out.append((d,airp))
    return [airp for d,airp in sorted(out)]
def get_all_tiles_near(routes,zoomlevel,dist_nm,tilesize):
    resultset=set()
    for rt in routes:
        m1=mapper.latlon2merc(mapper.from_str(rt.a.pos),zoomlevel)
        m2=mapper.latlon2merc(mapper.from_str(rt.b.pos),zoomlevel)
        
        av=Vertex(int(m1[0]),int(m1[1]))
        bv=Vertex(int(m2[0]),int(m2[1]))
        l=Line(av,bv)
        startmerc=clampmerc(m1,tilesize)
        maxdist=mapper.approx_scale(startmerc,zoomlevel,dist_nm)
        maxdist+=3*tilesize/2
        fill(l,startmerc,zoomlevel=zoomlevel,maxdist=maxdist,tilesize=tilesize,result=resultset)
    return resultset
def verify(src, zoomlevel):
    limitx1, limity1 = mapper.latlon2merc((63, 15), zoomlevel)
    limitx1 = int(limitx1)
    limity1 = int(limity1)
    tilesizemask = tilesize - 1
    limitx1 &= ~tilesizemask
    limity1 &= ~tilesizemask
    srcblob = BlobFile(src + "%d" % (zoomlevel,), tilesize=tilesize)
    f = 16
    im = Image.new("RGB", (f * tilesize, f * tilesize))
    basey = 0
    for by in xrange(limity1, limity1 + f * tilesize, tilesize):
        basex = 0
        print "DOne: %f" % (basey / float(f * tilesize))
        for bx in xrange(limitx1, limitx1 + f * tilesize, tilesize):
            b = srcblob.get_tile(bx, by)
            if b == None:
                print "NO tile at ", bx, by
                basex += tilesize
                continue
            print "found tile at ", bx, by
            assert len(b) == 4 * tilesize * tilesize
            fi = StringIO(b)
            for i in xrange(tilesize):
                for j in xrange(tilesize):
                    # lo=unpack(">h",fi.read(2))[0]
                    hi = unpack(">h", fi.read(2))[0]
                    im.putpixel((basex + j, basey + i), (hi / 6, hi / 6, hi / 6.0))
            basex += tilesize
        basey += tilesize
    im.save("out-%d.png" % (zoomlevel,))
Beispiel #16
0
def follow_along13(context, start, end, longwayround=False):
    if type(context) == list:
        borders = [[
            mapper.latlon2merc(mapper.from_str(x), 13) for x in points
        ] for points in context]
    else:
        borders = get_borders(context)
    print "start,end", start, end
    part1, idx1, pos1 = find_closest(borders, start)
    part2, idx2, pos2 = find_closest(borders, end)
    print "Found", pos1, pos2
    if part1 != part2:
        raise Exception("Start and endpoint are not on same island!")
    part = part1
    print "from,to", idx1, idx2
    if idx1 == idx2:
        return [start, end]
    res1, dist1 = circle(borders[part], pos1, idx1, idx2, pos2, -1)
    res2, dist2 = circle(borders[part], pos1, idx1, idx2, pos2, 1)
    if dist1 < dist2:
        if longwayround:
            ret = res2
        else:
            ret = res1
    else:
        if longwayround:
            ret = res1
        else:
            ret = res2
    return [start] + ret + [end]
Beispiel #17
0
def clean_up_polygon(poss):
    print "Clean poly:", poss

    def tov(merc):
        return Vertex(int(merc[0]), int(merc[1]))

    def fromv(v):
        return (v.get_x(), v.get_y())

    vertices = []
    last = None
    for pos in poss:
        #print pos
        if pos == last: continue
        last = pos
        vertices.append(tov(mapper.latlon2merc(mapper.from_str(pos), 13)))
    poly = Polygon(vvector(vertices))
    #print "calling tidy-up"
    shape = tidy_up_polygon(poly)
    ret = []
    for poly in shape.get_polys():
        #print "Got poly"
        vs = poly.get_vertices()
        out = []
        for v in vs:
            out.append(mapper.to_str(mapper.merc2latlon(fromv(v), 13)))
        ret.append(out)
    return ret
def verify(src, zoomlevel):
    limitx1, limity1 = mapper.latlon2merc((63, 15), zoomlevel)
    limitx1 = int(limitx1)
    limity1 = int(limity1)
    tilesizemask = tilesize - 1
    limitx1 &= ~tilesizemask
    limity1 &= ~tilesizemask
    srcblob = BlobFile(src + "%d" % (zoomlevel, ), tilesize=tilesize)
    f = 16
    im = Image.new("RGB", (f * tilesize, f * tilesize))
    basey = 0
    for by in xrange(limity1, limity1 + f * tilesize, tilesize):
        basex = 0
        print "DOne: %f" % (basey / float(f * tilesize))
        for bx in xrange(limitx1, limitx1 + f * tilesize, tilesize):
            b = srcblob.get_tile(bx, by)
            if b == None:
                print "NO tile at ", bx, by
                basex += tilesize
                continue
            print "found tile at ", bx, by
            assert len(b) == 4 * tilesize * tilesize
            fi = StringIO(b)
            for i in xrange(tilesize):
                for j in xrange(tilesize):
                    #lo=unpack(">h",fi.read(2))[0]
                    hi = unpack(">h", fi.read(2))[0]
                    im.putpixel((basex + j, basey + i),
                                (hi / 6, hi / 6, hi / 6.0))
            basex += tilesize
        basey += tilesize
    im.save("out-%d.png" % (zoomlevel, ))
 def get_airspaces(routes):
     for routename,coords,altspec in routes:
         sig=getsig(coords,altspec)
         if (routename,sig) in predef:
             #pobj=None
             #for sroutename,ssig in predef:
             #    if routename==sroutename:
             pobj=(routename,sig)
             width_nm,floor,ceiling,coordstr=predef[pobj]
             rawcoords=re.findall(ur"(\d{6}N)\s*(\d{7}E)",coordstr)
             coords=[mapper.latlon2merc(mapper.from_str(mapper.parse_coords(lats,lons)),13) for lats,lons in rawcoords]
             width=float(mapper.approx_scale(coords[0],13,1.25*width_nm))
             try:
                 outline=get_outline(coords,width)
             except Exception:
                 uprint(u"Trouble parsing %s"%(routename,))
                 raise
             yield dict(name=routename,
                 floor=floor,
                 ceiling=ceiling,
                 freqs=[],
                 type="RNAV",
                 points=[mapper.to_str(mapper.merc2latlon(x,13)) for x in outline])
         else:
             uprint("Need to have predefine for route %s, with md5: %s"%(routename,sig))
             uprint("Altitude, and points")
             raise Exception('Missing predef for route. Use: ("%s","%s") : ( 10,"FL 65","FL 95","""\n\n    """),'%(routename,sig))
Beispiel #20
0
def get_stuff_near_route(rts,items,dist,vertdist):
    for item in items:
        try:
            itemmerc=mapper.latlon2merc(mapper.from_str(item['pos']),13)
        except Exception:
            print "Bad coord:",item['pos']
            continue
        itemv=Vertex(int(itemmerc[0]),int(itemmerc[1]))
        onenm=mapper.approx_scale(itemmerc,13,1.0)
        for rt in rts:
            if rt.dt==None: continue
            #print "========================================="
            av=Vertex(int(rt.subposa[0]),int(rt.subposa[1]))
            bv=Vertex(int(rt.subposb[0]),int(rt.subposb[1]))
            l=Line(av,bv)
            linelen=(bv-av).approxlength()
            actualclosest=l.approx_closest(itemv)
            #print item['name'],"A: ",av,"B: ",bv,"clo:",actualclosest
            actualdist=(actualclosest-itemv).approxlength()/onenm
            #print "Actualdist: ",actualdist
            ls=(actualclosest-av).approxlength()
            #print "Length from start:",ls
            #print "Linelen:",linelen
            if linelen>1e-3:
                along=ls/linelen
            else:
                along=0
            #print "Along:",along
            #print "Startalt:",rt.startalt," endalt: ",rt.endalt
            alongnm=rt.d*along
            alongnm_a=rt.relstartd+alongnm
            #print "NM from ",rt.a.waypoint," is ",alongnm_a
            closealt=rt.startalt+(rt.endalt-rt.startalt)*along
            #print "Altitude at point: ",closealt, " before: ",rt.a.waypoint,rt.b.waypoint
            altmargin=0
            if 'elev' in item:
                itemalt=mapper.parse_elev(item['elev'])
                altmargin=closealt-itemalt
            else:
                itemalt=None
                altmargin=0
            if actualdist<dist and altmargin<vertdist:
                bear=mapper.approx_bearing_vec(actualclosest,itemv)            
                d=dict(item)
                #print "Yielding."
                d['name']=d['kind']+': ' +d['name']
                d['dist_from_a']=alongnm_a
                d['dist_from_b']=rt.outer_d-alongnm_a
                d['dir_from_a']=describe_dir(rt.tt)
                d['dir_from_b']=describe_dir((rt.tt+180.0)%360.0)
                d['dist']=actualdist
                d['bearing']=bear
                d['elevf']=itemalt
                if itemalt!=None:
                    d['vertmargin']=altmargin
                d['closestalt']=closealt
                d['a']=rt.a
                d['b']=rt.b
                d['id']=rt.a.id
                yield d
Beispiel #21
0
def follow_along13(context,start,end,longwayround=False):
    if type(context)==list:
        borders=[[mapper.latlon2merc(mapper.from_str(x),13) for x in points] for points in context]
    else:
        borders=get_borders(context)
    print "start,end",start,end
    part1,idx1,pos1=find_closest(borders,start)
    part2,idx2,pos2=find_closest(borders,end)
    print "Found",pos1,pos2
    if part1!=part2: raise Exception("Start and endpoint are not on same island!")
    part=part1
    print "from,to",idx1,idx2
    if idx1==idx2:
        return [start,end]
    res1,dist1=circle(borders[part],pos1,idx1,idx2,pos2,-1)
    res2,dist2=circle(borders[part],pos1,idx1,idx2,pos2,1)
    if dist1<dist2:
        if longwayround:
            ret=res2
        else:
            ret=res1
    else:
        if longwayround:
            ret=res1
        else:
            ret=res2        
    return [start]+ret+[end]
Beispiel #22
0
def clean_up_polygon(poss):
    print "Clean poly:",poss
    def tov(merc):
        return Vertex(int(merc[0]),int(merc[1]))
    def fromv(v):
        return (v.get_x(),v.get_y())
    vertices=[]
    last=None
    for pos in poss:
        #print pos
        if pos==last: continue
        last=pos
        vertices.append(tov(mapper.latlon2merc(mapper.from_str(pos),13)))
    poly=Polygon(vvector(vertices))
    #print "calling tidy-up"
    shape=tidy_up_polygon(poly)
    ret=[]
    for poly in shape.get_polys():
        #print "Got poly"
        vs=poly.get_vertices()
        out=[]
        for v in vs:
            out.append(mapper.to_str(mapper.merc2latlon(fromv(v),13)))
        ret.append(out)
    return ret
Beispiel #23
0
def get_pixel_radius(o,zoomlevel):
    merc=mapper.latlon2merc(mapper.from_str(o['pos']),zoomlevel)
    draw_radius_nm=(int(o['height'])*2.0*0.16e-3)
    draw_radius_pixels=mapper.approx_scale(merc,zoomlevel,draw_radius_nm)
    radius=draw_radius_pixels
    if radius<4:
        radius=4
    return radius
Beispiel #24
0
def get_latlon_outline(latlonseq,width_nm):
    print "Width nm:",width_nm
    mercseq=[mapper.latlon2merc(mapper.from_str(ll),13) for ll in latlonseq]
    width=float(mapper.approx_scale(mercseq[0],13,width_nm))    
    
    mercout=get_merc_outline(mercseq,width)
    
    points=[mapper.to_str(mapper.merc2latlon(x,13)) for x in mercout]
    return points    
Beispiel #25
0
def get_weather(lat,lon):
    zoomlevel=13
    px,py=mapper.latlon2merc((lat,lon),zoomlevel)
    w=Weather()
    areas=weather_chart_areas.get_areas()
    insides=[]
    dists=[]
    
    for name,area in areas.items():
        poly_coords=[]
        centerx=0.0
        centery=0.0
        for coord in area:
            x,y=mapper.latlon2merc(coord,zoomlevel)
            centerx+=x+0.0
            centery+=y+0.0
            poly_coords.append(Vertex(int(x),int(y)))
        if len(poly_coords)<3:
            print "Weather area %s has few points: %s "%(name,area)
            continue
        centerx/=len(poly_coords)
        centery/=len(poly_coords)
        cdist=(centerx-px)**2+(centery-py)**2
        poly=Polygon(vvector(poly_coords))
        if poly.is_inside(Vertex(int(px),int(py))):
            cdist*=1e-3
        insides.append((cdist,name,area))
    #print "insides:",insides
    insides.sort()
    dist,name,area=insides[0]
    if dist>20000**2:        
        return None        
    w.weather_area=name
    
    mainarea,rest=name.split("_")
    part=rest[:-2]
    seg=rest[-2:]
    
    try:
        fc=get_parsed_weather()
    except Exception,cause:
        print "Couldn't fetch weather: ",cause #there's no weather service at certain times.
        return None
Beispiel #26
0
def get_weather(lat, lon):
    zoomlevel = 13
    px, py = mapper.latlon2merc((lat, lon), zoomlevel)
    w = Weather()
    areas = weather_chart_areas.get_areas()
    insides = []
    dists = []

    for name, area in areas.items():
        poly_coords = []
        centerx = 0.0
        centery = 0.0
        for coord in area:
            x, y = mapper.latlon2merc(coord, zoomlevel)
            centerx += x + 0.0
            centery += y + 0.0
            poly_coords.append(Vertex(int(x), int(y)))
        if len(poly_coords) < 3:
            print "Weather area %s has few points: %s " % (name, area)
            continue
        centerx /= len(poly_coords)
        centery /= len(poly_coords)
        cdist = (centerx - px)**2 + (centery - py)**2
        poly = Polygon(vvector(poly_coords))
        if poly.is_inside(Vertex(int(px), int(py))):
            cdist *= 1e-3
        insides.append((cdist, name, area))
    #print "insides:",insides
    insides.sort()
    dist, name, area = insides[0]
    if dist > 20000**2:
        return None
    w.weather_area = name

    mainarea, rest = name.split("_")
    part = rest[:-2]
    seg = rest[-2:]

    try:
        fc = get_parsed_weather()
    except Exception, cause:
        print "Couldn't fetch weather: ", cause  #there's no weather service at certain times.
        return None
def run(path):
    f = open(path)
    lines = list(f)
    calib = None
    for line in lines:
        if line.strip() == "": continue
        name, coords = parse_line(line)
        if name.count("(") == 1 and name.count(")") == 1:
            #print "Calib:",name,coords
            assert calib == None  #only one calibration line per file, please
            dummy, rest = name.split("(")
            assert rest.endswith(")")
            rest = rest[:-1]
            geo_points = []
            for c_str in rest.split("-"):
                geo_point = []
                for comp_str in c_str.split(","):
                    geo_point.append(float(comp_str.strip()))

                geo_points.append(
                    tuple(
                        mapper.latlon2merc((geo_point[0], geo_point[1]),
                                           zoomlevel)))
            assert len(geo_points) == 2
            #print "Geo_points:",geo_points
            #print "Coords:",coords
            geo_dist = vec_len(vec_sub(*geo_points))
            coord_dist = vec_len(vec_sub(*coords))
            geo_angle = get_angle(vec_sub(geo_points[1], geo_points[0]))
            coord_angle = get_angle(vec_sub(coords[1], coords[0]))
            ##print "Geo angle: %f"%(geo_angle*180.0/math.pi)
            #print "Coord angle: %f"%(coord_angle*180.0/math.pi)

            coord_offset = vec_sub(geo_points[0], coords[0])

            calib = dict(center_coord=coords[0],
                         center_geo_points=geo_points[0],
                         rotate=geo_angle - coord_angle,
                         scale=float(geo_dist) / float(coord_dist))
    assert calib != None
    #print calib
    ret = dict()
    for line in lines:
        if line.strip() == "": continue
        name, coords = parse_line(line)
        #if name.count("(")!=1 or name.count(")")!=1:
        geo_points = []
        for cd in coords:
            geo_points.append(fixup(cd, calib))

        ret[name] = [mapper.merc2latlon(c, zoomlevel) for c in geo_points]
        #print "Coords: %s, geo points: %s"%(coords,geo_points)
        #print name,":","; ".join(format_latlon(mapper.merc2latlon(c,zoomlevel)) for c in geo_points)

    return ret
Beispiel #28
0
def get_polygons_around(lat,lon,polys):
    zoomlevel=13
    px,py=mapper.latlon2merc((lat,lon),zoomlevel)
    insides=[]
    for space in polys:                
        poly_coords=[]
        for coord in space['points']:
            x,y=mapper.latlon2merc(mapper.from_str(coord),zoomlevel)
            poly_coords.append(Vertex(int(x),int(y)))
        if len(poly_coords)<3:
            #print "Space %s has few points: %s "%(space['name'],space['points'])
            continue
        poly=Polygon(vvector(poly_coords))
        #print "Checking if inside poly:",space
        if poly.is_inside(Vertex(int(px),int(py))):
            insides.append(space)
            #print "Is inside"
        else:
            pass#print "Is NOT inside"
    return insides
Beispiel #29
0
def get_obstacles(lat,lon,zoomlevel):
    clickx,clicky=mapper.latlon2merc((lat,lon),13)
    rad=8
    if zoomlevel>=11:
        rad+=(zoomlevel-11)*6
        
    rad<<=(13-zoomlevel)
    bb=BoundingBox(clickx-rad,clicky-rad,clickx+rad,clicky+rad)
    #print "Looking for stuff in bb",bb
    for obst in cache.get_obstacles_in_bb(bb):
        #print "Got obstacle ",obst
        yield obst
Beispiel #30
0
def get_terrain_elev_in_box_approx(latlon,nautmiles):
    #nautmiles/=2
    zoomlevel=8
    merc_=mapper.latlon2merc(latlon,zoomlevel)
    merc=(int(merc_[0]),int(merc_[1]))
    pixels=mapper.approx_scale(merc, zoomlevel, nautmiles)
    #print "Num pixels on zoomlevel 8",pixels," naut",nautmiles
    del merc
    del merc_
    while pixels>4 and zoomlevel>0:
        zoomlevel-=1
        pixels/=2
        #print "Pixels on zoom",zoomlevel,": ",pixels
    pixels=int(pixels+0.5)
    if pixels<=1: pixels=1
    if zoomlevel>=8: zoomlevel=8

    merc_=mapper.latlon2merc(latlon,zoomlevel)
    merc=(int(merc_[0]),int(merc_[1]))
    #print "Getting terrain zoomlevel ",zoomlevel
    return get_terrain_elev_merc(merc,zoomlevel,(pixels,pixels))
Beispiel #31
0
def get_terrain_elev_in_box_approx(latlon, nautmiles):
    #nautmiles/=2
    zoomlevel = 8
    merc_ = mapper.latlon2merc(latlon, zoomlevel)
    merc = (int(merc_[0]), int(merc_[1]))
    pixels = mapper.approx_scale(merc, zoomlevel, nautmiles)
    #print "Num pixels on zoomlevel 8",pixels," naut",nautmiles
    del merc
    del merc_
    while pixels > 4 and zoomlevel > 0:
        zoomlevel -= 1
        pixels /= 2
        #print "Pixels on zoom",zoomlevel,": ",pixels
    pixels = int(pixels + 0.5)
    if pixels <= 1: pixels = 1
    if zoomlevel >= 8: zoomlevel = 8

    merc_ = mapper.latlon2merc(latlon, zoomlevel)
    merc = (int(merc_[0]), int(merc_[1]))
    #print "Getting terrain zoomlevel ",zoomlevel
    return get_terrain_elev_merc(merc, zoomlevel, (pixels, pixels))
def run(path):
    f=open(path)
    lines=list(f)
    calib=None
    for line in lines:
        if line.strip()=="": continue
        name,coords=parse_line(line)
        if name.count("(")==1 and name.count(")")==1:
            #print "Calib:",name,coords
            assert calib==None #only one calibration line per file, please
            dummy,rest=name.split("(")
            assert rest.endswith(")")
            rest=rest[:-1]
            geo_points=[]
            for c_str in rest.split("-"):
                geo_point=[]
                for comp_str in c_str.split(","):
                    geo_point.append(float(comp_str.strip()))

                geo_points.append(tuple(mapper.latlon2merc((geo_point[0],geo_point[1]),zoomlevel)))
            assert len(geo_points)==2
            #print "Geo_points:",geo_points
            #print "Coords:",coords
            geo_dist=vec_len(vec_sub(*geo_points))
            coord_dist=vec_len(vec_sub(*coords))
            geo_angle=get_angle(vec_sub(geo_points[1],geo_points[0]))
            coord_angle=get_angle(vec_sub(coords[1],coords[0]))
            ##print "Geo angle: %f"%(geo_angle*180.0/math.pi)
            #print "Coord angle: %f"%(coord_angle*180.0/math.pi)

            coord_offset=vec_sub(geo_points[0],coords[0])

            calib=dict(
                center_coord=coords[0],
                center_geo_points=geo_points[0],
                rotate=geo_angle-coord_angle,
                scale=float(geo_dist)/float(coord_dist))
    assert calib!=None
    #print calib
    ret=dict()
    for line in lines:
        if line.strip()=="": continue
        name,coords=parse_line(line)
        #if name.count("(")!=1 or name.count(")")!=1:
        geo_points=[]
        for cd in coords:
            geo_points.append(fixup(cd,calib))
        
        ret[name]=[mapper.merc2latlon(c,zoomlevel) for c in geo_points]
        #print "Coords: %s, geo points: %s"%(coords,geo_points)
        #print name,":","; ".join(format_latlon(mapper.merc2latlon(c,zoomlevel)) for c in geo_points)
    
    return ret
Beispiel #33
0
def filter_bad_airfields(bad,good):
    toadd=[]
    try:
        bspitems=[]
        for item in good:
            bspitems.append(BspTree.Item(                                           
                mapper.latlon2merc(mapper.from_str(item['pos']),13),item) )
        bsp=BspTree(bspitems)
        for abad in bad:
            m=mapper.latlon2merc(mapper.from_str(abad['pos']),13)
            twonm=mapper.approx_scale(m,13,2)   
            bb=BoundingBox(m[0],m[1],m[0],m[1]).expanded(twonm)
            
            for ap in bsp.findall_in_bb(bb):
                print "Not adding bad airfield:",ap.val['name']
                break
            else:
                toadd.append(abad)
    except:
        print "Failed to add bad airfields"
        raise
    return toadd
Beispiel #34
0
def get_fir_crossing(latlon1,latlon2):
    """
    Returns tuple of: 
     * airspace-dict
     * latlon of crossing
    """
    px1,py1=mapper.latlon2merc(latlon1,13)
    px2,py2=mapper.latlon2merc(latlon2,13)
    bb0=BoundingBox(min(px1,px2),min(py1,py2),max(px1,px2),max(py1,py2))
    line=Line(Vertex(int(px1),int(py1)),Vertex(int(px2),int(py2)))
    for poly,space in cache.get_firs_in_bb(bb0):
        a=poly.is_inside(Vertex(int(px1),int(py1)))
        b=poly.is_inside(Vertex(int(px2),int(py2)))
        print "Considering space %s, starting: %s, ending: %s"%(
                space['name'],a,b)
        
        if b and not a: 
            cross=list(poly.first_entrance(line))
            if cross:
                outlatlon=(cross[0].get_x(),cross[0].get_y())
                return space,mapper.merc2latlon(outlatlon,13)
    return None
Beispiel #35
0
def get_polygons_on_line(latlon1,latlon2,polys):
    zoomlevel=13
    px1,py1=mapper.latlon2merc(latlon1,zoomlevel)
    px2,py2=mapper.latlon2merc(latlon2,zoomlevel)
    line=Line(Vertex(int(px1),int(py1)),Vertex(int(px2),int(py2)))
    crosses=[]
    for space in polys:                
        poly_coords=[]
        for coord in space['points']:
            x,y=mapper.latlon2merc(mapper.from_str(coord),zoomlevel)
            poly_coords.append(Vertex(int(x),int(y)))
        if len(poly_coords)<3:
            #print "Space %s has few points: %s "%(space['name'],space['points'])
            continue
        poly=Polygon(vvector(poly_coords))
        #print "Checking if intersect poly:",space
        if len(poly.intersect_line(line))>0:
            crosses.append(space)
            #print "Is crossing"
        else:
            pass#print "Is NOT crossing"
    return crosses
Beispiel #36
0
def get_polygons_around2(lat,lon,polyspaces):
    """for Polygon,Space-pairs"""
    zoomlevel=13
    px,py=mapper.latlon2merc((lat,lon),zoomlevel)
    insides=[]
    for polyspace in polyspaces:                
        poly,space=polyspace
        #print "Checking if inside poly:",space
        if poly.is_inside(Vertex(int(px),int(py))):
            insides.append(space)
            #print "Is inside"
        else:
            pass#print "Is NOT inside"
    return insides
Beispiel #37
0
def merc_limits(zoomlevel,conservative=False,hd=False):
    def ints(xs): return [int(x) for x in xs]
    if (zoomlevel,conservative,hd) in mlim:
        return mlim[(zoomlevel,conservative,hd)]
    if hd:
        lat1,lon1,lat2,lon2=latlon_limits_hd()
    else:
        lat1,lon1,lat2,lon2=latlon_limits()
    limitx1,limity1=ints(mapper.latlon2merc((lat2,lon1),zoomlevel))
    limitx2,limity2=ints(mapper.latlon2merc((lat1,lon2),zoomlevel))
    if conservative:
        mlim[(zoomlevel,conservative,hd)]=(limitx1,limity1,limitx2,limity2)
        return limitx1,limity1,limitx2,limity2
    else:
        tilesize=256
        tilesizemask=tilesize-1
        limitx1&=~tilesizemask
        limity1&=~tilesizemask
        limitx2&=~tilesizemask
        limity2&=~tilesizemask
        limitx2+=tilesize
        limity2+=tilesize
        mlim[(zoomlevel,conservative,hd)]=(limitx1,limity1,limitx2,limity2)
        return limitx1,limity1,limitx2,limity2
Beispiel #38
0
def filter_bad_airfields(bad, good):
    toadd = []
    try:
        bspitems = []
        for item in good:
            bspitems.append(
                BspTree.Item(
                    mapper.latlon2merc(mapper.from_str(item['pos']), 13),
                    item))
        bsp = BspTree(bspitems)
        for abad in bad:
            m = mapper.latlon2merc(mapper.from_str(abad['pos']), 13)
            twonm = mapper.approx_scale(m, 13, 2)
            bb = BoundingBox(m[0], m[1], m[0], m[1]).expanded(twonm)

            for ap in bsp.findall_in_bb(bb):
                print "Not adding bad airfield:", ap.val['name']
                break
            else:
                toadd.append(abad)
    except:
        print "Failed to add bad airfields"
        raise
    return toadd
Beispiel #39
0
 def invent_matrix(self,cksum,variant):
     print "Variant:",variant
     for ad in ec.get_airfields():
         if not 'adcharts' in ad: continue
         dbb=False
         for adchart in ad['adcharts'].values():
             if adchart['checksum']==cksum:
                 lat,lon=mapper.from_str(ad['pos'])
                 w,h=adchart['render_width'],adchart['render_height']
                 print "adpos:",ad['pos'],lat,lon
                 dbb=True
                 break
         if dbb:break
     else:
         raise Exception("Can't find this chart in aipdata")
     
   
     
     
     if variant.lower().count('vac'):
         mercsizex=w
         mercsizey=h
         scale=7
     else:
         mercsizex=w
         mercsizey=h
         scale=1
     
     print "lat,lon",lat,lon
     m1=mapper.latlon2merc((lat,lon),13)
     print "corner merc",m1
     ns=[]
     for offx,offy in [(0,0),
                       (mercsizex,0),
                       (0,mercsizey),
                       (mercsizex,mercsizey)]:
         merc2=(m1[0]+(offx-mercsizex/2)*scale,m1[1]+(offy-mercsizey/2)*scale)
         n=AirportMarker()
         n.latitude,n.longitude=mapper.merc2latlon(merc2,13)
         n.x,n.y=(offx,offy)
         ns.append(n)
     error,A,T=customproj.solve(ns)
     matrix=list(A)+list(T)            
     print "Fake projection:",matrix
     return matrix
Beispiel #40
0
    def invent_matrix(self, cksum, variant):
        print "Variant:", variant
        for ad in ec.get_airfields():
            if not 'adcharts' in ad: continue
            dbb = False
            for adchart in ad['adcharts'].values():
                if adchart['checksum'] == cksum:
                    lat, lon = mapper.from_str(ad['pos'])
                    w, h = adchart['render_width'], adchart['render_height']
                    print "adpos:", ad['pos'], lat, lon
                    dbb = True
                    break
            if dbb: break
        else:
            raise Exception("Can't find this chart in aipdata")

        if variant.lower().count('vac'):
            mercsizex = w
            mercsizey = h
            scale = 7
        else:
            mercsizex = w
            mercsizey = h
            scale = 1

        print "lat,lon", lat, lon
        m1 = mapper.latlon2merc((lat, lon), 13)
        print "corner merc", m1
        ns = []
        for offx, offy in [(0, 0), (mercsizex, 0), (0, mercsizey),
                           (mercsizex, mercsizey)]:
            merc2 = (m1[0] + (offx - mercsizex / 2) * scale,
                     m1[1] + (offy - mercsizey / 2) * scale)
            n = AirportMarker()
            n.latitude, n.longitude = mapper.merc2latlon(merc2, 13)
            n.x, n.y = (offx, offy)
            ns.append(n)
        error, A, T = customproj.solve(ns)
        matrix = list(A) + list(T)
        print "Fake projection:", matrix
        return matrix
Beispiel #41
0
def cleanup_poly(latlonpoints, name="?"):

    for minstep in [0, 10, 100, 1000, 10000, 100000]:
        mercpoints = []
        lastmerc = None
        for latlon in latlonpoints:
            merc = mapper.latlon2merc(latlon, 13)
            if lastmerc != None:
                dist = math.sqrt(
                    sum([(lastmerc[i] - merc[i])**2 for i in xrange(2)]))
                if dist < minstep:
                    continue
            if merc == lastmerc:
                continue
            lastmerc = merc
            mercpoints.append(Vertex(int(merc[0]), int(merc[1])))
        if len(mercpoints) < 50:
            break
    if len(mercpoints) <= 2: return None
    if mercpoints[0] == mercpoints[-1]:
        del mercpoints[-1]
    if len(mercpoints) <= 2: return None
    poly = Polygon(vvector(mercpoints))
    if len(mercpoints) == 4:
        swapped = [mercpoints[1], mercpoints[0]] + mercpoints[2:]
        swappedpoly = Polygon(vvector(swapped))
        #print "Found 4-corner area: ",name," areas:",swappedpoly.calc_area(),poly.calc_area()
        if abs(swappedpoly.calc_area()) > abs(1.1 * poly.calc_area()):
            print "Untwisting an area", name
            mercpoints = swapped
            poly = swappedpoly

    backtomerc = [
        mapper.merc2latlon((m.get_x(), m.get_y()), 13) for m in mercpoints
    ]
    if poly.is_ccw():
        return backtomerc
    else:
        #print "Reversed "+latlonpoints
        return reversed(backtomerc)
Beispiel #42
0
def get_borders(pcountry):
    #print "Getting for",pcountry
    global borders
    if not borders:
        if not os.path.exists("fplan/extract/lands.bin"):
            if os.system("bunzip2 fplan/extract/lands.bin.bz2") != 0:
                raise Exception("Couldn't unbzip2 lands.bin.bz2")
        f = open("fplan/extract/lands.bin")
        tborders = pickle.load(f)
        f.close()
        out = dict()
        for country, parts in tborders.items():
            outparts = []
            tot = 0
            for part in parts:
                outpart = []
                poly_coords = []
                last = None
                for coord in part:
                    merc = mapper.latlon2merc(mapper.from_str(coord), 13)
                    if merc == last: continue
                    last = merc
                    outpart.append(merc)
                    tot += 1
                    poly_coords.append(Vertex(int(merc[0]), int(merc[1])))
                assert len(outpart) >= 3
                if outpart[0] == outpart[-1]:
                    outpart = outpart[:-1]
                    poly_coords = poly_coords[:-1]
                poly = Polygon(vvector(poly_coords))
                assert poly.is_ccw()

                outparts.append(outpart)
            #print "Parts in ",country,len(outparts),tot
            out[country] = outparts
        borders = out
    #if pcountry!="sweden":
    #    raise Exception("Debug, just allow sweden for now. just remove this after.")
    return borders[pcountry]
Beispiel #43
0
def get_borders(pcountry):
    #print "Getting for",pcountry
    global borders
    if not borders:
        if not os.path.exists("fplan/extract/lands.bin"):
            if os.system("bunzip2 fplan/extract/lands.bin.bz2")!=0:
                raise Exception("Couldn't unbzip2 lands.bin.bz2")
        f=open("fplan/extract/lands.bin")
        tborders=pickle.load(f)
        f.close()
        out=dict()
        for country,parts in tborders.items():
            outparts=[]
            tot=0
            for part in parts:
                outpart=[]
                poly_coords=[]
                last=None
                for coord in part:
                    merc=mapper.latlon2merc(mapper.from_str(coord),13)
                    if merc==last: continue
                    last=merc
                    outpart.append(merc)
                    tot+=1
                    poly_coords.append(Vertex(int(merc[0]),int(merc[1])))
                assert len(outpart)>=3
                if outpart[0]==outpart[-1]:
                    outpart=outpart[:-1]
                    poly_coords=poly_coords[:-1]
                poly=Polygon(vvector(poly_coords))
                assert poly.is_ccw()

                outparts.append(outpart)
            #print "Parts in ",country,len(outparts),tot
            out[country]=outparts
        borders=out
    #if pcountry!="sweden":
    #    raise Exception("Debug, just allow sweden for now. just remove this after.")
    return borders[pcountry]
Beispiel #44
0
def cleanup_poly(latlonpoints,name="?"):
    
    for minstep in [0,10,100,1000,10000,100000]:
        mercpoints=[]
        lastmerc=None
        for latlon in latlonpoints:
            merc=mapper.latlon2merc(latlon,13)
            if lastmerc!=None:
                dist=math.sqrt(sum([(lastmerc[i]-merc[i])**2 for i in xrange(2)]))
                if dist<minstep:
                    continue
            if merc==lastmerc:
                continue
            lastmerc=merc
            mercpoints.append(Vertex(int(merc[0]),int(merc[1])))
        if len(mercpoints)<50:
            break
    if len(mercpoints)<=2: return None
    if mercpoints[0]==mercpoints[-1]:
        del mercpoints[-1]
    if len(mercpoints)<=2: return None
    poly=Polygon(vvector(mercpoints))
    if len(mercpoints)==4:
        swapped=[mercpoints[1],mercpoints[0]]+mercpoints[2:]
        swappedpoly=Polygon(vvector(swapped))
        #print "Found 4-corner area: ",name," areas:",swappedpoly.calc_area(),poly.calc_area()
        if abs(swappedpoly.calc_area())>abs(1.1*poly.calc_area()):
            print "Untwisting an area",name
            mercpoints=swapped
            poly=swappedpoly
            
    backtomerc=[mapper.merc2latlon((m.get_x(),m.get_y()),13) for m in mercpoints]
    if poly.is_ccw():
        return backtomerc
    else:    
        #print "Reversed "+latlonpoints
        return reversed(backtomerc)