Example #1
0
def great_circle(point_a, point_b):
    point_a = (point_a[1], point_a[0])
    point_b = (point_b[1], point_b[0])
    point_a = nv.GeoPoint(point_a[0], point_a[1], degrees=True)
    point_b = nv.GeoPoint(point_b[0], point_b[1], degrees=True)
    d, _a1, _a2 = point_a.distance_and_azimuth(point_b)
    return d
Example #2
0
def lookup_corners(symbol=None, id=None):
    bin = 'lookupCorners'
    if symbol is not None:
        command = (bin_folder+bin, '--quiet', '--latlon', '--symbol', symbol)
    elif id is not None:
        command = (bin_folder+bin, '--quiet', '--latlon', '--id', str(id))
    popen = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
    output = popen.communicate()[0].replace('\n', ' ').split(' ')
    corner1 = nvector.GeoPoint(float(output[0]), float(output[1]), degrees=True)
    corner2 = nvector.GeoPoint(float(output[2]), float(output[3]), degrees=True)
    corner3 = nvector.GeoPoint(float(output[4]), float(output[5]), degrees=True)
    return corner1, corner2, corner3
Example #3
0
def _cross_track_point(path, point):
    """Extend nvector package to find the projection point.

    The projection point is the closest point on path to the given point.
    Based on the nvector.cross_track_distance function.
    http://www.navlab.net/nvector/

    :param path: GeoPath
    :param point: GeoPoint
    """
    c_E = great_circle_normal(*path.nvector_normals())
    n_EB_E = point.to_nvector().normal  # type: np.array
    c_EP_E = np.cross(c_E, n_EB_E, axis=0)

    # Find intersection point C that is closest to point B
    frame = path.positionA.frame
    n_EA1_E = path.positionA.to_nvector(
    ).normal  # should also be ok to use  n_EB_C
    n_EC_E_tmp = unit(np.cross(c_E, c_EP_E, axis=0), norm_zero_vector=np.nan)
    n_EC_E = np.sign(np.dot(n_EC_E_tmp.T, n_EA1_E)) * n_EC_E_tmp
    if np.any(np.isnan(n_EC_E)):
        raise Exception(
            'Paths are Equal. Intersection point undefined. NaN returned.')
    lat_C, long_C = n_E2lat_lon(n_EC_E, frame.R_Ee)
    return nv.GeoPoint(lat_C, long_C, frame=frame)
Example #4
0
def get_midpoint(lat1, lon1, lat2, lon2):

    points = nvector.GeoPoint(latitude=[lat1, lat2],
                              longitude=[lon1, lon2],
                              degrees=True)
    nvectors = points.to_nvector()
    n_EM_E = nvectors.mean()
    g_EM_E = n_EM_E.to_geo_point()
    lat, lon = g_EM_E.latitude_deg, g_EM_E.longitude_deg

    return lat[0], lon[0]
Example #5
0
def _get_centroid(lat: pd.Series, lon: pd.Series) -> tuple:
    # TODO: currently getting centroid of turbines installed anytime. Get centroid for each day instead!
    # TODO: currently getting geospatial centroid. Get power-weighted centroid instead!
    points = nv.GeoPoint(
        latitude=lat.values,
        longitude=lon.values,
    )
    vectors = points.to_nvector()
    centroid_vector = vectors.mean()
    centroid = centroid_vector.to_geo_point()
    return (centroid.latitude_deg, centroid.longitude_deg)
def getBusinessScreennerResult():
    client = foursquare.Foursquare(client_id=CLIENT_ID,
                                   client_secret=CLIENT_SECRET)
    categoryId = request.args.get('categoryId', None)
    location = request.args.get('location', None)
    venuelist = client.venues.search(params={
        'near': location,
        'categoryId': categoryId
    })
    venuedict = {
        venue['location']['lat']: venue['location']['lng']
        for venue in venuelist['venues']
    }

    df = pd.DataFrame()
    df['lat'] = venuedict.keys()
    df['lng'] = venuedict.values()
    coords = df.as_matrix(columns=['lat', 'lng'])

    kms_per_radian = 6371.0088
    epsilon = 5 / kms_per_radian
    db = DBSCAN(eps=epsilon,
                min_samples=1,
                algorithm='ball_tree',
                metric='haversine').fit(np.radians(coords))
    cluster_labels = db.labels_
    num_clusters = len(set(cluster_labels))
    clusters = pd.Series(
        [coords[cluster_labels == n] for n in range(num_clusters)])
    print('Number of clusters: {}'.format(num_clusters))

    centermost_points = clusters.map(get_centermost_point)

    listpoints = [x[1] for x in centermost_points.iteritems()]

    locationpeers = list(itertools.combinations(listpoints, 2))

    returnPeers = []
    for eachPair in locationpeers:
        latitude = []
        longitude = []
        for eachpt in eachPair:
            latitude.append(eachpt[0])
            longitude.append(eachpt[1])
        points = nv.GeoPoint(latitude, longitude, degrees=True)
        nvectors = points.to_nvector()
        n_EM_E = nvectors.mean_horizontal_position()
        g_EM_E = n_EM_E.to_geo_point()
        lat, lon = g_EM_E.latitude_deg, g_EM_E.longitude_deg
        returnPeers.append((lat[0], lon[0]))

    return str(returnPeers)
