Exemplo n.º 1
0
    def load_ad_json(self, ac):
        out = []
        physical = []

        for rwy in ac['runways']:
            curphys = []
            for i, end in enumerate(rwy['ends']):
                endb = rwy['ends'][(i + 1) % 2]
                usable_pos = end.get("usable_pos", end['pos'])
                usable_posb = endb.get("usable_pos", endb['pos'])
                brg1, runway_dist = mapper.bearing_and_distance(
                    mapper.from_str(usable_pos), mapper.from_str(usable_posb))
                #brg2,landing_dist=mapper.bearing_afnd_distance(mapper.from_str(end['pos']),mapper.from_str(usable_posb))
                brgdummy, threshold_dist = mapper.bearing_and_distance(
                    mapper.from_str(usable_pos), mapper.from_str(end['pos']))
                out.append(
                    dict(name=end['thr'],
                         rwyhdg=brg1,
                         runway_length=runway_dist * 1852.0,
                         threshold=threshold_dist * 1852.0))
                curphys.append(
                    dict(name=end['thr'],
                         pos=end['pos'],
                         usable_pos=end.get("usable_pos", end['pos']),
                         threshold=threshold_dist * 1852.0))
            physical.append(curphys)
        jsonstr = json.dumps(dict(runways=out, physical=physical))
        print "JSON:", jsonstr
        return jsonstr
Exemplo n.º 2
0
 def load_ad_json(self,ac):
     out=[]
     physical=[]
 
     for rwy in ac['runways']:
         curphys=[]
         for i,end in enumerate(rwy['ends']):
             endb=rwy['ends'][(i+1)%2]
             usable_pos=end.get("usable_pos",end['pos'])
             usable_posb=endb.get("usable_pos",endb['pos'])
             brg1,runway_dist=mapper.bearing_and_distance(mapper.from_str(usable_pos),mapper.from_str(usable_posb))
             #brg2,landing_dist=mapper.bearing_afnd_distance(mapper.from_str(end['pos']),mapper.from_str(usable_posb))
             brgdummy,threshold_dist=mapper.bearing_and_distance(mapper.from_str(usable_pos),mapper.from_str(end['pos']))
             out.append(dict(
                 name=end['thr'],
                 rwyhdg=brg1,
                 runway_length=runway_dist*1852.0,
                 threshold=threshold_dist*1852.0                       
                 ))
             curphys.append(dict(
                     name=end['thr'],
                     pos=end['pos'],
                     usable_pos=end.get("usable_pos",end['pos']),
                     threshold=threshold_dist*1852.0))
         physical.append(curphys)
     jsonstr=json.dumps(dict(runways=out,physical=physical))
     print "JSON:",jsonstr
     return jsonstr
Exemplo n.º 3
0
def get_low_sun_near_route(rts):
    l=len(rts)
    out=[]
    dt=None
    for idx,rt in enumerate(rts):
        if rt.dt==None: continue
        #print "ord:",rt.a.ordering
        tottime=rt.dt-rt.startdt
        merca=rt.subposa
        mercb=rt.subposb
        curtime=timedelta(0)
        real_heading=rt.tt+rt.wca
        while True:
            if curtime>=tottime:
                break
            f=divide(curtime,tottime)
            fi=1.0-f
            merc=(fi*merca[0]+f*mercb[0],fi*merca[1]+f*mercb[1])
            latlon=mapper.merc2latlon(merc,13)        
            when=rt.startdt+curtime
            ele,azi=sun_position_in_sky(when,latlon[0],latlon[1])
            #print "Sun position: ele=%s, azi=%s, heading=%s"%(ele,azi,real_heading)
            if (ele>-0.5 and ele<25):
                off=(azi-real_heading)
                if abs(off)<25:
                    dirclock=int(round(off/15.0))
                    if dirclock<=0:
                        dirclock+=12
                    out.append(dict(
                        name="Low Sun Warning (Direction: %d o'clock, %.0f deg above horizon. Blinding?)"%(
                                dirclock,max(0,ele)),
                        pos=mapper.to_str(latlon),
                        elev="",
                        elevf=0,
                        dist=0,
                        bearing=azi,
                        closestalt=None,
                        kind='lowsun',
                        dist_from_a=mapper.bearing_and_distance(mapper.from_str(rt.a.pos),latlon)[1],
                        dist_from_b=mapper.bearing_and_distance(mapper.from_str(rt.b.pos),latlon)[1],
                        dir_from_a=describe_dir(rt.tt),
                        dir_from_b=describe_dir((rt.tt+180.0)%360.0),
                        a=rt.a,
                        b=rt.b,
                        id=rt.a.id))
                    print "Generated sun warning:",out[-1]
                    break
            curtime+=timedelta(minutes=2)
    return out
Exemplo n.º 4
0
 def parse_arc(line):
     db,rest=line.split(" ",1)
     assert db=="DB"
     c1,c2=rest.split(",")
     temp=[]
     temp.append(parse_rawcoord(c1))
     end=parse_rawcoord(c2)
     assert vars['center']
     
     bearing,radius=mapper.bearing_and_distance(mapper.parsecoord(vars['center']), mapper.parsecoord(end))
     temp.append("clockwise along an arc with radius %s NM centred on %s to the point %s"%((radius),vars['center'],end))
     #temp.append(end)
     coords.append(" ".join(temp))
