Exemple #1
0
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)

        # hacky config file validation for bad or missing coords

        # we have to store or it would draw under the dials
        settings_modal = None

        try:
            pt = Point(self.config_latlon)
        except ValueError:

            pt = Point()
            settings_modal = SettingsScreen()
            settings_modal.config_friendlyname = ''

            if self.config_latlon != '':
                settings_modal.feedback.text =\
                    "Invalid location detected in config, please select a new location"
                self.config_latlon = ''

        self.dial_widget = DialWidget(latlon_point=pt)
        self.now_marker = NowMarker()
        self.season_dial = SeasonDial()

        self.add_widget(self.dial_widget)
        self.add_widget(self.now_marker)
        self.add_widget(self.season_dial)

        # workaround for kivy's LIFO draw order
        if settings_modal is not None:
            Clock.schedule_once(lambda dt: settings_modal.open(), 0.5)
Exemple #2
0
    def radius_filter(self, row):
# afaik the DB doesn't have geocapability, so this is a favela-chic way of doing a bounding radius select.
        p = Point(row['lat'], row['lon'], row['alt'])
        me = Point(self.qst['lat'], self.qst['lon'], self.qst['alt'])
        dist = Distance.distance(p, me)
        if dist <= self.qst['search_radius']:
            return True
Exemple #3
0
    def __init__(self, host, port, tenant, device, latitude, longitude,
                 movement):
        self.__logger = logging.getLogger('trackingsim.sim')
        self.__origin = Point(latitude, longitude)
        self.__current_position = Point(latitude, longitude)
        self.__mqttc = mqtt.Client("{}:{}".format(tenant, device))
        self.__mqttc.username_pw_set("{}:{}".format(
            tenant, device))  # not necessary with iotagent-mosca
        self.__mqttc.connect(host=host, port=port)
        self.__mqttc.loop_start()
        self.__topic = "{0}:{1}/attrs".format(tenant, device)
        # self.__topic = "/{0}/{1}/attrs".format(tenant, device) # iotagent-mosca topic
        self.__sleep = np.random.uniform(self.__class__.MIN_SLEEP_TIME,
                                         self.__class__.MAX_SLEEP_TIME)
        self.__logger.info(
            "Starting simulation for device {0} with sleep time {1}".format(
                device, self.__sleep))

        if movement == 'straight-line':
            self.__next_movement = self.__get_next_position_for_straight_line
        else:
            self.__next_movement = self.__get_next_random_position

        # bearing displacement used in the last movement. Start with random values
        self.__displacement = \
            np.random.uniform(self.__class__.MIN_DISPLACEMENT, self.__class__.MAX_DISPLACEMENT)
        self.__bearing = \
            np.random.uniform(self.__class__.MIN_BEARING, self.__class__.MAX_BEARING)
Exemple #4
0
 def assert_expected(expected):
     found = False
     for r in results['features']:
         passed = True
         properties = None
         if 'geocoding' in r['properties']:
             properties = r['properties']['geocoding']
         else:
             properties = r['properties']
         failed = properties['failed'] = []
         for key, value in expected.items():
             value = str(value)
             if not compare_values(str(properties.get(key)), value):
                 # Value is not like expected. But in the case of
                 # coordinate we need to handle the tolerance.
                 if key == 'coordinate':
                     coord = r['geometry']['coordinates']
                     lat, lon, max_deviation = map(float, value.split(","))
                     deviation = distance(
                         Point(lat, lon),
                         Point(coord[1], coord[0])
                     )
                     if int(deviation.meters) <= int(max_deviation):
                         continue  # Continue to other properties
                     failed.append('distance')
                 passed = False
                 failed.append(key)
         if passed:
             found = True
     if not found:
         raise SearchException(
             params=params,
             expected=expected,
             results=results
         )
