Exemplo n.º 1
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']])
Exemplo n.º 2
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']])
Exemplo n.º 3
0
    def enroutenotams(self):
        c.techroute, c.route = get_route(tripuser(), session['current_trip'])
        c.tripobj = meta.Session.query(Trip).filter(
            sa.and_(Trip.user == tripuser(),
                    Trip.trip == session['current_trip'])).one()
        if len(c.route) == 0 or len(c.techroute) == 0:
            redirect(
                h.url_for(controller='flightplan',
                          action="index",
                          flash=u"Must have at least two waypoints in trip!"))
            return

        c.trip = c.tripobj.trip
        for rt in c.route:
            rt.notampoints = dict()
            rt.notampoints.update(
                dict([(info['item']['notam'], info['item']) for info in
                      get_notampoints_on_line(mapper.from_str(rt.a.pos),
                                              mapper.from_str(rt.b.pos), 5)]))

        for rt in c.route:
            for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos),
                                                 mapper.from_str(rt.b.pos)):
                rt.notampoints[space['name']] = space
        c.thislink = h.url_for(controller='flightplan', action="enroutenotams")
        return render('/enroutenotams.mako')
Exemplo n.º 4
0
    def standard_prep(self, c):
        if not 'current_trip' in session:
            redirect(h.url_for(controller='mapview', action="index"))
        tripobjs = meta.Session.query(Trip).filter(
            sa.and_(Trip.user == tripuser(),
                    Trip.trip == session['current_trip'])).all()
        if len(tripobjs) != 1:
            redirect(h.url_for(controller='mapview', action="index"))
        c.tripobj, = tripobjs
        c.trip = c.tripobj.trip
        c.techroute, c.route = get_route(tripuser(), session['current_trip'])
        #c.route=list(meta.Session.query(Route).filter(sa.and_(
        #    Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all())
        c.user = meta.Session.query(User).filter(
            User.user == session['user']).one()

        c.all_aircraft = list(
            meta.Session.query(Aircraft).filter(
                sa.and_(Aircraft.user == session['user'])).order_by(
                    Aircraft.aircraft).all())

        if len(c.route) == 0 or len(c.techroute) == 0:
            redirect(
                h.url_for(controller='flightplan',
                          action="index",
                          flash=u"Must have at least two waypoints in trip!"))
            return
        c.startfuel = 0
        if len(c.route) > 0:
            try:
                c.startfuel = c.route[0].a.stay.fuel
            except Exception:
                pass
            if c.startfuel == None:
                c.startfuel = 0
        #c.tripobj.startfuel
        c.acobjs = meta.Session.query(Aircraft).filter(
            sa.and_(Aircraft.user == tripuser(),
                    Aircraft.aircraft == c.tripobj.aircraft)).order_by(
                        Aircraft.aircraft).all()
        c.ac = None
        if len(c.acobjs) > 0:
            c.ac = c.acobjs[0]

        c.reserve_endurance = "Unknown"
        if c.ac and c.ac.cruise_burn > 1e-9 and len(c.techroute):
            minfuelintrip = min(t.accum_fuel_left for t in c.techroute)
            if minfuelintrip != None:
                c.reserve_endurance_hours = minfuelintrip / c.ac.cruise_burn
                mins = int(60.0 * c.reserve_endurance_hours)
                if mins >= 0:
                    c.reserve_endurance = "%dh%02dm" % (mins / 60, mins % 60)
        c.departure = c.route[0].a.waypoint
        c.arrival = c.route[-1].b.waypoint
        c.fillable = c.user.fillable
