Esempio n. 1
0
    def test_constructor(self):
        # Check that only Location instances are accepted
        assert_raises(ValueError, Bounds, 3, 5)

        sw = Location(latitude=49, longitude=6)
        ne = Location(latitude=51, longitude=7)
        b = Bounds(sw, ne)

        eq_(b.southwest.latitude, 49)
        eq_(b.southwest.longitude, 6)
        eq_(b.northeast.latitude, 51)
        eq_(b.northeast.longitude, 7)
Esempio n. 2
0
def test_constructor():
    # Check that only Location instances are accepted
    with pytest.raises(ValueError):
        Bounds(3, 5)

    sw = Location(latitude=49, longitude=6)
    ne = Location(latitude=51, longitude=7)
    b = Bounds(sw, ne)

    assert b.southwest.latitude == 49
    assert b.southwest.longitude == 6
    assert b.northeast.latitude == 51
    assert b.northeast.longitude == 7
Esempio n. 3
0
def _get_takeoff_locations(user):
    locations = Location.get_clustered_locations(
        Flight.takeoff_location_wkt,
        filter=and_(Flight.pilot == user, Flight.is_rankable()),
    )

    return [loc.to_lonlat() for loc in locations]
Esempio n. 4
0
def near(flight_id):
    flight = get_requested_record(Flight,
                                  flight_id,
                                  joinedload=[Flight.igc_file])

    current_user = User.get(request.user_id) if request.user_id else None
    if not flight.is_viewable(current_user):
        return jsonify(), 404

    try:
        latitude = float(request.args['lat'])
        longitude = float(request.args['lon'])
        time = float(request.args['time'])

    except (KeyError, ValueError):
        abort(400)

    location = Location(latitude=latitude, longitude=longitude)
    time = from_seconds_of_day(flight.takeoff_time, time)

    flights = _get_near_flights(flight, location, time, 1000)

    def add_flight_path(flight):
        trace = _get_flight_path(flight, threshold=0.0001, max_points=10000)
        trace['additional'] = dict(registration=flight.registration,
                                   competition_id=flight.competition_id)

        return trace

    return jsonify(flights=map(add_flight_path, flights))
Esempio n. 5
0
def _get_takeoff_locations(user):
    locations = Location.get_clustered_locations(
        Flight.takeoff_location_wkt,
        filter=and_(Flight.pilot == user, Flight.is_rankable()),
    )

    return [loc.to_lonlat() for loc in locations]
Esempio n. 6
0
def cumulative_distance(fixes, start_fix, end_fix):
    if start_fix >= end_fix:
        return 0

    distance = 0
    last_location = None

    for fix in fixes[start_fix:end_fix + 1]:
        location = Location(longitude=fix.location['longitude'], latitude=fix.location['latitude'])

        if last_location:
            distance += location.geographic_distance(last_location)

        last_location = location

    return distance
Esempio n. 7
0
def parse_location(args):
    try:
        latitude = float(args["lat"])
        longitude = float(args["lon"])
        return Location(latitude=latitude, longitude=longitude)

    except (KeyError, ValueError):
        abort(400)
Esempio n. 8
0
def parse_location():
    try:
        latitude = float(request.args['lat'])
        longitude = float(request.args['lon'])
        return Location(latitude=latitude, longitude=longitude)

    except (KeyError, ValueError):
        abort(400)
Esempio n. 9
0
def cumulative_distance(fixes, start_fix, end_fix):
    if start_fix >= end_fix:
        return 0

    distance = 0
    last_location = None

    for fix in fixes[start_fix:end_fix + 1]:
        location = Location(longitude=fix.location['longitude'],
                            latitude=fix.location['latitude'])

        if last_location:
            distance += location.geographic_distance(last_location)

        last_location = location

    return distance
Esempio n. 10
0
def _get_near_flights(flight, location, time, max_distance=1000):
    # calculate max_distance in degrees at the earth's sphere (approximate,
    # cutoff at +-85 deg)
    max_distance_deg = (max_distance / METERS_PER_DEGREE) / \
        math.cos(math.radians(min(abs(location.latitude), 85)))

    # the distance filter is geometric only, so max_distance must be given in
    # SRID units (which is degrees for WGS84). The filter will be more and more
    # inaccurate further to the poles. But it's a lot faster than the geograpic
    # filter...

    result = Flight.query() \
        .options(undefer_group('path')) \
        .filter(Flight.id != flight.id) \
        .filter(Flight.takeoff_time <= time) \
        .filter(Flight.landing_time >= time) \
        .filter(func.ST_DWithin(Flight.locations,
                                location.to_wkt_element(),
                                max_distance_deg))

    result = _patch_query(result)

    flights = []
    for flight in result:
        # find point closest to given time
        closest = min(range(len(flight.timestamps)),
                      key=lambda x: abs((flight.timestamps[x] - time).total_seconds()))

        trace = to_shape(flight.locations).coords

        if closest == 0 or closest == len(trace) - 1:
            point = trace[closest]
        else:
            # interpolate flight trace between two fixes
            next_smaller = closest if flight.timestamps[closest] < time else closest - 1
            next_larger = closest if flight.timestamps[closest] > time else closest + 1
            dx = (time - flight.timestamps[next_smaller]).total_seconds() / \
                 (flight.timestamps[next_larger] - flight.timestamps[next_smaller]).total_seconds()

            point_next = trace[closest]
            point_prev = trace[closest]

            point = [point_prev[0] + (point_next[0] - point_prev[0]) * dx,
                     point_prev[1] + (point_next[1] - point_prev[1]) * dx]

        point_distance = location.geographic_distance(
            Location(latitude=point[1], longitude=point[0]))

        if point_distance > max_distance:
            continue

        flights.append(flight)

        # limit to 5 flights
        if len(flights) == 5:
            break

    return flights