Exemple #5
0
def optimal_path(nodes, origin, dest):
    nodes = [Point(lats, longs) for lats, longs in nodes]
    origin = Point(origin)
    dest = Point(dest)

    waypoint_collec = [waypoint(origin, (origin, dest))]
    waypoint_collec += [waypoint(node, (origin, dest)) for node in nodes]

    to_dest = waypoint(dest, (origin, dest))

    waypoint_collec.append(to_dest)
    begin, remaining = waypoint_collec[0], waypoint_collec[1:]
    path = []

    # Check for the rang to see if its the nearest to the start point
    for i in range(MAX_STEPS):
        nearer = begin.nearest(remaining)
        if nearer is None:
            break

        path.append(nearer)
        remaining = [pot for pot in remaining if pot != nearer]
        begin = nearer

    # Does the path provide the correct destination?
    if to_dest in path:
        path.remove(to_dest)

    return '|'.join(["via:{},{}".format(pot.pot.latitude, pot.pot.longitude) for pot in path])
Exemple #6
0
    def calc_azimuth(self, from_crestnode_index, to_crestnode_index):
        # convenience function to calculate the azimuth between two crestnodes
        # note: this has to be done with rather elaborate vincenty distance
        #       calculations as latitude and longitude are not equal measures

        # Get the locations as lon, lat, z
        lon_A, lat_A, z_A = self.crestnodes[
            from_crestnode_index].geom.GetPoint()
        lon_B, lat_B, z_B = self.crestnodes[to_crestnode_index].geom.GetPoint()

        # Calculate A to B azimuth by setting a fake point to calc x and y
        fakepoint = Point(longitude=lon_A, latitude=lat_B)
        realpoint_A = Point(longitude=lon_A, latitude=lat_A)
        realpoint_B = Point(longitude=lon_B, latitude=lat_B)

        distance_x = VincentyDistance(fakepoint, realpoint_B).m
        distance_y = VincentyDistance(fakepoint, realpoint_A).m

        # correct distances with positive and negative signs
        if (lon_B - lon_A) < 0.0:
            distance_x = -1.0 * distance_x
        if (lat_B - lat_A) < 0.0:
            distance_y = -1.0 * distance_y

        azimuth = math.atan2(distance_x, distance_y)
        azimuth = math.degrees(azimuth)

        # correct azimuths to 0-360 scale
        if azimuth < 0.0:
            azimuth = azimuth + 360.0

        return azimuth
 def resolve_tweet(self, tweet):
     # The Twitter API allows tweet['coordinates'] to both be absent
     # and None, such that the key exists but has a None value.
     # "tweet.get('coordinates', {})" would return None in the latter
     # case, with None.get() in turn causing an AttributeError. (None
     # or {}), on the other hand, is {}, and {}.get() is okay.
     tweet_coordinates = (tweet.get('coordinates') or {}).get('coordinates')
     if not tweet_coordinates:
         return None
     tweet_coordinates = Point(longitude=tweet_coordinates[0],
                               latitude=tweet_coordinates[1])
     closest_candidate = None
     closest_distance = float('inf')
     for cell in self._cells_for(tweet_coordinates.latitude,
                                 tweet_coordinates.longitude):
         for candidate in self.location_map[cell]:
             candidate_coordinates = Point(candidate.latitude,
                                           candidate.longitude)
             distance = geopy_distance(tweet_coordinates,
                                       candidate_coordinates).miles
             if closest_distance > distance:
                 closest_candidate = candidate
                 closest_distance = distance
     if closest_distance < self.max_distance:
         return (False, closest_candidate)
     return None
Exemple #8
0
 def __init__(self,
              name,
              north=None,
              south=None,
              west=None,
              east=None,
              center=None,
              hashtags=set(),
              phrase='at',
              secondary=None):
     if center:
         self.center = Point(latitude=center[0], longitude=center[1])
     else:
         self.center = Point(latitude=(north + south) / 2,
                             longitude=(east + west) / 2)
     self.north = north
     self.south = south
     self.west = west
     self.east = east
     try:
         self.hashtags = hashtags
         self.hashtags.update(config.HASHTAGS)
     except NameError:
         self.hashtags = hashtags
     self.name = name
     self.phrase = phrase