Example #7
0
        zoom = 1
        self.ax.set_xlim([-self.radius / zoom, self.radius / zoom])
        self.ax.set_ylim([-self.radius / zoom, self.radius / zoom])
        self.ax.set_zlim([-self.radius / zoom, self.radius / zoom])

    def save_fig(self, filename):
        self.ax.set_aspect('equal')
        self.ax.axis('off')
        plt.savefig(filename, dpi=300)

    def show(self):
        plt.show()


if __name__ == '__main__':
    import nvector
    a = nvector.GeoPoint(10, 10, degrees=True)
    b = nvector.GeoPoint(20, 20, degrees=True)
    path = nvector.GeoPath(a, b)
    xs = []
    ys = []
    zs = []
    n_steps = 5
    for step in range(n_steps + 1):
        pvector = path.interpolate(step / n_steps).to_ecef_vector().pvector
        xs.append(pvector[0][0])
        ys.append(pvector[1][0])
        zs.append(pvector[2][0])
    plt = SpherePlot(radius=10)

Example #8
0
import nvector as nv
points = nv.GeoPoint(
    latitude=[-90, -77.8564],
    longitude=[166.6881, 166.6881],
    degrees=True,
)
nvectors = points.to_nvector()
n_EM_E = nvectors.mean()
g_EM_E = n_EM_E.to_geo_point()
lat, lon = g_EM_E.latitude_deg, g_EM_E.longitude_deg
print('Midpt. Lat: %2.2f, Lon: %2.2f' % (lat, lon))
Example #9
0
    def filter(self, chain):
        assert isinstance(chain, ADSBModeSChain)

        #print('UMKalmanFilter2D: filtering chain utn {} ta {}'.format(chain.utn, hex(chain.target_address)))

        assert len(chain.target_reports)

        # calculate center_lat, center_long
        center_lat = 0
        center_long = 0

        for tod, target_report in chain.target_reports.items(
        ):  # type: ADSBTargetReport
            center_lat += target_report.get("pos_lat_deg")
            center_long += target_report.get("pos_long_deg")

        center_lat /= len(chain.target_reports)
        center_long /= len(chain.target_reports)

        center_pos = nv.GeoPoint(center_lat, center_long, 0, degrees=True)

        #print('UMKalmanFilter2D: center latitude {} longitude {} z {}'.format(center_pos.latitude_deg, center_pos.longitude_deg, center_pos.z))

        first = True
        time_last = None
        z_last = None

        ts = []
        zs = []
        Fs = []
        Qs = []
        Rs = []
        zval = []

        # process
        for tod, target_report in chain.target_reports.items(
        ):  # type: float,ADSBTargetReport
            #data_point 0: time, 1: x, 2: y, 3: fl, 4: date

            #print('UMKalmanFilter2D: target_report {}'.format(target_report.position.getGeoPosStr()))

            x, y, z = target_report.position.getENU(
                center_pos)  # east, north, up

            #tmp = GeoPosition()
            #tmp.setENU(x, y, z, center_pos)
            #print('org {} tmp {}'.format(target_report.position.getGeoPosStr(), tmp.getGeoPosStr()))

            #print('point tod {} x {} y {} z {}'.format(tod, x, y, z))

            groundspeed_kt = target_report.get('groundspeed_kt')
            track_angle_deg = target_report.get('track_angle_deg')

            got_speed = groundspeed_kt is not None and track_angle_deg is not None

            if got_speed:
                track_angle_rad = np.deg2rad(
                    90 - track_angle_deg)  # convert to math angle and to rad
                groundspeed_ms = groundspeed_kt * 0.514444
                #print(' groundspeed kt {} ms {}'.format(groundspeed_kt, groundspeed_ms))

                v_x = groundspeed_ms * np.cos(track_angle_rad)
                v_y = groundspeed_ms * np.sin(track_angle_rad)
            else:
                v_x = 0
                v_y = 0

            if first:
                self.f.x = np.array([[x, v_x, y, v_y, z, 0]]).T
                time_last = tod
                z_last = z

                first = False
                #continue

            # z = get_sensor_reading()
            time_current = tod
            dt = time_current - time_last

            #if dt == 0:
            #    print('{}: skipping same-time point at {}'.format(self.name, time_current))
            #    continue

            #print ('dt {}'.format(dt))
            #assert dt > 0

            #ts.append((data_point[4], time_current)) #date,time
            ts.append(tod)

            # state transition matrix:, set time dependent
            Fs.append(
                np.array([[1, dt, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0],
                          [0, 0, 1, dt, 0, 0], [0, 0, 0, 1, 0, 0],
                          [0, 0, 0, 0, 1, dt], [0, 0, 0, 0, 0, 1]]))

            # the process noise, set time dependent
            #self.f.Q = Q_discrete_white_noise(dim=4, dt=dt, var=self.Q_std ** 2)
            #Qs.append(Q_continuous_white_noise(dim=2, dt=dt, spectral_density=self.Q_std ** 2, block_size=2))
            Qs.append(
                Q_discrete_white_noise(dim=2,
                                       dt=dt,
                                       var=self.Q_std**2,
                                       block_size=3))

            # measurement
            zs.append(np.array([x, v_x, y, v_y, z, z_last - z]))

            # measurement noise
            pos_acc_stddev_m = None
            spd_acc_stddev_ms = None

            nucr_nacv = target_report.get('nucr_nacv')
            got_spd_acc = nucr_nacv is not None

            if target_report.get("mops_version") is not None:
                vn = target_report.get("mops_version")

                if vn == 0:
                    nucp_nic = target_report.get("nucp_nic")
                    if nucp_nic is not None and nucp_nic in v0_pos_accuracies:
                        pos_acc_stddev_m = v0_pos_accuracies[nucp_nic]

                    if got_spd_acc and nucr_nacv in v0_spd_accuracies:
                        spd_acc_stddev_ms = v0_spd_accuracies[nucr_nacv]

                elif vn == 1 or vn == 2:
                    nac_p = target_report.get("nac_p")
                    if nac_p is not None and nac_p in v12_pos_accuracies:
                        pos_acc_stddev_m = v12_pos_accuracies[nac_p]

                    if got_spd_acc and nucr_nacv in v12_spd_accuracies:
                        spd_acc_stddev_ms = v12_spd_accuracies[nucr_nacv]

            if pos_acc_stddev_m is None:
                pos_acc_stddev_m = 50  # m stddev default noise

            if spd_acc_stddev_ms is None:
                spd_acc_stddev_ms = 10
            if not got_speed:  # velocities not set
                spd_acc_stddev_ms = self.big_noise_stddev

            #print('pos x {} y {}  v_x {} v_y {} pos_stddev {} v_stddev {}'.format(
            #    x, y, v_x, v_y, pos_acc_stddev_m, vel_acc_stddev_ms))

            Rs.append(
                np.array([[pos_acc_stddev_m**2, 0, 0, 0, 0, 0],
                          [0, spd_acc_stddev_ms**2, 0, 0, 0, 0],
                          [0, 0, pos_acc_stddev_m**2, 0, 0, 0],
                          [0, 0, 0, spd_acc_stddev_ms**2, 0, 0],
                          [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 10**2]]))

            #print target_report

            time_last = time_current

        (mu, cov, _, _) = self.f.batch_filter(zs=zs, Fs=Fs, Qs=Qs, Rs=Rs)

        #print('ts {} zs {} mu {} cov {}'.format(len(ts), len(zs), len(mu), len(cov)))
        assert len(ts) == len(zs) == len(mu) == len(cov)

        (mu_smoothed, cov_smoothed, K, Pp) = rts_smoother(mu, cov, Fs, Qs)

        reconstructed = ReconstructedADSBModeSChain(chain.utn,
                                                    chain.target_address)
        reconstructed.target_reports = chain.target_reports

        for cnt in range(0, len(mu)):  # until len(mu)-1
            tod = ts[cnt]
            assert tod in chain.target_reports

            target_report = chain.target_reports[tod]  # type: ADSBTargetReport

            # filtered
            ref_fil = ReferenceUpdate(chain.utn, tod)
            ref_fil.fromADSBTargetReport(target_report)
            ref_fil.sac = 0
            ref_fil.sic = 0

            #print('\ntod {}'.format(tod))

            #print('org x {} y {}'.format(zs[cnt][0], zs[cnt][1]))
            # x mu[cnt][0][0], y mu[cnt][2][0]
            ref_fil_pos = GeoPosition()
            #print('fil x {} y {}'.format(mu[cnt][0][0], mu[cnt][2][0]))
            ref_fil_pos.setENU(mu[cnt][0][0], mu[cnt][2][0], mu[cnt][4][0],
                               center_pos)

            ref_fil.pos_lat_deg, ref_fil.pos_long_deg, _ = ref_fil_pos.getGeoPos(
            )

            #print('cov {}'.format(cov[cnt]))

            stddev_x = math.sqrt(cov[cnt][0][0])
            stddev_y = math.sqrt(cov[cnt][2][2])
            cov_xy = cov[cnt][0][2]

            ref_fil.pos_std_dev_x_m = stddev_x
            ref_fil.pos_std_dev_xy_corr_coeff = cov_xy
            ref_fil.pos_std_dev_y_m = stddev_y

            #print('fil stddev_x {} stddev_y {} cov_xy {}'.format(stddev_x, stddev_y, cov_xy))

            d_lat, d_long = ref_fil_pos.getLatLongDelta(stddev_y, stddev_x)
            cov_latlong = cov_xy * (d_lat / stddev_x) * (d_long / stddev_y)
            #print('d_lat {} d_long {} cov_latlong {}'.format(d_lat, d_long, cov_latlong))

            ref_fil.pos_std_dev_lat_deg = d_lat
            ref_fil.pos_std_dev_latlong_corr_coeff = cov_latlong
            ref_fil.pos_std_dev_long_deg = d_long

            v_x = mu[cnt][1][0]
            v_y = mu[cnt][3][0]

            heading_math_rad = math.atan2(v_y, v_x)
            heading_deg = 90 - np.rad2deg(heading_math_rad)

            groundspeed_ms = math.sqrt(v_x**2 + v_y**2)
            groundspeed_kt = groundspeed_ms / 0.514444

            ref_fil.heading_deg = heading_deg
            ref_fil.groundspeed_kt = groundspeed_kt

            reconstructed.filtered_target_reports[tod] = ref_fil

            # smoothed
            ref_smo = ReferenceUpdate(chain.utn, tod)
            ref_smo.fromADSBTargetReport(target_report)
            ref_smo.sac = 0
            ref_smo.sic = 1

            ref_smo_pos = GeoPosition()
            #print('smo x {} y {}'.format(mu_smoothed[cnt][0][0], mu_smoothed[cnt][2][0]))
            ref_smo_pos.setENU(mu_smoothed[cnt][0][0], mu_smoothed[cnt][2][0],
                               mu_smoothed[cnt][4][0], center_pos)

            ref_smo.pos_lat_deg, ref_fil.pos_long_deg, _ = ref_fil_pos.getGeoPos(
            )

            stddev_x = math.sqrt(cov_smoothed[cnt][0][0])
            stddev_y = math.sqrt(cov_smoothed[cnt][2][2])
            cov_xy = cov_smoothed[cnt][0][2]

            ref_smo.pos_std_dev_x_m = stddev_x
            ref_smo.pos_std_dev_xy_corr_coeff = cov_xy
            ref_smo.pos_std_dev_y_m = stddev_y

            #print('smo stddev_x {} stddev_y {} cov_xy {}'.format(stddev_x, stddev_y, cov_xy))

            d_lat, d_long = ref_smo_pos.getLatLongDelta(stddev_y, stddev_x)
            cov_latlong = cov_xy * (d_lat / stddev_x) * (d_long / stddev_y)
            #print('\nrs_stddev_y {} rs_stddev_x {}'.format(math.sqrt(Rs[cnt][0][0]), math.sqrt(Rs[cnt][2][2])))
            #print('stddev_y {} stddev_x {}'.format(stddev_y, stddev_x))
            #print('d_lat {} d_long {} cov_latlong {}'.format(d_lat, d_long, cov_latlong))

            ref_smo.pos_std_dev_lat_deg = d_lat
            ref_smo.pos_std_dev_latlong_corr_coeff = cov_latlong
            ref_smo.pos_std_dev_long_deg = d_long

            v_x = mu_smoothed[cnt][1][0]
            v_y = mu_smoothed[cnt][3][0]

            heading_math_rad = math.atan2(v_y, v_x)
            heading_deg = 90 - np.rad2deg(heading_math_rad)

            groundspeed_ms = math.sqrt(v_x**2 + v_y**2)
            groundspeed_kt = groundspeed_ms / 0.514444

            ref_smo_pos.heading_deg = heading_deg
            ref_smo_pos.groundspeed_kt = groundspeed_kt

            reconstructed.smoothed_target_reports[tod] = ref_smo

            #print('org {}'.format(target_report.position.getGeoPosStr()))
            #print('fil {}'.format(ref_fil_pos.getGeoPosStr()))
            #print('smo {}'.format(ref_smo_pos.getGeoPosStr()))

        return reconstructed