Esempio n. 11
0
def first(flight, **kwargs):
    return ContestLeg(
        flight=flight,
        contest_type="olc_plus",
        trace_type="classic",
        distance=234833,
        cruise_height=-6491,
        cruise_distance=241148,
        cruise_duration=timedelta(seconds=7104),
        climb_height=6510,
        climb_duration=timedelta(seconds=5252),
        start_height=1234,
        end_height=1253,
        start_time=flight.takeoff_time + timedelta(minutes=5),
        end_time=flight.takeoff_time + timedelta(minutes=53),
        start_location=Location(51.4, 7.1),
        end_location=Location(52.5, 7.8),
    ).apply_kwargs(kwargs)
Esempio n. 12
0
def olc_classic(flight, **kwargs):
    return Trace(
        flight=flight,
        contest_type="olc_plus",
        trace_type="classic",
        distance=725123,
        duration=timedelta(hours=6.53),
        times=[
            datetime(2016, 8, 17, 9, 53, 22),
            datetime(2016, 8, 17, 11, 32, 29),
            datetime(2016, 8, 17, 14, 2, 54),
            datetime(2016, 8, 17, 16, 43, 43),
        ],
        locations=[
            Location(51.3, 7.1),
            Location(51.6, 9.3),
            Location(50.2, 5.8),
            Location(51.3, 7.1),
        ],
    ).apply_kwargs(kwargs)
Esempio n. 13
0
def _get_flight_path(pilot, threshold=0.001, last_update=None):
    fp = _get_flight_path2(pilot, last_update=last_update)
    if not fp:
        return None

    num_levels = 4
    zoom_factor = 4
    zoom_levels = [0]
    zoom_levels.extend([
        round(-log(
            32.0 / 45.0 *
            (threshold * pow(zoom_factor, num_levels - i - 1)), 2))
        for i in range(1, num_levels)
    ])

    xcsoar_flight = xcsoar.Flight(fp)

    xcsoar_flight.reduce(num_levels=num_levels,
                         zoom_factor=zoom_factor,
                         threshold=threshold)

    encoded_flight = xcsoar_flight.encode()

    points = encoded_flight["locations"]
    barogram_t = encoded_flight["times"]
    barogram_h = encoded_flight["altitude"]
    enl = encoded_flight["enl"]

    fp_reduced = map(lambda line: FlightPathFix(*line), xcsoar_flight.path())
    elevations = xcsoar.encode(
        [
            fix.elevation if fix.elevation is not None else UNKNOWN_ELEVATION
            for fix in fp_reduced
        ],
        method="signed",
    )

    geoid_height = egm96_height(
        Location(latitude=fp[0].location["latitude"],
                 longitude=fp[0].location["longitude"]))

    return dict(
        points=points,
        barogram_t=barogram_t,
        barogram_h=barogram_h,
        enl=enl,
        elevations=elevations,
        geoid=geoid_height,
    )
Esempio n. 14
0
def read_location(node):
    """
    Reads the latitude and longitude attributes of the node
    and returns a Location instance if the node was parsed correctly.
    """

    if node is None:
        return None

    if 'latitude' not in node or 'longitude' not in node:
        return None

    try:
        latitude = float(node['latitude'])
        longitude = float(node['longitude'])
        return Location(latitude=latitude, longitude=longitude)
    except ValueError:
        return None
Esempio n. 15
0
def near():
    try:
        latitude = float(request.args['lat'])
        longitude = float(request.args['lon'])
        time = float(request.args['time'])

    except (KeyError, ValueError):
        abort(400)

    location = Location(latitude=latitude, longitude=longitude)
    time = from_seconds_of_day(g.flight.takeoff_time, time)

    flights = _get_near_flights(g.flight, location, time, 1000)

    def add_flight_path(flight):
        trace = _get_flight_path(flight, threshold=0.0001, max_points=10000)
        trace['additional'] = dict(registration=flight.registration,
                                   competition_id=flight.competition_id)

        return trace

    return jsonify(flights=map(add_flight_path, flights))
Esempio n. 16
0
def _get_takeoff_locations():
    return Location.get_clustered_locations(
        Flight.takeoff_location_wkt,
        filter=and_(Flight.pilot == g.user, Flight.is_rankable()))
Esempio n. 17
0
def _get_takeoff_locations():
    return Location.get_clustered_locations(Flight.takeoff_location_wkt,
                                            filter=(Flight.pilot == g.user))
Esempio n. 18
0
def _get_takeoff_locations():
    return Location.get_clustered_locations(Flight.takeoff_location_wkt,
                                            filter=and_(
                                                Flight.pilot == g.user,
                                                Flight.is_rankable()))
Esempio n. 19
0
def test_by_location_returns_none_by_default():
    assert TimeZone.by_location(Location(longitude=10, latitude=10)) is None
Esempio n. 20
0
def test_by_location_returns_timezone():
    tz = TimeZone.by_location(Location(longitude=20, latitude=30))
    assert tz is not None
    assert tz.zone == "Europe/Berlin"