Exemple #9
0
    def __init__(self, host, port, tenant, device, latitude, longitude,
                 movement):

        longitude = float(longitude) + np.random.uniform(
            self.__class__.RANGE_VARIATION_MIN,
            self.__class__.RANGE_VARIATION_MAX)
        latitude = float(latitude) + np.random.uniform(
            self.__class__.RANGE_VARIATION_MIN,
            self.__class__.RANGE_VARIATION_MAX)

        self.__logger = logging.getLogger('trackingsim.sim')
        self.__origin = Point(latitude, longitude)
        self.__current_position = Point(str(latitude), str(longitude))
        self.__mqttc = mqtt.Client(str(threading.current_thread().ident))
        self.__mqttc.connect(host=host, port=port)
        self.__mqttc.loop_start()
        self.__topic = "/{0}/{1}/attrs".format(tenant, device)
        self.__sleep = 10
        self.__logger.info(
            "Starting simulation for device {0} with sleep time {1}".format(
                device, self.__sleep))

        if movement == 'straight-line':
            self.__next_movement = self.__get_next_position_for_straight_line
        elif movement == 'static':
            self.__next_movement = self.__get_static_position
        else:
            self.__next_movement = self.__get_next_random_position

        # bearing displacement used in the last movement. Start with random values
        self.__displacement = \
            np.random.uniform(self.__class__.MIN_DISPLACEMENT, self.__class__.MAX_DISPLACEMENT)
        self.__bearing = \
            np.random.uniform(self.__class__.MIN_BEARING, self.__class__.MAX_BEARING)
Exemple #10
0
def get_distance_from_arrakeen_m(location):
    """Return distance from arrakeen in meters."""
    l = get_location(location)
    point_location = Point(l.latitude, l.longitude)
    point_arrakeen = Point(current_app.config['PAWEB_ARRAKEEN_LATITUDE'], \
                           current_app.config['PAWEB_ARRAKEEN_LONGITUDE'])
    return vincenty(point_location, point_arrakeen).m
Exemple #11
0
    def test_two_edge_path(self):
        first_start = data_factory.right_angle_start
        first_middle = data_factory.right_angle_middle
        first_end = data_factory.right_angle_end
        first_right_angled_road = data_factory.create_part(
            first_start, first_middle, first_end)

        second_start = first_end
        second_middle = Point('%.1f' % (first_end.latitude + 0.1),
                              first_end.longitude)
        second_end = Point('%.1f' % (first_end.latitude + 0.1),
                           '%.1f' % (first_end.longitude + 0.1))
        second_right_angled_road = data_factory.create_part(
            second_start, second_middle, second_end)

        shapefile = data_factory.create_shapefile([first_right_angled_road] +
                                                  [second_right_angled_road])

        networkx = convert._to_networkx_graph(shapefile)
        G = convert.load_graph_from_shapefile_records(networkx)

        actual_distance = distance.using_route(G, first_start, second_end)

        self.assertTrue(
            abs(actual_distance -
                (data_factory.right_angle_distance * 2)) < 1 * ureg.metre)
def get_distance(a, b):
    """
    origin (float, float): coordinates longitude, latitude, eg: (-122.7282, 45.5801)
    destination (float, float): coordinates
    return (float): in m
    """
    return geodistance(Point(a[1], a[0]), Point(b[1], b[0])).meters