Exemplo n.º 5
0
    def parse_arc(line):
        db, rest = line.split(" ", 1)
        assert db == "DB"
        c1, c2 = rest.split(",")
        temp = []
        temp.append(parse_rawcoord(c1))
        end = parse_rawcoord(c2)
        assert vars['center']

        bearing, radius = mapper.bearing_and_distance(
            mapper.parsecoord(vars['center']), mapper.parsecoord(end))
        temp.append(
            "clockwise along an arc with radius %s NM centred on %s to the point %s"
            % ((radius), vars['center'], end))
        #temp.append(end)
        coords.append(" ".join(temp))
Exemplo n.º 6
0
def get_user_trips(user):
    users = meta.Session.query(User).filter(User.user == user).all()
    if len(users) == 0:
        return []
    user, = users

    trips = meta.Session.query(Trip).filter(
        sa.and_(Trip.user == user.user)).order_by(Trip.trip).all()
    out = []
    for trip in trips:
        meta.Session.flush()
        try:
            #print "Processing trip",trip.trip
            tripobj = dict()
            tripobj['name'] = trip.trip
            tripobj['aircraft'] = trip.aircraft

            actypes = list(
                meta.Session.query(Aircraft).filter(
                    Aircraft.aircraft == trip.aircraft).all())
            if len(actypes) == 0:
                tripobj['atsradiotype'] = '?'
            else:
                tripobj['atsradiotype'] = actypes[0].atsradiotype

            waypoints = []

            def eitherf(x, fallback):
                try:
                    if x == None: return fallback
                    return float(x)
                except Exception:
                    return 0.0

            def da(x):
                try:
                    if x == None: return datetime(1970, 1, 1)
                    if type(x) == datetime: return x
                    return datetime(1970, 1, 1)
                except Exception:
                    return datetime(1970, 1, 1)

            def f(x):
                try:
                    if x == None: return 0.0
                    return float(x)
                except Exception:
                    return 0.0

            def i(x):
                try:
                    if x == None: return 0
                    return int(x)
                except Exception:
                    return 0

            def s(x):
                try:
                    if x == None: return ""
                    if type(x) == unicode: return x
                    return unicode(x, 'utf8')
                except Exception:
                    return ""

            def add_wp(name, pos, startalt, endalt, winddir, windvel, gs, what,
                       legpart, lastsub, d, tas, land_at_end, endfuel,
                       fuelburn, depart_dt, arrive_dt, altitude):
                assert depart_dt == None or type(depart_dt) == datetime
                assert type(pos[0]) in [float, int]
                assert type(pos[1]) in [float, int]
                d = dict(lat=pos[0],
                         lon=pos[1],
                         name=name,
                         startalt=f(startalt),
                         endalt=f(endalt),
                         winddir=f(winddir),
                         windvel=f(windvel),
                         gs=eitherf(gs, 75),
                         what=s(what),
                         legpart=s(legpart),
                         lastsub=i(lastsub),
                         d=f(d),
                         tas=eitherf(tas, 75),
                         land_at_end=i(land_at_end),
                         endfuel=f(endfuel),
                         fuelburn=f(fuelburn),
                         depart_dt=da(depart_dt),
                         arrive_dt=da(arrive_dt),
                         altitude=s(altitude))
                waypoints.append(d)

            try:

                rts, dummy = calc_route_info.get_route(user.user, trip.trip)
            except Exception:
                print traceback.format_exc()
                wpy = list(
                    meta.Session.query(Waypoint).filter(
                        sa.and_(Waypoint.user == user.user,
                                Waypoint.trip == trip.trip)).order_by(
                                    Waypoint.ordering).all())

                rts = []
                for wp1, wp2 in zip(wpy, wpy[1:]):
                    trts = meta.Session.query(Route).filter(
                        sa.and_(Route.user == user.user,
                                Route.trip == trip.trip,
                                Route.waypoint1 == wp1.id,
                                Route.waypoint2 == wp2.id)).all()
                    dummy, d = mapper.bearing_and_distance(wp1.pos, wp2.pos)
                    if len(trts) == 0:
                        rts.append(
                            Route(user=user.user,
                                  trip=trip.trip,
                                  waypoint1=wp1.id,
                                  waypoint2=wp2.id,
                                  winddir=None,
                                  windvel=None,
                                  tas=None,
                                  variation=None,
                                  altitude="1500"))
                    else:
                        rts.append(trts[0])

                if len(rts):
                    rt0 = rts[0]
                    add_wp(rt0.a.waypoint, mapper.from_str(rt0.a.pos), 1500,
                           1500, rt0.winddir, rt0.windvel, 0, "start", "start",
                           1, 0, rt0.tas, False, 0, 0, None, None,
                           rt0.altitude)
                    del rt0
                    for rt in rts:
                        land_at_end = not not (rt.b.stay)
                        #print "Land at end of leg:",rt.b.waypoint,":",land_at_end
                        dummy, d = mapper.bearing_and_distance(
                            rt.a.pos, rt.b.pos)
                        add_wp(rt.a.waypoint, mapper.from_str(rt.a.pos), 1500,
                               1500, rt.winddir, rt.windvel, 0, "cruise",
                               "mid", 1, d, rt.tas, land_at_end, 0, 0, None,
                               None, rt.altitude)

            else:
                if len(rts):
                    rt0 = rts[0]
                    try:
                        startfuel = rt0.accum_fuel_left + rt0.fuel_burn
                    except Exception:
                        startfuel = None
                    print "Startfuel:", startfuel
                    add_wp(rt0.a.waypoint, rt0.startpos, rt0.startalt,
                           rt0.endalt, rt0.winddir, rt0.windvel, rt0.gs,
                           "start", "start", 1, 0, rt0.tas, False, startfuel,
                           0, rt0.depart_dt, rt0.depart_dt, rt0.altitude)
                    del rt0
                    for rt in rts:
                        land_at_end = not not (rt.b.stay and rt.lastsub)
                        #print "Land at end of leg:",rt.b.waypoint,":",land_at_end
                        add_wp(rt.b.waypoint, rt.endpos, rt.startalt,
                               rt.endalt, rt.winddir, rt.windvel, rt.gs,
                               rt.what, rt.legpart, rt.lastsub, rt.d, rt.tas,
                               land_at_end, rt.accum_fuel_left, rt.fuel_burn,
                               rt.depart_dt, rt.arrive_dt, rt.altitude)

            tripobj['waypoints'] = waypoints
        except Exception:
            print "While processing trip", trip.trip, ":", traceback.format_exc(
            )
            continue
        out.append(tripobj)
    return out