Exemplo n.º 5
0
    def standard_prep(self,c):
        if not 'current_trip' in session:
            redirect(h.url_for(controller='mapview',action="index"))
        tripobjs=meta.Session.query(Trip).filter(sa.and_(
            Trip.user==tripuser(),Trip.trip==session['current_trip'])).all()
        if len(tripobjs)!=1:
            redirect(h.url_for(controller='mapview',action="index"))
        c.tripobj,=tripobjs
        c.trip=c.tripobj.trip
        c.techroute,c.route=get_route(tripuser(),session['current_trip'])
        #c.route=list(meta.Session.query(Route).filter(sa.and_(
        #    Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all())
        c.user=meta.Session.query(User).filter(
                User.user==session['user']).one()

        c.all_aircraft=list(meta.Session.query(Aircraft).filter(sa.and_(
            Aircraft.user==session['user'])).order_by(Aircraft.aircraft).all())
        
            
        if len(c.route)==0 or len(c.techroute)==0:
            redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!"))
            return
        c.startfuel=0
        if len(c.route)>0:
            try:
                c.startfuel=c.route[0].a.stay.fuel
            except Exception:
                pass
            if c.startfuel==None:
                c.startfuel=0
        #c.tripobj.startfuel
        c.acobjs=meta.Session.query(Aircraft).filter(sa.and_(
                 Aircraft.user==tripuser(),Aircraft.aircraft==c.tripobj.aircraft)).order_by(Aircraft.aircraft).all()
        c.ac=None
        if len(c.acobjs)>0:
            c.ac=c.acobjs[0]
        
        c.reserve_endurance="Unknown"
        if c.ac and c.ac.cruise_burn>1e-9 and len(c.techroute):
            minfuelintrip=min(t.accum_fuel_left for t in c.techroute)
            if minfuelintrip!=None:
                c.reserve_endurance_hours=minfuelintrip/c.ac.cruise_burn
                mins=int(60.0*c.reserve_endurance_hours)
                if mins>=0:
                    c.reserve_endurance="%dh%02dm"%(mins/60,mins%60)
        c.departure=c.route[0].a.waypoint
        c.arrival=c.route[-1].b.waypoint
        c.fillable=c.user.fillable        
Exemplo n.º 6
0
    def enroutenotams(self):
        c.techroute,c.route=get_route(tripuser(),session['current_trip'])
        c.tripobj=meta.Session.query(Trip).filter(sa.and_(
            Trip.user==tripuser(),Trip.trip==session['current_trip'])).one()
        if len(c.route)==0 or len(c.techroute)==0:
            redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!"))
            return
        
        c.trip=c.tripobj.trip
        for rt in c.route:
            rt.notampoints=dict()
            rt.notampoints.update(dict([(info['item']['notam'],info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos),5)]))

        for rt in c.route:
            for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)):
                rt.notampoints[space['name']]=space
        c.thislink=h.url_for(controller='flightplan',action="enroutenotams")
        return render('/enroutenotams.mako')
Exemplo n.º 7
0
    def get_trip(self):
        try:
            print "Get trip",request.params
            users=meta.Session.query(User).filter(User.user==request.params['user']).all()
            if len(users)==0:
                return json.dumps(dict(error=u"No user with that name"))
            user,=users
            if user.password!=request.params['password'] and user.password!=md5str(request.params['password']):
                return json.dumps(dict(error=u"Wrong password"))
            
            trip,=meta.Session.query(Trip).filter(sa.and_(Trip.user==user.user,Trip.trip==request.params['trip'])).order_by(Trip.trip).all()
            
            tripobj=dict()
            tripobj['trip']=trip.trip
            waypoints=[]
            rts,dummy=calc_route_info.get_route(user.user,trip.trip)
            if len(rts):
                def either(x,fallback):
                    if x==None: return fallback
                    return x
                def add_wp(name,pos,startalt,endalt,winddir,windvel,gs,what,legpart,lastsub,d,tas,land_at_end):
                    d=dict(lat=pos[0],lon=pos[1],
                        name=name,startalt=startalt,endalt=endalt,winddir=winddir,windvel=windvel,
                            gs=either(gs,75),what=what,legpart=legpart,lastsub=lastsub,d=d,tas=either(tas,75),land_at_end=land_at_end)
                    waypoints.append(d)
                rt0=rts[0]
                
                add_wp(rt0.a.waypoint,rt0.startpos,rt0.startalt,rt0.endalt,rt0.winddir,rt0.windvel,rt0.gs,
                        "start","start",1,0,rt0.tas,False)
                                        
                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)

            tripobj['waypoints']=waypoints
            print "returning json:", waypoints
            response.headers['Content-Type'] = 'text/plain'            
            return json.dumps(tripobj)
        except Exception,cause:
            response.headers['Content-Type'] = 'text/plain'            
            print "Exception",cause
            return json.dumps(dict(error=repr(cause)))