Exemple #13
0
def best_path(nodes, origin, dest):
    # import pdb; pdb.set_trace()
    # I'll convert my own damn parameters.
    nodes = [Point(lat, lng) for lat, lng in nodes]
    origin = Point(origin)
    dest = Point(dest)

    waypoints = [Waypoint(origin, (origin, dest))]
    waypoints += [Waypoint(node, (origin, dest)) for node in nodes]
    to = Waypoint(dest, (origin, dest))
    waypoints.append(to)

    start, remaining = waypoints[0], waypoints[1:]
    path = []
    for i in range(MAX_STEPS):
        closer = start.closest(remaining)
        if closer is None:
            break
        path.append(closer)
        remaining = [pt for pt in remaining if pt != closer]
        start = closer

    # check to see if destination is in path
    if to in path:
        path.remove(to)
    return '|'.join(
        ["via:{},{}".format(pt.pt.latitude, pt.pt.longitude) for pt in path])
 def get_pos(self):
     if self.speed > self.get_total_distance():
         self._last_pos = self.destination
         self._last_step = len(self._step_keys)-1
     if self.get_last_pos() == self.destination:
         return self.get_last_pos()
     distance = self.speed
     origin = Point(*self._last_pos)
     ((so_lat, so_lng), (sd_lat, sd_lng)) = self._step_dict[self._step_keys[self._last_step]]
     bearing = self._calc_bearing(so_lat, so_lng, sd_lat, sd_lng)
     while haversine.haversine(self._last_pos, (sd_lat, sd_lng))*1000 < distance:
         distance -= haversine.haversine(self._last_pos, (sd_lat, sd_lng))*1000
         self._last_pos = (sd_lat, sd_lng)
         if self._last_step < len(self._step_keys)-1:
             self._last_step += 1
             ((so_lat, so_lng), (sd_lat, sd_lng)) = self._step_dict[self._step_keys[self._last_step]]
             bearing = self._calc_bearing(so_lat, so_lng, sd_lat, sd_lng)
             origin = Point(so_lat, so_lng)
             lat, lng = self._calc_next_pos(origin, distance, bearing)
             if haversine.haversine(self._last_pos, (lat, lng))*1000 < distance:
                 distance -= haversine.haversine(self._last_pos, (lat, lng))*1000
                 self._last_pos = (lat, lng)
         else:
             return self.get_last_pos()
     else:
         lat, lng = self._calc_next_pos(origin, distance, bearing)
         self._last_pos = (lat, lng)
         return self.get_last_pos()
Exemple #15
0
def organize_file(filename, config):
    location = 'data/linkstream/'

    if not os.path.exists(location):
        os.makedirs(location)

    df = pd.read_csv(filename, header=0)

    if pd.__version__ >= '0.17.0':
        df.sort_values(by=['uid', 'timestamp'], ascending=[1, 1], inplace=True)
    else:
        df.sort(['uid', 'timestamp'], ascending=[1, 1], inplace=True)

    df = df.reset_index(drop=True).rename(index=str,
                                          columns={
                                              "uid": "uid_alpha",
                                              "timestamp": "timestamp_alpha",
                                              "lat": "lat_alpha",
                                              "lon": "lon_alpha",
                                              "layer": "layer_alpha"
                                          })
    df2 = df.shift(-1).rename(index=str,
                              columns={
                                  "uid_alpha": "uid_beta",
                                  "timestamp_alpha": "timestamp_beta",
                                  "lat_alpha": "lat_beta",
                                  "lon_alpha": "lon_beta",
                                  "layer_alpha": "layer_beta"
                              })

    df = pd.concat([df, df2], axis=1)
    df = df[df['uid_alpha'] == df['uid_beta']]

    df['distance'] = df.apply(lambda r: distance.distance(
        Point("%f %f" % (r['lat_alpha'], r['lon_alpha'])),
        Point("%f %f" % (r['lat_beta'], r['lon_beta']))).meters,
                              axis=1)
    df['time_elapsed'] = df.apply(
        lambda r: abs(r['timestamp_alpha'] - r['timestamp_beta']), axis=1)

    if 'min_distance' in config.keys():
        min_distance = config['min_distance']
    else:
        min_distance = 500

    if 'max_speed' in config.keys():
        max_speed = 1 / config['max_speed']
    else:
        max_speed = 0.036  # (1 / 100 Km/h) ~= (1 / 27.8 m/s)

    df = df[df['distance'] > min_distance]
    df = df[df['time_elapsed'] > max_speed * df['distance']]

    if 'filename' in config.keys():
        df.to_csv(location + config['filename'], index=False)
    else:
        df.to_csv(location + IdGenerator.uuid4().hex + '.csv', index=False)

    return df