Exemplo n.º 7
0
def get_terrain_near_route(rts,vertdist,interval=10):
    l=len(rts)
    out=[]
    for idx,rt in enumerate(rts):
        #print "ord:",rt.a.ordering
        if rt.dt==None:
            continue
        merca=rt.subposa
        mercb=rt.subposb
        
        minstep=2
                
        stepcount=rt.d/float(minstep)
        if stepcount>100:
            newstep=rt.d/100.0
            if newstep>minstep:
                minstep=newstep
        if interval<minstep:
            interval=minstep        
        df=rt.d
        
        
        if df<1e-3:
            df=1e-3
        along_nm=0.0
        #isfirstorlast=(idx==0 or idx==l-1)        
        while True:
            alongf=float(along_nm)/float(df)
            end=False
            if alongf>1.0:
                alongf=1.0
                end=True
            merc=((1.0-alongf)*merca[0]+(alongf)*mercb[0],
                  (1.0-alongf)*merca[1]+(alongf)*mercb[1])
            alt=(1.0-alongf)*rt.startalt+(alongf)*rt.endalt
            latlon=mapper.merc2latlon(merc,13)
            elev=get_terrain_elev_in_box_approx(latlon,2*minstep)
            
            
            dist_from_a=mapper.bearing_and_distance(mapper.from_str(rt.a.pos),latlon)[1]
            dist_from_b=rt.d-dist_from_a
            if dist_from_b<0: dist_from_b=0
            
                
                
            
            
            #if isfirstorlast and (along_nm<2.5 or along_nm>d-2.5):
            #    along_nm+=minstep
            #    continue
               
            if (alt-elev<vertdist and
                not (rt.a.stay and dist_from_a<5) and
                not ((rt.b.stay or idx==l-1) and dist_from_b<5) ):

                #print "idx",idx,"ord:",rt.a.ordering
                #print "Terrain warning: ",dict(a=rt.a.waypoint,b=rt.b.waypoint,kind=rt.legpart,startalt=rt.startalt,endalt=rt.endalt,along=alongf,end=end)
                out.append(dict(
                    name="Terrain warning",
                    pos=mapper.to_str(latlon),
                    elev="%.0f"%(elev,),
                    elevf=elev,
                    dist=0,
                    bearing=0,
                    closestalt=alt,
                    kind='terrain',
                    dist_from_a=dist_from_a,
                    dir_from_a=describe_dir(rt.tt),
                    dist_from_b=dist_from_b,
                    dir_from_b=describe_dir((rt.tt+180.0)%360.0),
                    a=rt.a,
                    b=rt.b,
                    id=rt.a.id))
                along_nm+=interval
            else:
                along_nm+=minstep
            if end: 
                break
    return out
Exemplo n.º 8
0
 def getdist_meter(p1, p2):
     brg, dist = mapper.bearing_and_distance(
         mapper.merc2latlon(p1, 20), mapper.merc2latlon(p2, 20))
     return dist * 1852.0