Exemplo n.º 8
0
    def get_trip(self):
        try:
            print "Get trip", request.params
            users = meta.Session.query(User).filter(
                User.user == request.params['user']).all()
            if len(users) == 0:
                return json.dumps(dict(error=u"No user with that name"))
            user, = users
            if user.password != request.params[
                    'password'] and user.password != md5str(
                        request.params['password']):
                return json.dumps(dict(error=u"Wrong password"))

            trip, = meta.Session.query(Trip).filter(
                sa.and_(Trip.user == user.user,
                        Trip.trip == request.params['trip'])).order_by(
                            Trip.trip).all()

            tripobj = dict()
            tripobj['trip'] = trip.trip
            waypoints = []
            rts, dummy = calc_route_info.get_route(user.user, trip.trip)
            if len(rts):

                def either(x, fallback):
                    if x == None: return fallback
                    return x

                def add_wp(name, pos, startalt, endalt, winddir, windvel, gs,
                           what, legpart, lastsub, d, tas, land_at_end):
                    d = dict(lat=pos[0],
                             lon=pos[1],
                             name=name,
                             startalt=startalt,
                             endalt=endalt,
                             winddir=winddir,
                             windvel=windvel,
                             gs=either(gs, 75),
                             what=what,
                             legpart=legpart,
                             lastsub=lastsub,
                             d=d,
                             tas=either(tas, 75),
                             land_at_end=land_at_end)
                    waypoints.append(d)

                rt0 = rts[0]

                add_wp(rt0.a.waypoint, rt0.startpos, rt0.startalt, rt0.endalt,
                       rt0.winddir, rt0.windvel, rt0.gs, "start", "start", 1,
                       0, rt0.tas, False)

                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)

            tripobj['waypoints'] = waypoints
            print "returning json:", waypoints
            response.headers['Content-Type'] = 'text/plain'
            return json.dumps(tripobj)
        except Exception, cause:
            response.headers['Content-Type'] = 'text/plain'
            print "Exception", cause
            return json.dumps(dict(error=repr(cause)))
Exemplo n.º 9
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.º 10
0
    def obstacles(self):
        routes, baseroute = get_route(tripuser(), session['current_trip'])

        tripobj = meta.Session.query(Trip).filter(
            sa.and_(Trip.user == tripuser(),
                    Trip.trip == session['current_trip'])).one()
        c.trip = tripobj.trip
        id2order = dict([(rt.a.id, rt.a.ordering) for rt in baseroute])
        byidsorted = sorted(self.get_obstacles(routes).items(),
                            key=lambda x: id2order.get(x[0], 0))
        out = []

        def classify(item):
            #print item
            vertlimit = 1000
            if item.get('kind', None) == 'lowsun':
                return "#ffffb0"
            if item.get('kind', None) == 'terrain':
                vertlimit = 500
            try:
                margin = item['closestalt'] - mapper.parse_elev(item['elev'])
            except Exception:
                return "#0000ff"  #Unknown margin, unknown height
            if item['dist'] > 0.6 / 1.852:
                return None  #Not really too close anyway
            if margin < 0:
                return "#ff3030"
            if margin < vertlimit:
                return "#ffb0b0"
            return None

        dupecheck = dict()
        for idx, items in byidsorted:
            for item in items:
                ident = (item['name'], item['pos'], item.get('elev', None))
                dupecheck.setdefault(ident, []).append(item)
        bestdupe = dict()
        for ident, dupes in dupecheck.items():
            best = min(dupes, key=lambda x: x['dist'])
            bestdupe[ident] = best

        for idx, items in byidsorted:
            cur = []
            for item in items:
                dist_from_a = item['dist_from_a']
                dist_from_b = item['dist_from_b']

                if abs(dist_from_a) < 0.5:
                    descr = "Near %s" % (item['a'].waypoint, )
                elif abs(dist_from_b) < 0.5:
                    descr = "Near %s" % (item['b'].waypoint, )
                elif dist_from_a < dist_from_b:
                    descr = "%.0fNM %s of %s" % (
                        dist_from_a, item['dir_from_a'], item['a'].waypoint)
                else:
                    descr = "%.0fNM %s of %s" % (
                        dist_from_b, item['dir_from_b'], item['b'].waypoint)

                ident = (item['name'], item['pos'], item.get('elev', None))
                best = bestdupe[ident]
                if not (best is item): continue

                #if ident in seen: continue
                #seen.add(ident)
                cur.append(
                    dict(
                        routepointdescr=descr,
                        #dir_from_a=item['dir_from_a'],
                        #fromwhat=fromwhat,
                        kind=item.get('kind', None),
                        bearing=item.get('bearing', None),
                        along_nm=dist_from_a,
                        dist=item['dist'],
                        name=item['name'],
                        closestalt=item['closestalt'],
                        elev=item.get('elev', None)))
                cur[-1]['color'] = classify(cur[-1])
            out.append((items[0]['a'].waypoint,
                        sorted(cur, key=lambda x: x['along_nm'])))

        c.items = out
        return render('/obstacles.mako')