Exemple #16
0
 def worker(acc, bearing):
     destination = travelDistance.destination(point=start, bearing=bearing)
     distancePoint = gDistance.distance(
         Point(fromA['lat'], fromA['lng']),
         Point(destination.latitude, destination.longitude)).km
     if (distancePoint > acc['distance']):
         return {'bearing': bearing, 'distance': distancePoint}
     return acc
Exemple #17
0
    def test_unpickle_graph(self):
        G = nx.read_gpickle("/tmp/columbia.roads.pickle")

        expected_distance = 0.17716759526992643 * ureg.kilometres
        start = Point(-75.490017, +10.478256)
        end = Point(-75.488535, +10.480564)
        actual_distance = distance.using_route(G, start, end)
        self.assertEqual(actual_distance, expected_distance)
def get_bbox(position, radius):
    """
    return (4 float): long west, lat north, long east, lat south
    """
    nw = geodistance(meters=radius * 1.4).destination(
        Point(position[1], position[0]), 225)
    se = geodistance(meters=radius * 1.4).destination(
        Point(position[1], position[0]), 45)
    return nw[1], nw[0], se[1], se[0]
Exemple #19
0
def is_inside_radius(latitude1, longitude1, latitude2, longitude2, radius):
    if latitude1 is not None and longitude1 is not None and latitude2 is not None and longitude2 is not None:
        point1 = Point(latitude1, longitude1)
        point2 = Point(latitude2, longitude2)
        result = distance.distance(point1, point2).miles

        if result <= radius:
            return True
    return False
 def test_get_class_points(self):
     #should pass only if the flask server is up!
     small_polygon = build_polygon(35.3, 33.11, 35.35, 33.15)
     client_lib.set_working_polygon(small_polygon)
     points_list = [Point(35.32, 33.13), Point(35.31, 33.12)]
     points, patches = get_all_class_points_in_polygon(
         small_polygon, 2000, 'peaks', 0, 8)
     logging.info(points.shape)
     self.assertTupleEqual(points.shape, (1, 2))
Exemple #21
0
def calculateDistance(startLon, startLat, endLon, endLat):
    try:
        p1 = Point(str(startLon) + ' ' + str(startLat))
        p2 = Point(str(endLon) + ' ' +  str(endLat))
        dist = distance.distance(p1,p2).kilometers
        dist = str(dist)[:5]
        return dist
    except ValueError:
        return 0
Exemple #22
0
    def gps_distance(self):
        if self.tee_pos.latitude is 0 or self.basket_pos.latitude == 0:
            return False

        p1 = Point(self.tee_pos.latitude, self.tee_pos.longitude)
        p2 = Point(self.basket_pos.latitude, self.basket_pos.longitude)
        d = distance.distance(p1, p2)

        return '%i' % d.meters
Exemple #23
0
def distance_to_point(p1, p2):
    """
    Calculate distance from point to point
    :param p1:
    :param p2:
    :return: meters
    """
    a = Point(latitude=p1[1], longitude=p1[0])
    b = Point(latitude=p2[1], longitude=p2[0])
    return distance(a, b).m
Exemple #24
0
 def flat_result(self, result):
     out = result['properties']
     out['lat'] = result['geometry']['coordinates'][1]
     out['lon'] = result['geometry']['coordinates'][0]
     out['distance'] = '—'
     if 'coordinate' in self.expected:
         lat, lon, max_deviation = map(float, self.expected['coordinate'].split(','))
         dist = distance(Point(lat, lon), Point(out['lat'], out['lon']))
         out['distance'] = int(dist.meters)
     return out