Exemplo n.º 9
0
    def ats(self):
        try:
            #waypoints=meta.Session.query(Waypoint).filter(sa.and_(
            #     Waypoint.user==tripuser(),Waypoint.trip==session['current_trip'])).order_by(Waypoint.ordering).all()
            #c.waypoints=[]
            self.standard_prep(c)

            #print "Routes:",c.route

            def break_subtrips(routes):
                out = []
                T = 0.0
                for i, rt in enumerate(routes):
                    out.append(rt)
                    if rt.time_hours:
                        T += rt.time_hours
                    if rt.b.stay or i == len(routes) - 1:
                        if len(out):
                            yield dict(T=T), out
                        T = 0.0
                        out = []

            def format_cruise(tas):
                if tas > 999: tas = 999
                if tas < 0: tas = 0
                return "N%04d" % (tas, )

            def format_alt(alt):
                try:
                    alt = alt.upper().strip()
                    if alt.startswith("FL"):
                        ialt = int(float(alt[2:].strip()))
                        return "F%03d" % (ialt, )
                    ialt = int(float(alt)) / 100
                    print "parsed alt %s" % (repr(alt, )), "as", ialt
                    return "A%03d" % (ialt, )
                except Exception:
                    raise AtsException(
                        "Bad altitude specification for some leg: <%s>" %
                        (alt))

            c.atstrips = []
            last_fuel_left = None
            nr_persons = None
            for meta, routes in break_subtrips(c.route):
                print "===============New subtrip..............."
                spaces = set()
                fir_whenposname = []
                accum_time = 0
                #print "broke ruote",meta
                if len(routes) == 0: continue
                at = dict()
                at['T'] = meta['T']
                waypoints = [routes[0].a]
                for rt in routes:
                    waypoints.append(rt.b)
                wps = []
                stay = routes[0].a.stay
                dep_ad = "ZZZZ"
                dep_ad_name = waypoints[0].waypoint
                dep_ad_coords = mapper.format_lfv_ats(
                    *mapper.from_str(waypoints[0].pos))
                dest_ad = "ZZZZ"
                dest_ad_name = waypoints[-1].waypoint
                dest_ad_coords = mapper.format_lfv_ats(
                    *mapper.from_str(waypoints[-1].pos))
                extra_remarks = []
                lastwppos = None
                lastaltspeed = None
                for i, wp in enumerate(waypoints):
                    print "Subtrip:", i, wp.waypoint
                    at['T'] = meta['T']
                    lat, lon = mapper.from_str(wp.pos)
                    if lastwppos:
                        assert i >= 1
                        curpos = (lat, lon)
                        crossing1 = airspace.get_fir_crossing(
                            lastwppos, curpos)
                        for sub in routes[i - 1].subs:
                            if crossing1:
                                posa,posb=mapper.merc2latlon(sub.subposa,13),\
                                            mapper.merc2latlon(sub.subposb,13)
                                crossing = airspace.get_fir_crossing(
                                    posa, posb)
                                if crossing:
                                    fir, enterpos = crossing
                                    bearing, along = mapper.bearing_and_distance(
                                        posa, enterpos)
                                    if sub.gs > 1e-6:
                                        curtime = accum_time + along / sub.gs
                                        fir_whenposname.append(
                                            (curtime, enterpos, fir['icao']))
                            if sub.time != None:
                                accum_time += sub.time
                            else:
                                accum_time = 9999

                        for space in get_any_space_on_line(lastwppos, curpos):
                            spaces.add((space['name'],
                                        space.get('floor', "<Unknown>"),
                                        space.get('ceiling', "<Unknown>")))

                    lastwppos = (lat, lon)
                    symbolicpos = None
                    airport = None

                    if i == 0 or i == len(waypoints) - 1:
                        for ad in airspace.get_airfields(lat, lon, 11):
                            if not ad['icao'].upper() in ['ZZZZ', 'ESVF']:
                                airport = ad
                                symbolicpos = ad['icao'].upper()
                                if i == 0:
                                    dep_ad = ad['icao'].upper()
                                if i == len(waypoints) - 1:
                                    dest_ad = ad['icao'].upper()
                                break
                    else:
                        for sigp in airspace.get_sigpoints(lat, lon, 11):
                            if sigp['kind'] == "sig. point":
                                if len(sigp['name']) == 5:
                                    sigfound = sigp
                                    symbolicpos = sigp['name']
                                    break

                    if symbolicpos == None:
                        symbolicpos = mapper.format_lfv_ats(lat, lon)

                    if i < len(routes):
                        altspeed = (format_alt(routes[i].altitude),
                                    format_cruise(routes[i].tas))
                        if lastaltspeed != None:
                            if lastaltspeed != altspeed:
                                alt, speed = altspeed
                                symbolicpos += "/" + speed + alt
                        lastaltspeed = altspeed

                    wps.append(
                        dict(name=wp.waypoint,
                             airport=airport,
                             symbolicpos="DCT " + symbolicpos,
                             exactpos=mapper.format_lfv(lat, lon),
                             decimalpos="%.5f,%.5f" % (lat, lon)))
                for when, pos, fir in fir_whenposname:
                    hour, minute = divmod(int(60 * when), 60)
                    extra_remarks.append("EET/%s%02d%02d" %
                                         (fir, hour, minute))
                if dep_ad == "ZZZZ":
                    extra_remarks.append(
                        u"DEP/%s %s" %
                        (dep_ad_coords, strip_accents(dep_ad_name.upper())))
                if dest_ad == "ZZZZ":
                    extra_remarks.append(
                        u"DEST/%s %s" %
                        (dest_ad_coords, strip_accents(dest_ad_name.upper())))
                if stay.date_of_flight.strip():
                    dof = stay.date_of_flight.replace("-", "").strip()
                    if len(dof) == 8 and dof.startswith("20"):
                        dof = dof[2:]
                else:
                    dof = routes[0].depart_dt.strftime("%y%m%d")
                print "dof:", dof

                if len(dof) != 6:
                    raise AtsException(
                        u"ATS flight plans need takeoff date for all takeoffs!"
                    )
                else:
                    extra_remarks.append(u"DOF/%s" % (dof, ))
                if stay and stay.nr_persons:
                    nr_persons = stay.nr_persons
                else:
                    if nr_persons == None:
                        raise AtsException(
                            u"You must enter the the number of persons who will be flying!"
                        )
                tas = routes[0].tas
                altitude = routes[0].altitude
                at['wps'] = wps
                if any(rt.time_hours == None for rt in routes):
                    raise AtsException(
                        "TAS is less than headwind for some part of trip.")
                enroute_time = sum(rt.time_hours for rt in routes)

                fuel = last_fuel_left
                if stay and stay.fuel:
                    fuel = stay.fuel

                if not c.ac:
                    raise AtsException(
                        "You must choose an aircraft type for this journey to be able to create an ATS flight plan"
                    )
                if c.ac.cruise_burn > 1e-3 and fuel:
                    endurance = float(fuel) / float(c.ac.cruise_burn)
                else:
                    endurance = 0.0

                if endurance <= 0.0:
                    if fuel == None:
                        raise AtsException(
                            "Enter a value for 'Fuel at takeoff'!")
                    else:
                        raise AtsException(
                            "You do not have enough fuel for the entire journey! This means your endurance would be 0 or negative for one or more legs. Add a fuel stop, shorten the journey, or bring more fuel!"
                        )

                if not c.user.realname:
                    raise AtsException(
                        "You should enter your name under profile settings, for use as the name of the commander in the flight plan"
                    )
                phonenr = ""
                if c.user.phonenr:
                    phonenr = c.user.phonenr
                fir_whenposname.sort()

                def eqp(x, s):
                    x = "".join(re.findall('[A-Z]', x.upper()))
                    if len(x) == 0:
                        return s
                    return x

                dummy = u"""
    FPL-SEVLI-VG
    -ULAC/L-V/C
    -EFKG1330
    -N0075F065 DCT 5959N02016E DCT 5949N01936E DCT 5929N01818E DCT 5927N01742E
    -ZZZZ0130 
    -DEST/5927N01742E FRÖLUNDA RMK/BORDER CROSSING 40MIN AFTER TAKEOFF DOF/101002 ORGN/ESSAZPZX
    -E/0300 P/2
    A/R W
    C/ANDERS MUSIKKA +4670123123"""

                atsfplan = u"""
(FPL-%(acreg)s-%(flight_rules)s%(type_of_flight)s
-%(actype)s/%(turbulence_category)s-%(equipment)s/%(transponder)s
-%(dep_ad)s%(eobt)s
-%(cruise_speed)s%(level)s %(route)s DCT
-%(dest_ad)s%(ete)s 
-%(extra_remarks)s
-E/%(endurance)s P/%(nr_passengers)s
A/%(markings)s%(extra_equipment)s
C/%(commander)s %(phonenr)s)""" % (dict(
                    acreg=c.ac.aircraft.replace("-", ""),
                    actype=c.ac.atstype,
                    turbulence_category='L',
                    flight_rules='V',
                    type_of_flight='G',
                    equipment=eqp(c.ac.com_nav_equipment, 'V'),
                    transponder=eqp(c.ac.transponder_equipment, 'C'),
                    extra_equipment=u" %s" %
                    (c.ac.extra_equipment, ) if c.ac.extra_equipment else "",
                    dep_ad=dep_ad,
                    eobt=routes[0].depart_dt.strftime("%H%M"),
                    cruise_speed=format_cruise(tas),
                    level=format_alt(altitude),
                    route=(" ".join("%s" % (w['symbolicpos'], )
                                    for w in wps[1:-1])),
                    dest_ad=dest_ad,
                    ete=lfvclockfmt(enroute_time),
                    extra_remarks=" ".join(extra_remarks),
                    endurance=lfvclockfmt(endurance),
                    nr_passengers=nr_persons,
                    markings=c.ac.markings,
                    commander=strip_accents(c.user.realname if c.user.realname
                                            else u"UNKNOWN").replace(" ", ""),
                    phonenr=c.user.phonenr if c.user.phonenr else ""))
                at['atsfplan'] = atsfplan.strip()
                #print "Adding atstrip:",atsfplan
                at['spacesummary'] = spaces
                last_fuel_left = routes[-1].accum_fuel_left
                c.atstrips.append(at)

            c.atstrips = [at for at in c.atstrips if len(at['wps'])]
            #response.headers['Content-Type'] = 'application/xml'
            return render('/ats.mako')
        except AtsException, ats:
            redirect(
                h.url_for(controller='flightplan',
                          action="index",
                          flash=unicode(ats)))