Exemplo n.º 11
0
    def index(self):
        if not self.validate(exception=False):
            redirect(h.url_for(controller='mapview', action="index"))

        c.flash = request.params.get('flash', None)
        c.waypoints = list(
            meta.Session.query(Waypoint).filter(
                sa.and_(Waypoint.user == tripuser(),
                        Waypoint.trip == c.trip.trip)).order_by(
                            Waypoint.ordering).all())

        if len(c.waypoints):
            wp0 = c.waypoints[0]
            if wp0.stay != None:
                c.stay = wp0.stay
            else:
                #print "No 'Stay', adding"
                c.stay = Stay(c.trip.user, c.trip.trip, wp0.id)
                meta.Session.add(c.stay)
                meta.Session.flush()
                meta.Session.commit()
        else:
            c.stay = None

        c.realname = c.userobj.realname

        dummy, routes = get_route(tripuser(), c.trip.trip)
        c.derived_data = self.get_json_routeinfo(routes)

        c.totdist = 0.0
        if len(routes) > 0:
            c.totdist = routes[-1].accum_dist

        wp2route = dict()
        for rt in routes:
            wp2route[(rt.waypoint1, rt.waypoint2)] = rt

        def get(what, a, b):
            #print "A:<%s>"%(what,),a.pos,b.pos
            route = wp2route.get((a.id, b.id), None)

            if route:
                if what in ['TT', 'D', 'Var']:
                    bear, dist = route.tt, route.d  #mapper.bearing_and_distance(a.pos,b.pos)
                    #print "Bear,dist:",bear,dist
                    if what == 'TT':
                        return "%03.0f" % (bear, )
                    elif what == 'D':
                        return "%.1f" % (dist, )
                    elif what == 'Var':
                        var = route.variation
                        return "%+.0f" % (round(var), )
                if what in ['W', 'V', 'Alt', 'TAS', 'Dev']:
                    #routes=list(meta.Session.query(Route).filter(sa.and_(
                    #    Route.user==tripuser(),Route.trip==session['current_trip'],
                    #    Route.waypoint1==a.id,Route.waypoint2==b.id)).all())
                    if what == 'W':
                        return "%03.0f" % (route.winddir)
                    elif what == 'V':
                        return "%.0f" % (route.windvel)
                    elif what == 'Alt':
                        try:
                            #print "Parsing elev:",route.altitude
                            mapper.parse_elev(route.altitude)
                        except Exception, cause:
                            #print "couldn't parse elev:",route.altitude
                            return "1500"
                        return route.altitude
                    elif what == 'Dev':
                        #print "Dev is:",repr(route.deviation)
                        return "%.0f" % (
                            route.deviation) if route.deviation != None else ''
                    elif what == 'TAS':
                        #print "A:<%s>"%(what,),a.id,b.id,route.tas,id(route)
                        if not route.tas:
                            return 75
                        return "%.0f" % (route.tas)
                return ""

            return ""