Exemple #25
0
def get_cluster_hotel(sender, lat, longi):
    global Rest
    for rest in Rest:
        p1 = Point(lat + " " + longi)
        dist = distance.distance(Point(rest['lat'] + " " + rest['long']),
                                 p1).kilometers
        #if(dist <= rest['radius']):
        key = 'Rest_cluster:' + rest['ID'] + ':' + rest['name']
        restcluster = redList(redis=pot_con, key=key)
        restcluster.append(sender)
def getCellSize(lat_lng):
  lat_lng.sort()
  corner1 = Point(lat_lng[0]) #lat,lng of first corner of first cell (upper LH)
  corner2 = Point(lat_lng[1]) #lat,lng of second corner of first cell (upper RH)
  lat_lng.sort(key=lambda a: (a[1], a[0])) #sorts by longitude rather than latitude
  corner3 = Point(lat_lng[1]) #lat,lng of third corner of first cell (lower LH)
  
  cell_width = distance.great_circle(corner1,corner2).km
  cell_height = distance.great_circle(corner1,corner3).km
  
  return cell_width * cell_height
Exemple #27
0
def calculate_distance_from_center(latitude, longitude):
    
    downtown_lat = 43.6426
    downtown_lon = -79.3871
    
    center = Point(downtown_lat, downtown_lon)
    p = Point(float(latitude), float(longitude))
    d_center = distance.distance(p, center).kilometers
 
   
    return(d_center)
Exemple #28
0
 def get_context_data(self, *, object_list=None, **kwargs):
     context = super(IndexView, self).get_context_data(**kwargs)
     context['relations'] = RelationType.objects.all()
     query = FamillieList.objects.all()
     center = Point(48.9215, 24.70972)
     points = []
     for q in query:
         point = Point(q.point.x, q.point.y)
         if geodesic(center, point).kilometers < 5:
             print(point)
             points.append(point)
     context['points'] = points
     return context
Exemple #29
0
def build_vision_polygon(event_id, site_lat, site_lon, yaw, opening_angle,
                         dist_km):
    """
    This function allows to build the vision angle of a camera, ie. the zone covered by the detection device.

    It takes as input:

    - site_lat, the latitude of the detection device;

    - site_lon, the longitude of the detection device;

    - yaw, the orientation of the device expressed in degrees;

    - opening_angle, the width of the zone covered by the device expressed in degrees;

    - dist_km, the distance that the detection device is able to cover in kilometers.

    The function then builds and returns the zone covered by the detection device as a Dash Leaflet Polygon, which can
    be represented on the map.
    """

    # The center corresponds the point from which the vision angle "starts"
    center = [site_lat, site_lon]

    points1 = []
    points2 = []

    for i in reversed(range(1, opening_angle + 1)):
        yaw1 = (yaw - i / 2) % 360
        yaw2 = (yaw + i / 2) % 360

        point = geodesic(kilometers=dist_km).destination(
            Point(site_lat, site_lon), yaw1)
        points1.append([point.latitude, point.longitude])

        point = geodesic(kilometers=dist_km).destination(
            Point(site_lat, site_lon), yaw2)
        points2.append([point.latitude, point.longitude])

    points = [center] + points1 + list(reversed(points2))

    polygon = dl.Polygon(id={
        'type': 'vision_polygon',
        'index': str(event_id)
    },
                         color="#ff7800",
                         opacity=0.5,
                         positions=points)

    return polygon
Exemple #30
0
def get_scan_area():
    """Returns the square kilometers for configured scan area"""
    lat1 = config.MAP_START[0]
    lat2 = config.MAP_END[0]
    lon1 = config.MAP_START[1]
    lon2 = config.MAP_END[1]
    p1 = Point(lat1, lon1)
    p2 = Point(lat1, lon2)
    p3 = Point(lat1, lon1)
    p4 = Point(lat2, lon1)

    width = distance.distance(p1, p2).kilometers
    height = distance.distance(p3, p4).kilometers
    area = int(width * height)
    return area