Exemplo n.º 10
0
 def getdist_meter(p1,p2):
     brg,dist=mapper.bearing_and_distance(mapper.merc2latlon(p1,20),mapper.merc2latlon(p2,20))
     return dist*1852.0
Exemplo n.º 11
0
 def close(a,b):
     bearing,dist=mapper.bearing_and_distance(
                 mapper.from_str(a),mapper.from_str(b))
     #print (a,b),dist
     return dist<1.0
Exemplo n.º 12
0
def get_user_trips(user):
    users=meta.Session.query(User).filter(User.user==user).all()
    if len(users)==0:
        return []
    user,=users
    
    trips=meta.Session.query(Trip).filter(sa.and_(Trip.user==user.user)).order_by(Trip.trip).all()
    out=[]
    for trip in trips:
        meta.Session.flush()
        try:
            #print "Processing trip",trip.trip
            tripobj=dict()
            tripobj['name']=trip.trip
            tripobj['aircraft']=trip.aircraft
            
            actypes=list(meta.Session.query(Aircraft).filter(Aircraft.aircraft==trip.aircraft).all())
            if len(actypes)==0:
                tripobj['atsradiotype']='?'
            else:
                tripobj['atsradiotype']=actypes[0].atsradiotype
            
            waypoints=[]
            def eitherf(x,fallback):
                try:
                    if x==None: return fallback
                    return float(x)
                except Exception:
                    return 0.0
            def da(x):
                try:
                    if x==None: return datetime(1970,1,1)
                    if type(x)==datetime: return x
                    return datetime(1970,1,1)
                except Exception:
                    return datetime(1970,1,1)
            def f(x):
                try:
                    if x==None: return 0.0
                    return float(x)
                except Exception:
                    return 0.0
            def i(x):
                try:
                    if x==None: return 0
                    return int(x)
                except Exception:
                    return 0
            def s(x):
                try:
                    if x==None: return ""
                    if type(x)==unicode: return x
                    return unicode(x,'utf8')
                except Exception:
                    return ""
            def add_wp(name,pos,startalt,endalt,winddir,windvel,gs,what,legpart,lastsub,d,tas,land_at_end,
                       endfuel,fuelburn,depart_dt,arrive_dt,altitude):
                assert depart_dt==None or type(depart_dt)==datetime                
                assert type(pos[0])in [float,int]
                assert type(pos[1])in [float,int]
                d=dict(lat=pos[0],lon=pos[1],
                    name=name,startalt=f(startalt),endalt=f(endalt),winddir=f(winddir),windvel=f(windvel),
                        gs=eitherf(gs,75),what=s(what),legpart=s(legpart),lastsub=i(lastsub),d=f(d),tas=eitherf(tas,75),land_at_end=i(land_at_end),
                        endfuel=f(endfuel),fuelburn=f(fuelburn),depart_dt=da(depart_dt),arrive_dt=da(arrive_dt),altitude=s(altitude)
                        )
                waypoints.append(d)
            
            try:

                rts,dummy=calc_route_info.get_route(user.user,trip.trip)
            except Exception:
                print traceback.format_exc()
                wpy=list(meta.Session.query(Waypoint).filter(sa.and_(
                         Waypoint.user==user.user,Waypoint.trip==trip.trip)).order_by(Waypoint.ordering).all())

                rts=[]                
                for wp1,wp2 in zip(wpy,wpy[1:]):
                    trts=meta.Session.query(Route).filter(sa.and_(
                        Route.user==user.user,Route.trip==trip.trip,
                        Route.waypoint1==wp1.id,Route.waypoint2==wp2.id)).all()
                    dummy,d=mapper.bearing_and_distance(wp1.pos,wp2.pos)                        
                    if len(trts)==0:
                        rts.append(Route(user=user.user,trip=trip.trip,waypoint1=wp1.id,waypoint2=wp2.id,winddir=None,windvel=None,tas=None,variation=None,altitude="1500"))
                    else:
                        rts.append(trts[0])
                
                if len(rts):
                    rt0=rts[0]                    
                    add_wp(rt0.a.waypoint,mapper.from_str(rt0.a.pos),1500,1500,rt0.winddir,rt0.windvel,0,
                            "start","start",1,0,rt0.tas,False,0,0,
                            None,None,rt0.altitude)
                    del rt0
                    for rt in rts:                        
                        land_at_end=not not (rt.b.stay)
                        #print "Land at end of leg:",rt.b.waypoint,":",land_at_end
                        dummy,d=mapper.bearing_and_distance(rt.a.pos,rt.b.pos)
                        add_wp(rt.a.waypoint,mapper.from_str(rt.a.pos),1500,1500,rt.winddir,rt.windvel,0,
                            "cruise","mid",1,d,rt.tas,land_at_end,0,0,
                            None,None,rt.altitude)
            
            else:
                if len(rts):
                    rt0=rts[0]                    
                    try:
                        startfuel=rt0.accum_fuel_left+rt0.fuel_burn
                    except Exception:
                        startfuel=None
                    print "Startfuel:",startfuel
                    add_wp(rt0.a.waypoint,rt0.startpos,rt0.startalt,rt0.endalt,rt0.winddir,rt0.windvel,rt0.gs,
                            "start","start",1,0,rt0.tas,False,startfuel,0,
                            rt0.depart_dt,rt0.depart_dt,rt0.altitude)
                    del rt0
                    for rt in rts:                        
                        land_at_end=not not (rt.b.stay and rt.lastsub)
                        #print "Land at end of leg:",rt.b.waypoint,":",land_at_end
                        add_wp(rt.b.waypoint,rt.endpos,rt.startalt,rt.endalt,rt.winddir,rt.windvel,rt.gs,rt.what,rt.legpart,rt.lastsub,rt.d,rt.tas,land_at_end,
                               rt.accum_fuel_left,rt.fuel_burn,rt.depart_dt,rt.arrive_dt,rt.altitude)
            
            tripobj['waypoints']=waypoints
        except Exception:
            print "While processing trip",trip.trip,":",traceback.format_exc()
            continue
        out.append(tripobj)
    return out