Exemplo n.º 12
0
                        except Exception:
                            setattr(route, att, 0)
                    #print "Setting attrib '%s' of object %s to '%s'"%(att,route,val)

            if not tripsharing.sharing_active():
                acname = request.params.get('aircraft', '').strip()
                if acname != "":
                    c.trip.aircraft = acname

            meta.Session.flush()
            meta.Session.commit()
        except Exception, cause:
            log.error("Save flightplan failed! %s" % (cause, ))
            return ''

        return self.get_json_routeinfo(get_route(tripuser(), c.trip.trip)[1])

    def optimize(self):
        if not self.validate(exception=False,
                             tripname=request.params.get('tripname', False)):
            return ""

        #for rt in c.route:
        #    rt.maxobstelev=get_obstacle_free_height_on_line(
        ##            mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos))
        # #   print "Max obst elev",rt.maxobstelev
        strat = request.params.get('strategy', 'time')
        print "Strategy", strat
        resultcode, routes = calc_route_info.get_optimized(
            tripuser(), c.trip.trip, strat)
        if resultcode == False:
Exemplo n.º 13
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.º 14
0
    def obstacles(self):    
        routes,baseroute=get_route(tripuser(),session['current_trip'])
        
        tripobj=meta.Session.query(Trip).filter(sa.and_(
            Trip.user==tripuser(),Trip.trip==session['current_trip'])).one()
        c.trip=tripobj.trip
        id2order=dict([(rt.a.id,rt.a.ordering) for rt in baseroute])
        byidsorted=sorted(self.get_obstacles(routes).items(),key=lambda x:id2order.get(x[0],0))
        out=[]
        def classify(item):
            #print item
            vertlimit=1000
            if item.get('kind',None)=='lowsun':
                return "#ffffb0"            
            if item.get('kind',None)=='terrain':
                vertlimit=500                
            try:
                margin=item['closestalt']-mapper.parse_elev(item['elev'])
            except Exception:
                return "#0000ff" #Unknown margin, unknown height
            if item['dist']>0.6/1.852:
                return None #Not really too close anyway
            if margin<0:
                return "#ff3030"
            if margin<vertlimit:
                return "#ffb0b0"
            return None    
            
        dupecheck=dict()
        for idx,items in byidsorted:
            for item in items:
                ident=(item['name'],item['pos'],item.get('elev',None))
                dupecheck.setdefault(ident,[]).append(item)
        bestdupe=dict()
        for ident,dupes in dupecheck.items():
            best=min(dupes,key=lambda x:x['dist'])
            bestdupe[ident]=best
            
        for idx,items in byidsorted:
            cur=[]
            for item in items:
                dist_from_a=item['dist_from_a']
                dist_from_b=item['dist_from_b']

                if abs(dist_from_a)<0.5:
                    descr="Near %s"%(item['a'].waypoint,)
                elif abs(dist_from_b)<0.5:
                    descr="Near %s"%(item['b'].waypoint,)
                elif dist_from_a<dist_from_b:
                    descr="%.0fNM %s of %s"%(dist_from_a,item['dir_from_a'],item['a'].waypoint)
                else:
                    descr="%.0fNM %s of %s"%(dist_from_b,item['dir_from_b'],item['b'].waypoint)
                
                    
                ident=(item['name'],item['pos'],item.get('elev',None))
                best=bestdupe[ident]
                if not (best is item): continue
                
                
                #if ident in seen: continue
                #seen.add(ident)
                cur.append(dict(
                    routepointdescr=descr,
                    #dir_from_a=item['dir_from_a'],
                    #fromwhat=fromwhat,
                    kind=item.get('kind',None),
                    bearing=item.get('bearing',None),
                    along_nm=dist_from_a,                    
                    dist=item['dist'],
                    name=item['name'],
                    closestalt=item['closestalt'],
                    elev=item.get('elev',None)))
                cur[-1]['color']=classify(cur[-1])
            out.append((items[0]['a'].waypoint,sorted(cur,key=lambda x:x['along_nm'])))

        
        c.items=out
        return render('/obstacles.mako')
Exemplo n.º 15
0
 def index(self):
     if not self.validate(exception=False):
         redirect(h.url_for(controller='mapview',action="index"))
     
     c.flash=request.params.get('flash',None)
     c.waypoints=list(meta.Session.query(Waypoint).filter(sa.and_(
          Waypoint.user==tripuser(),Waypoint.trip==c.trip.trip)).order_by(Waypoint.ordering).all())
     
     if len(c.waypoints):        
         wp0=c.waypoints[0]
         if wp0.stay!=None:
             c.stay=wp0.stay
         else:
             #print "No 'Stay', adding"
             c.stay=Stay(c.trip.user,c.trip.trip,wp0.id)
             meta.Session.add(c.stay)
             meta.Session.flush()
             meta.Session.commit()
     else:
         c.stay=None
             
     c.realname=c.userobj.realname
     
     dummy,routes=get_route(tripuser(),c.trip.trip)
     c.derived_data=self.get_json_routeinfo(routes)
      
     c.totdist=0.0
     if len(routes)>0:
         c.totdist=routes[-1].accum_dist
     
     wp2route=dict()
     for rt in routes:
         wp2route[(rt.waypoint1,rt.waypoint2)]=rt
     def get(what,a,b):
         #print "A:<%s>"%(what,),a.pos,b.pos
         route=wp2route.get((a.id,b.id),None)
         
         if route:                
             if what in ['TT','D','Var']:
                 bear,dist=route.tt,route.d #mapper.bearing_and_distance(a.pos,b.pos)
                 #print "Bear,dist:",bear,dist
                 if what=='TT':
                     return "%03.0f"%(bear,)
                 elif what=='D':
                     return "%.1f"%(dist,)
                 elif what=='Var':
                     var=route.variation
                     return "%+.0f"%(round(var),)
             if what in ['W','V','Alt','TAS','Dev']:
                 #routes=list(meta.Session.query(Route).filter(sa.and_(
                 #    Route.user==tripuser(),Route.trip==session['current_trip'],
                 #    Route.waypoint1==a.id,Route.waypoint2==b.id)).all())
                 if what=='W':
                     return "%03.0f"%(route.winddir)
                 elif what=='V':
                     return "%.0f"%(route.windvel)
                 elif what=='Alt':
                     try:
                         #print "Parsing elev:",route.altitude
                         mapper.parse_elev(route.altitude)
                     except Exception,cause:
                         #print "couldn't parse elev:",route.altitude
                         return "1500"
                     return route.altitude                    
                 elif what=='Dev':
                     #print "Dev is:",repr(route.deviation)
                     return "%.0f"%(route.deviation) if route.deviation!=None else ''   
                 elif what=='TAS':
                     #print "A:<%s>"%(what,),a.id,b.id,route.tas,id(route)
                     if not route.tas:
                         return 75                        
                     return "%.0f"%(route.tas)
             return ""            
             
         return ""
Exemplo n.º 16
0
                 #print "Setting attrib '%s' of object %s to '%s'"%(att,route,val)
         
         if not tripsharing.sharing_active():
             acname=request.params.get('aircraft','').strip()
             if acname!="":
                 c.trip.aircraft=acname
               
             
             
         meta.Session.flush()
         meta.Session.commit()
     except Exception,cause:
         log.error("Save flightplan failed! %s"%(cause,))
         return ''
     
     return self.get_json_routeinfo(get_route(tripuser(),c.trip.trip)[1])
 
 def optimize(self):
     if not self.validate(exception=False,tripname=request.params.get('tripname',False)):
         return ""
     
     #for rt in c.route:
     #    rt.maxobstelev=get_obstacle_free_height_on_line(
     ##            mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos))
     # #   print "Max obst elev",rt.maxobstelev
     strat=request.params.get('strategy','time')
     print "Strategy",strat
     resultcode,routes=calc_route_info.get_optimized(tripuser(),c.trip.trip,
                         strat)
     if resultcode==False:
         return ""