Exemplo n.º 13
0
 def close(a, b):
     bearing, dist = mapper.bearing_and_distance(
         mapper.from_str(a), mapper.from_str(b))
     #print (a,b),dist
     return dist < 1.0
Exemplo n.º 14
0
    def ats(self):
        try:
            #waypoints=meta.Session.query(Waypoint).filter(sa.and_(
            #     Waypoint.user==tripuser(),Waypoint.trip==session['current_trip'])).order_by(Waypoint.ordering).all()
            #c.waypoints=[]
            self.standard_prep(c)
            #print "Routes:",c.route
            
            def break_subtrips(routes):
                out=[]
                T=0.0
                for i,rt in enumerate(routes):
                    out.append(rt)
                    if rt.time_hours:
                        T+=rt.time_hours
                    if rt.b.stay or i==len(routes)-1:
                        if len(out):
                            yield dict(T=T),out
                        T=0.0
                        out=[]                
            def format_cruise(tas):
                if tas>999: tas=999
                if tas<0: tas=0
                return "N%04d"%(tas,)
            def format_alt(alt):
                try:                    
                    alt=alt.upper().strip()
                    if alt.startswith("FL"):
                        ialt=int(float(alt[2:].strip()))
                        return "F%03d"%(ialt,)
                    ialt=int(float(alt))/100
                    print "parsed alt %s"%(repr(alt,)),"as",ialt
                    return "A%03d"%(ialt,)
                except Exception:
                    raise AtsException("Bad altitude specification for some leg: <%s>"%(alt))
                        
                        
            c.atstrips=[]
            last_fuel_left=None
            nr_persons=None
            for meta,routes in break_subtrips(c.route):
                print "===============New subtrip..............."
                spaces=set()                
                fir_whenposname=[]
                accum_time=0
                #print "broke ruote",meta
                if len(routes)==0: continue
                at=dict()
                at['T']=meta['T']
                waypoints=[routes[0].a]
                for rt in routes: 
                    waypoints.append(rt.b)
                wps=[]
                stay=routes[0].a.stay
                dep_ad="ZZZZ"
                dep_ad_name=waypoints[0].waypoint
                dep_ad_coords=mapper.format_lfv_ats(*mapper.from_str(waypoints[0].pos))
                dest_ad="ZZZZ"
                dest_ad_name=waypoints[-1].waypoint
                dest_ad_coords=mapper.format_lfv_ats(*mapper.from_str(waypoints[-1].pos))
                extra_remarks=[]
                lastwppos=None
                lastaltspeed=None
                for i,wp in enumerate(waypoints):
                    print "Subtrip:",i,wp.waypoint
                    at['T']=meta['T']
                    lat,lon=mapper.from_str(wp.pos)
                    if lastwppos:
                        assert i>=1
                        curpos=(lat,lon)
                        crossing1=airspace.get_fir_crossing(lastwppos,curpos)                        
                        for sub in routes[i-1].subs:
                            if crossing1:
                                posa,posb=mapper.merc2latlon(sub.subposa,13),\
                                            mapper.merc2latlon(sub.subposb,13)
                                crossing=airspace.get_fir_crossing(posa,posb)
                                if crossing:
                                    fir,enterpos=crossing
                                    bearing,along=mapper.bearing_and_distance(posa,enterpos)
                                    if sub.gs>1e-6:
                                        curtime=accum_time+along/sub.gs
                                        fir_whenposname.append((curtime,enterpos,fir['icao']))
                            if sub.time!=None:
                                accum_time+=sub.time
                            else:
                                accum_time=9999
                            
                        for space in get_any_space_on_line(lastwppos,curpos):
                            spaces.add((space['name'],space.get('floor',"<Unknown>"),space.get('ceiling',"<Unknown>")))
                    
                    lastwppos=(lat,lon)         
                    symbolicpos=None
                    airport=None
                    
                    
                    
                    if i==0 or i==len(waypoints)-1:
                        for ad in airspace.get_airfields(lat,lon,11):
                            if not ad['icao'].upper() in ['ZZZZ','ESVF']:
                                airport=ad
                                symbolicpos=ad['icao'].upper()
                                if i==0:
                                    dep_ad=ad['icao'].upper()
                                if i==len(waypoints)-1:
                                    dest_ad=ad['icao'].upper()
                                break
                    else:
                        for sigp in airspace.get_sigpoints(lat,lon,11):
                            if sigp['kind']=="sig. point":
                                if len(sigp['name'])==5:
                                    sigfound=sigp
                                    symbolicpos=sigp['name']
                                    break                
                    
                    if symbolicpos==None:
                        symbolicpos=mapper.format_lfv_ats(lat,lon)
                        
                    if i<len(routes):
                        altspeed=(format_alt(routes[i].altitude),format_cruise(routes[i].tas))
                        if lastaltspeed!=None:
                            if lastaltspeed!=altspeed:
                                alt,speed=altspeed
                                symbolicpos+="/"+speed+alt
                        lastaltspeed=altspeed
                        
                    wps.append(dict(
                        name=wp.waypoint,
                        airport=airport,
                        symbolicpos="DCT "+symbolicpos,                
                        exactpos=mapper.format_lfv(lat,lon),
                        decimalpos="%.5f,%.5f"%(lat,lon)
                        ))
                for when,pos,fir in fir_whenposname:
                    hour,minute=divmod(int(60*when),60)
                    extra_remarks.append("EET/%s%02d%02d"%(fir,hour,minute))
                if dep_ad=="ZZZZ":
                    extra_remarks.append(u"DEP/%s %s"%(dep_ad_coords,strip_accents(dep_ad_name.upper())))
                if dest_ad=="ZZZZ":
                    extra_remarks.append(u"DEST/%s %s"%(dest_ad_coords,strip_accents(dest_ad_name.upper())))
                if stay.date_of_flight.strip():
                    dof=stay.date_of_flight.replace("-","").strip()
                    if len(dof)==8 and dof.startswith("20"):
                        dof=dof[2:]
                else:
                    dof=routes[0].depart_dt.strftime("%y%m%d")
                print "dof:",dof
                                        
                if len(dof)!=6:
                    raise AtsException(u"ATS flight plans need takeoff date for all takeoffs!")
                else:                    
                    extra_remarks.append(u"DOF/%s"%(dof,))            
                if stay and stay.nr_persons:
                    nr_persons=stay.nr_persons
                else:
                    if nr_persons==None:
                        raise AtsException(u"You must enter the the number of persons who will be flying!")
                tas=routes[0].tas
                altitude=routes[0].altitude
                at['wps']=wps
                if any(rt.time_hours==None for rt in routes):
                    raise AtsException("TAS is less than headwind for some part of trip.")
                enroute_time=sum(rt.time_hours for rt in routes)

                fuel=last_fuel_left
                if stay and stay.fuel:
                    fuel=stay.fuel
                    
                if not c.ac:
                    raise AtsException("You must choose an aircraft type for this journey to be able to create an ATS flight plan")
                if c.ac.cruise_burn>1e-3 and fuel:
                    endurance=float(fuel)/float(c.ac.cruise_burn)
                else:
                    endurance=0.0
                
                if endurance<=0.0:
                    if fuel==None:
                        raise AtsException("Enter a value for 'Fuel at takeoff'!")
                    else:
                        raise AtsException("You do not have enough fuel for the entire journey! This means your endurance would be 0 or negative for one or more legs. Add a fuel stop, shorten the journey, or bring more fuel!")
                        
                if not c.user.realname:
                    raise AtsException("You should enter your name under profile settings, for use as the name of the commander in the flight plan")
                phonenr=""
                if c.user.phonenr:            
                    phonenr=c.user.phonenr
                fir_whenposname.sort()
                def eqp(x,s):
                    x="".join(re.findall('[A-Z]',x.upper()))
                    if len(x)==0:
                        return s
                    return x
                    
                dummy=u"""
    FPL-SEVLI-VG
    -ULAC/L-V/C
    -EFKG1330
    -N0075F065 DCT 5959N02016E DCT 5949N01936E DCT 5929N01818E DCT 5927N01742E
    -ZZZZ0130 
    -DEST/5927N01742E FRÖLUNDA RMK/BORDER CROSSING 40MIN AFTER TAKEOFF DOF/101002 ORGN/ESSAZPZX
    -E/0300 P/2
    A/R W
    C/ANDERS MUSIKKA +4670123123"""
            
                atsfplan=u"""
(FPL-%(acreg)s-%(flight_rules)s%(type_of_flight)s
-%(actype)s/%(turbulence_category)s-%(equipment)s/%(transponder)s
-%(dep_ad)s%(eobt)s
-%(cruise_speed)s%(level)s %(route)s DCT
-%(dest_ad)s%(ete)s 
-%(extra_remarks)s
-E/%(endurance)s P/%(nr_passengers)s
A/%(markings)s%(extra_equipment)s
C/%(commander)s %(phonenr)s)"""%(dict(
                acreg=c.ac.aircraft.replace("-",""),
                actype=c.ac.atstype,
                turbulence_category='L',
                flight_rules='V',
                type_of_flight='G',
                equipment=eqp(c.ac.com_nav_equipment,'V'),
                transponder=eqp(c.ac.transponder_equipment,'C'),
                extra_equipment=u" %s"%(c.ac.extra_equipment,) if c.ac.extra_equipment else "",
                dep_ad=dep_ad,
                eobt=routes[0].depart_dt.strftime("%H%M"),
                cruise_speed=format_cruise(tas),
                level=format_alt(altitude),
                route=(" ".join("%s"%(w['symbolicpos'],) for w in wps[1:-1])),
                dest_ad=dest_ad,
                ete=lfvclockfmt(enroute_time),
                extra_remarks=" ".join(extra_remarks),
                endurance=lfvclockfmt(endurance),
                nr_passengers=nr_persons,
                markings=c.ac.markings,
                commander=strip_accents(c.user.realname if c.user.realname else u"UNKNOWN").replace(" ",""),
                phonenr=c.user.phonenr if c.user.phonenr else ""))
                at['atsfplan']=atsfplan.strip()
                #print "Adding atstrip:",atsfplan    
                at['spacesummary']=spaces
                last_fuel_left=routes[-1].accum_fuel_left
                c.atstrips.append(at)    
            
            c.atstrips=[at for at in c.atstrips if len(at['wps'])]
            #response.headers['Content-Type'] = 'application/xml'               
            return render('/ats.mako')
        except AtsException,ats:
            redirect(h.url_for(controller='flightplan',action="index",flash=unicode(ats)))