Exemple #1
0
def line_risk2(T_list, line):
    
    
    risk = 0
    
    # 預先算五點
    points = None
    
    for T in T_list:
        T_center = T[0:2]
        T_range = T[2]
        line_dis = dis_p2l(T_center,line)
        # 若線段中最短距離小於 range 代表有部分落於 range 內
        if line_dis[1] < T_range:
            if points == None:
                points = cut_into_length(line)
            risk += 1
            for p in points:
                dis = geo.distance(p, T_center)
#                if  dis <= T_range:
                if dis !=0:
                    risk += (math.pow(dis,-4)*T[3])
                else:
                    risk += 10000

    risk *= geo.distance(line[0], line[1])/5

    return risk
def _trim_spoke_q(shorter, longer, d):

    # if length difference significant, trim
    if abs(longer.length()-d)>longer.seg.network.street_scale:
        return True 
   
    # if next point after shorter spoke end is better match for longer end, trim!
    next_shorter = shorter.next()
    if next_shorter:
        delta_next = geo.distance(longer.end().point, next_shorter.end().point)
        delta_this = geo.distance(longer.end().point, shorter.end().point)
        return delta_next < delta_this

    # no good reason to trim
    return False
Exemple #3
0
    def getBusPath(self, line=0, via=0, start=-1, end=-1):
        try:
            doc = xml.dom.minidom.parse("Linha1.kml")
        except:
            return []

        linepts = self.listLinePoints(line, via)
        sp = ep = -1  # Point IDs
        sd = ed = -1  # Distancias
        start_pt = end_pt = None
        if start != -1:
            if linepts.index(start) == -1: start = -1
            else:
                pt = self.getStopPosition(start)
                start_pt = geo.xyz(float(pt['lat']), float(pt['lon']))
        if end != -1:
            if linepts.index(end) == -1: end = -1
            else:
                pt = self.getStopPosition(end)
                end_pt = geo.xyz(float(pt['lat']), float(pt['lon']))

        plist = []
        for node in doc.getElementsByTagName("coordinates"):
            pts = node.childNodes[0].data.split()
            for i in range(0, len(pts)):
                #plist.append(pts[i])
                #continue
                p = pts[i].split(',')
                pt = geo.xyz(float(p[0]), float(p[1]))
                plist.append({'lat': p[0], 'lon': p[1]})
                if start_pt != None:
                    d = geo.distance(start_pt, pt)
                    if sd == -1 or d < sd:
                        #point = {'lat': p[0], 'lon': p[1], 'dist': sd}
                        sd = d
                        sp = i
                if end_pt != None:
                    d = geo.distance(end_pt, pt)
                    if ed == -1 or d < ed:
                        #point = {'lat': p[0], 'lon': p[1], 'dist': ed}
                        ed = d
                        ep = i
        if (ep == -1 or sp == -1):
            return plist
        elif ep < sp:
            return plist[sp:] + plist[:ep]
        else:
            return plist[sp:ep]
Exemple #4
0
 def getBusPath(self, line=0, via=0, start=-1, end=-1):
     try:
         doc = xml.dom.minidom.parse("Linha1.kml")
     except:
         return []
     
     linepts = self.listLinePoints(line, via)
     sp = ep = -1 # Point IDs
     sd = ed = -1 # Distancias
     start_pt = end_pt = None
     if start != -1:
         if linepts.index(start) == -1: start = -1
         else:
             pt = self.getStopPosition(start)
             start_pt = geo.xyz(float(pt['lat']), float(pt['lon']))
     if end != -1:
         if linepts.index(end) == -1: end = -1
         else:
             pt = self.getStopPosition(end)
             end_pt = geo.xyz(float(pt['lat']), float(pt['lon']))
     
     plist = []
     for node in doc.getElementsByTagName("coordinates"):
         pts = node.childNodes[0].data.split()
         for i in range(0, len(pts)):
             #plist.append(pts[i])
             #continue
             p = pts[i].split(',')
             pt = geo.xyz(float(p[0]), float(p[1]))
             plist.append({'lat': p[0], 'lon': p[1]})
             if start_pt != None:
                 d = geo.distance(start_pt, pt)
                 if sd == -1 or d < sd:
                     #point = {'lat': p[0], 'lon': p[1], 'dist': sd}
                     sd = d
                     sp = i
             if end_pt != None:
                 d = geo.distance(end_pt, pt)
                 if ed == -1 or d < ed:
                     #point = {'lat': p[0], 'lon': p[1], 'dist': ed}
                     ed = d
                     ep = i
     if (ep == -1 or sp == -1):
         return plist
     elif ep < sp:
         return plist[sp:] + plist[:ep]
     else:
         return plist[sp:ep]
Exemple #5
0
    def closest(cls, location, count=5, with_event=False):
        from operator import itemgetter
        import geo
        pdx_lat, pdx_lon = "45.511810", "-122.675680"
        try:
            # lat is +, lon is -, a bug if otherwise
            lat, lon, zip_code = geo.get_geocode(location)
            if not geo.is_within_radius(pdx_lat, pdx_lon, 15, lat, lon):
                return list()
            dist = 0.2
            got_result = False
            while not got_result:
                hi_lat, lo_lat, hi_lon, lo_lon = \
                    geo.radius_to_ll_bounds(lat, lon, dist)
                venues = Venue.select(AND(Venue.q.geocode_lat >= lo_lat,
                    Venue.q.geocode_lat <= hi_lat, Venue.q.geocode_lon >= lo_lon,
                    Venue.q.geocode_lon <= hi_lon))
                venues = list(venues)
                if with_event:
                    venues = [v for v in venues if v.today_events.count()] 
                if len(venues) >= count:
                    got_result = True
                else:
                    dist *= 2
        except IOError:
            return list()

        # sort by distance
        lst = [(v, geo.distance(lat, lon, v.geocode_lat, v.geocode_lon)) for v in venues]
        lst.sort(key=itemgetter(1))
        return lst[:count]
Exemple #6
0
def dist_in_miles(g, src, dst):
    '''Given a NetworkX graph data and node names, compute mileage between.'''
    src_pair = lat_long_pair(g.node[src])
    src_loc = geo.xyz(src_pair[0], src_pair[1])
    dst_pair = lat_long_pair(g.node[dst])
    dst_loc = geo.xyz(dst_pair[0], dst_pair[1])
    return geo.distance(src_loc, dst_loc) * METERS_TO_MILES
Exemple #7
0
def dist_in_miles(data, src, dst):
    '''Given a dict of names and location data, compute mileage between.'''
    src_pair = lat_long_pair(data[src])
    src_loc = geo.xyz(src_pair[0], src_pair[1])
    dst_pair = lat_long_pair(data[dst])
    dst_loc = geo.xyz(dst_pair[0], dst_pair[1])
    return geo.distance(src_loc, dst_loc) * METERS_TO_MILES
Exemple #8
0
    def put_sign(self, sign_id, latitude, longitude):
        nearest_cluster = None
        nearest_distance = float('inf')
        for cluster in self.clusters:
            if latitude > cluster.latitude + self.gridsize_lat or \
               latitude < cluster.latitude - self.gridsize_lat or \
               longitude > cluster.longitude + self.gridsize_lon or \
               longitude < cluster.longitude - self.gridsize_lon:
                continue

            distance = geo.distance(cluster.latitude, cluster.longitude,
                                    latitude, longitude)
            if distance < nearest_distance:
                nearest_cluster = cluster
                nearest_distance = distance

        if nearest_cluster:
            # Check duplicate
            if sign_id in nearest_cluster.signs:
                return
            if len(nearest_cluster.signs) < self.n_signs:
                nearest_cluster.signs.add(sign_id)
            nearest_cluster.size += 1
        elif len(self.clusters) < self.n_max:
            cluster = Cluster()
            cluster.latitude = latitude
            cluster.longitude = longitude
            cluster.size = 1
            cluster.signs.add(sign_id)
            self.clusters.append(cluster)
Exemple #9
0
 def genArc2(self, branch, point, ref, u, radius, son):
     ipr = self.points[branch.initialPoint]
     fpr = self.points[branch.finalPoint]
     lenght = geo.distance(ipr, fpr)
     if son == 1:
         off = 40
     else:
         off = -40
     off = 0
      
     t=(lenght-branch.radius*0.6)/lenght
     ref2 = [(1-t)*ipr[0]+t*fpr[0],((1-t)*ipr[1]+t*fpr[1]),((1-t)*ipr[2]+t*fpr[2])]
     ipr = self.points[point-1]
     coords = geo2.rotateByAxis(geo2.getVector4_3(ref2), geo2.getVector4_3(ipr), u, -90+off)
     vAux1 = geo.createVertex(coords[0],coords[1],coords[2])
         
     ipr = self.points[point-1]
     coords = geo2.rotateByAxis(geo2.getVector4_3(ref), geo2.getVector4_3(ipr), u, -90+off)
     vAux2 = geo.createVertex(coords[0],coords[1],coords[2])
     circleI = geo.createCircleNormal2(point,vAux2,vAux2,radius,branch.index)
     
     vAux3 = geo.createVertexOnCurveFraction(circleI, 0.25)
     eliFullAux = geo.createEllipseFull(vAux3, vAux1, point)
     eliFull = geo.createEllipseFull(vAux3, vAux1, point)
     
     geo.deleteCurve2(circleI)
     geo.deleteVertex(vAux1)
     geo.deleteVertex(vAux2)
      
     v1 = geo.createVertexOnCurveFraction(eliFullAux, 0)
     v2 = geo.createVertexOnCurveFraction(eliFullAux, 0.5)
     eli1 = geo.splitCurve2(eliFullAux, v1, v2)
     eli2 = eli1-1
     arcs = [eli1,eli2,eliFull]
     return arcs
Exemple #10
0
def dist_in_miles(g, src, dst):
    '''Given a NetworkX graph data and node names, compute mileage between.'''
    src_pair = lat_long_pair(g.node[src])
    src_loc = geo.xyz(src_pair[0], src_pair[1])
    dst_pair = lat_long_pair(g.node[dst])
    dst_loc = geo.xyz(dst_pair[0], dst_pair[1])
    return geo.distance(src_loc, dst_loc) * METERS_TO_MILES
Exemple #11
0
 def getDistanceRaw(self):
     if self.distanceRaw==None:
         this=geo.xyz(self.lat,self.lon)
         distance=int(geo.distance(this,home))
         self.distanceRaw=distance
         
     return self.distanceRaw
Exemple #12
0
def dist_in_miles(data, src, dst):
    '''Given a dict of names and location data, compute mileage between.'''
    src_pair = lat_long_pair(data[src])
    src_loc = geo.xyz(src_pair[0], src_pair[1])
    dst_pair = lat_long_pair(data[dst])
    dst_loc = geo.xyz(dst_pair[0], dst_pair[1])
    return geo.distance(src_loc, dst_loc) * METERS_TO_MILES
Exemple #13
0
    def match(self, spokes):
        match_set = []
        if self.seg.match: return match_set

        len1 = self.length()
        street_scale = self.seg.network.street_scale
        for spoke in spokes:
            if spoke.seg.match: continue
            len2 = spoke.length()

            if len1<=len2:
                length = len1
                d1=length
                d2=spoke.project(self.end().point)
            else:
                length = len2
                d1 = self.project(spoke.end().point)
                d2 = length

            # to match, segments must be approximately same length
            if abs(d1-d2) > max(street_scale, 0.1*length): continue

            # to match, segment end points must be near each other
            if geo.distance(self.interpolate(d1),spoke.interpolate(d2)) > street_scale: continue

            match_set.append((self, d1, spoke, d2))

        return match_set
Exemple #14
0
    def process_answer(self, guess, player):
        if player not in self.players:
            raise KeyError(f"Unknown player: '{player}'")

        (main_name, hint), ref = self.place
        delta = time.time() - self.start
        dist = geo.distance(ref, guess)

        sd = self.dist_score(dist)
        st = sd * self.time_score(delta)

        score = round(st + sd)
        msg = MSG_TEMPLATE.format(dist=dist, delta=delta, st=st, sd=sd, score=score)

        self.distances[player] = dist
        self.durations[player] = delta
        self.scores[player] = score
        self.messages[player] = msg

        res = dict(dist=dist, delta=delta, score=score, msg=msg,
                   guess=dict(lon=guess[0], lat=guess[1]),
                   answer=dict(lon=ref[0], lat=ref[1], name=main_name),
                   player=player, st=st, sd=sd,
                   )
        self.records.append(res)
        self.dones[player] = True

        game_done = all(self.dones[p] for p in self.players)
        if game_done:
            self.on_run_end()
        return res, game_done
Exemple #15
0
 def genArcFull(self, branch, point, ref):
     radius = branch.getRadius()
     u = branch.getU(self.points)
     ipr = self.points[branch.initialPoint]
     fpr = self.points[branch.finalPoint]
     lenght = geo.distance(ipr, fpr)
      
     t=(lenght-radius[0]*radius[1])/lenght
     ref2 = [(1-t)*ipr[0]+t*fpr[0],((1-t)*ipr[1]+t*fpr[1]),((1-t)*ipr[2]+t*fpr[2])]
     ipr = self.points[point-1]
     coords = geo2.rotateByAxis(geo2.getVector4_3(ref2), geo2.getVector4_3(ipr), u, -90)
     vAux1 = geo.createVertex(coords[0],coords[1],coords[2])
         
     
     coords = geo2.rotateByAxis(geo2.getVector4_3(ref), geo2.getVector4_3(ipr), u, -90)
     vAux2 = geo.createVertex(coords[0],coords[1],coords[2])
     circleI = geo.createCircleNormal2(point,vAux2,vAux2,radius[1],branch.index)
     
     vAux3 = geo.createVertexOnCurveFraction(circleI, 0.25)
     eliFull = geo.createEllipseFull(vAux3, vAux1, point)
     geo.deleteCurve(circleI)
     #geo.deleteVertex(vAux2)
     geo.deleteVertex(vAux1)
     #geo.deleteVertex(vAux3)
     if eliFull == circleI:
         tube.eprint("Erro Ellipse")
         return -1
     else:
         return eliFull
 def simulatePulseOld(self):
     self.checkQueues()
     if self.vehicle.homePositionSet:
         if self.vehicle.homePosition == self.vehicle.position:
             self.pulseQueue.put(0)
         else:
             angleToCollar = geo.great_circle_angle(
                 self.vehicle.homePosition, self.vehicle.position,
                 geo.geographic_northpole)
             distanceToCollar = geo.distance(self.vehicle.position,
                                             self.vehicle.homePosition)
             vehicleHeadingToCollar = self.vehicle.heading - angleToCollar
             print("simulateBeep", angleToCollar, distanceToCollar,
                   self.vehicle.heading, vehicleHeadingToCollar)
             # Start at full strength
             beepStrength = 600.0
             # Adjust for distance
             maxDistance = 500.0
             distanceToCollar = min(distanceToCollar, maxDistance)
             beepStrength *= (maxDistance - distanceToCollar) / maxDistance
             # Adjust for vehicle heading in relationship to direction to collar
             vehicleHeadingToCollar = abs(vehicleHeadingToCollar)
             if vehicleHeadingToCollar > 180.0:
                 vehicleHeadingToCollar = 180.0 - (vehicleHeadingToCollar -
                                                   180.0)
             vehicleHeadingToCollar = 180.0 - vehicleHeadingToCollar
             beepMultiplier = vehicleHeadingToCollar / 180.0
             print("beepMultiplier", beepMultiplier, vehicleHeadingToCollar)
             beepStrength *= beepMultiplier
             self.pulseQueue.put(beepStrength)
     else:
         print("simulateBeep - home position not set")
     self.simulationTimer = threading.Timer(60.0 / BPM, self.simulatePulse)
     self.simulationTimer.start()
Exemple #17
0
  def _drawPoint(self, crPosUnitsProj, point, colors, distance=True, action="", highlight=False):
    (cr, pos, units, proj) = crPosUnitsProj
    (lat,lon) = point.getLL() #TODO use getLLE for 3D distance
    (lat1,lon1) = pos # current position coordinates
    kiloMetricDistance = geo.distance(lat,lon,lat1,lon1)
    unitString = units.km2CurrentUnitString(kiloMetricDistance, 0, True)
    if distance and pos and units:
      distanceString = " (%s)" % unitString
    else:
      distanceString=""

    text = "%s%s" % (point.getName(), distanceString)

    (x,y) = proj.ll2xy(lat, lon)
    # get colors
    (bgColor,textColor) = colors

    if highlight:
      # draw the highlighting circle
      cr.set_line_width(8)
      cr.set_source_rgba(*bgColor.getCairoColor()) # highlight circle color
      cr.arc(x, y, 15, 0, 2.0 * math.pi)
      cr.stroke()
      cr.fill()

    # draw the point
    cr.set_source_rgb(0.0, 0.0, 0.0)
    cr.set_line_width(10)
    cr.arc(x, y, 3, 0, 2.0 * math.pi)
    cr.stroke()
    cr.set_source_rgb(0.0, 0.0, 1.0)
    cr.set_line_width(8)
    cr.arc(x, y, 2, 0, 2.0 * math.pi)
    cr.stroke()

    # draw a caption with transparent background
    cr.set_font_size(25)
    extents = cr.text_extents(text) # get the text extents
    (w,h) = (extents[2], extents[3])
    border = 2
    cr.set_line_width(2)

    cr.set_source_rgba(*bgColor.getCairoColor()) # trasparent blue
    (rx,ry,rw,rh) = (x - border+12, y + border+h*0.2 + 6, w + 4*border, -(h*1.4))
    cr.rectangle(rx,ry,rw,rh) # create the transparent background rectangle
    cr.fill()

    # register clickable area
    click = self.m.get('clickHandler', None)
    if click:
      """ make the POI caption clickable"""
      click.registerXYWH(rx,ry-(-rh),rw,-rh, action)
    cr.fill()

    # draw the actual text
    cr.set_source_rgba(*textColor.getCairoColor()) # slightly transparent white
    cr.move_to(x+15,y+7)
    cr.show_text(text) # show the transparent result caption
    cr.stroke()
Exemple #18
0
 def get_member_info(self, member):
     info = {'nickname': re.sub('[<>&]', '', member.nickname),
             'lat': member.location.lat,
             'lon': member.location.lon}
     if self.member:
         info['distance'] = geo.distance(
             self.member.location, member.location)
     return info
    def dist_between_crimes(self, crime1, crime2):
        coord1 = crime1.get_coordinates()
        coord2 = crime2.get_coordinates()

        #splat operator * turns fnctn(['p','p']) into fnctn('p1','p2')
        dist = geo.distance(geo.xyz(*coord1), geo.xyz(*coord2))

        #avoid 1/r^2 singularities with 100 m min dist
        return dist if dist > 100 else 100
def move_to(start, goal,velocity):
    # 如果在一步內,則不經計算直接到點(同時避免超過)
    if (geo.distance(start,goal) <= velocity):
        return goal
    # move direction
    move = geo.normalize(geo.Vector(start,goal))
    # mul by v
    move = geo.constance_multi(velocity, move)
    return geo.vector_add(start, move)
Exemple #21
0
def compute_sensor_movement(last_position, current_position):
    # Calculate how the sensor moved.
    course = geo.course(last_position.lat, last_position.lon,
                        current_position.lat, current_position.lon)
    displacement = geo.distance(last_position.lat, last_position.lon,
                                current_position.lat, current_position.lon)
    dx = displacement * trig.sind(course)
    dy = displacement * trig.cosd(course)
    return dx, dy
Exemple #22
0
 def updateItemDistance(self):
     position = self.get("pos", None) # our lat lon coordinates
     if position is not None:
       (lat1,lon1) = position
       (lat2,lon2) = (float(item['lat']), float(item['lng']))
       distance = geo.distance(lat1,lon1,lat2,lon2)
     else:
       distance = 0 # in this case, we don't know our position, so we say the distance is 0
     return distance
    def dist_between_crimes(self,crime1,crime2):
        coord1 = crime1.get_coordinates()
        coord2 = crime2.get_coordinates()

        #splat operator * turns fnctn(['p','p']) into fnctn('p1','p2')
        dist = geo.distance(geo.xyz(*coord1),geo.xyz(*coord2))

        #avoid 1/r^2 singularities with 100 m min dist
        return dist if dist > 100 else 100
Exemple #24
0
def genWaypoints(x,y):
  bbox = [min(y),min(x),max(y),max(x)]
  response = urllib2.urlopen("http://overpass.osm.rambler.ru/cgi/interpreter?data=[out:json];node[natural~'peak'][name](%(X)s);node[place~'town|city|village|hamlet'](%(X)s);out;" % {'X':','.join(map(str,bbox))})    
  places = json.loads(response.read())  
  
  minplaces = {}
  for i in range(len(x)):
    lon,lat = x[i],y[i]    
    pt1 = geo.xyz(lon,lat)
    mindist = False
    minplace = False
    for place in places['elements']:    
      pt2 = geo.xyz(place['lon'],place['lat'])
      dist = geo.distance(pt1,pt2)
      if False == mindist or dist < mindist:
        if (dist < 100 and 'natural' in place['tags'] and place['tags']['natural'] == 'peak') or \
           (dist < 150 and 'place' in place['tags'] and place['tags']['place'] == 'hamlet') or \
           (dist < 500 and 'place' in place['tags'] and place['tags']['place'] == 'village') or \
           (dist < 1500 and 'place' in place['tags'] and place['tags']['place'] == 'place') or \
           (dist < 5000 and 'place' in place['tags'] and place['tags']['place'] == 'city'):
          mindist = dist
          minplace = place
    if minplace:      
      minplaces[minplace['tags']['name']] = minplace
  waypoints = {}
  for place in minplaces.values():    
    pt2 = geo.xyz(place['lon'],place['lat'])
    mindist = False;  
    for i in range(len(x)):
      lon,lat = x[i],y[i]
      pt1 = geo.xyz(lon,lat)
      dist = geo.distance(pt1,pt2)
      if False == mindist or dist < mindist:
        mindist = dist
        mini = i      
    if (mindist < 100 and 'natural' in place['tags'] and place['tags']['natural'] == 'peak') or \
       (mindist < 150 and 'place' in place['tags'] and place['tags']['place'] == 'hamlet') or \
       (mindist < 500 and 'place' in place['tags'] and place['tags']['place'] == 'village') or \
       (mindist < 1500 and 'place' in place['tags'] and place['tags']['place'] == 'place') or \
       (mindist < 5000 and 'place' in place['tags'] and place['tags']['place'] == 'city'):
         
      waypoints[mini] = (mindist,place['tags']['name'])
  return waypoints;
Exemple #25
0
    def get_distance(self):
        corner1, corner2 = self.bounding_box()

        p1 = Point.from_latlon(*corner1)
        p2 = Point.from_latlon(*corner2)
        dist = geo.distance(p1, p2)

        dist_param = round(dist**self.distance_harshness)
        print(self.name, dist_param)
        return dist_param
Exemple #26
0
        def jct_filter_max_d(self, setJct, parms):   
            (max_d,d) = parms

            dist = geo.distance(setJct.point,self.jct.point)
            jcts_near_point = self.set_nwk.get_jcts_near_point(self.jct.point, d)
            
            log.debug('DEBUG jct_filter_max_d (dist <= max_d) = (%s <= %s) (%s), d = %s, len(jcts_near_point)=%s',
                      dist, max_d, dist <= max_d, d, len(jcts_near_point))
            return (dist <= max_d and
                    len(jcts_near_point) == 1)
Exemple #27
0
 def localAddPointsToLine(lat1, lon1, lat2, lon2, maxDistance):
   distance = geo.distance(lat1, lon1, lat2, lon2)
   if distance <= maxDistance: # the termination criterion
     return
   else:
     middleLat = (lat1 + lat2) / 2.0 # fin the midpoint between the two points
     middleLon = (lon1 + lon2) / 2.0
     pointsBetween.append((middleLat, middleLon))
     # process the 2 new line segments
     localAddPointsToLine(lat1, lon1, middleLat, middleLon, maxDistance)
     localAddPointsToLine(middleLat, middleLon, lat2, lon2, maxDistance)
Exemple #28
0
 def rand_map(self):
     index = -1
     coord_table = []
     while True:
         x = (random.randint(0, self.map_size[0] - 1),
              random.randint(0, self.map_size[0] - 1))
         if x not in coord_table and self.in_area(
                 x) is False and geo.distance(x,
                                              start_pos) >= map_size[1] / 3:
             coord_table.append(x)
             yield x
Exemple #29
0
def compute_sensor_movement(last_position, current_position):
  # Calculate how the sensor moved.
  course = geo.course(
    last_position.lat, last_position.lon,
    current_position.lat, current_position.lon)
  displacement = geo.distance(
    last_position.lat, last_position.lon,
    current_position.lat, current_position.lon)
  dx = displacement * trig.sind(course)
  dy = displacement * trig.cosd(course)
  return dx, dy
Exemple #30
0
 def screenRadius(self):
   """Return the centerpoint and radius of a circle encompassing the screen."""
   (centreXpixel,centreYpixel) = self.screenPos(0.5,0.5)
   (centreX, centreY) = self.xy2ll(centreXpixel, centreYpixel)
   #ASUMPTION: screen is rectangular
   (cornerXpixel,cornerYpixel) = self.screenPos(0, 0) # we take the coordinates of one corner of the screen
   (cornerX,cornerY) = self.xy2ll(cornerXpixel, cornerYpixel) # we convert them to projection coordinates
   (anotherCornerXpixel,anotherCornerYpixel) = self.screenPos(1, 1) # we take the coordinates of another corner of the screen
   (anotherCornerX,anotherCornerY) = self.xy2ll(anotherCornerXpixel, anotherCornerYpixel) # we convert them to projection coordinates
   """radius = diagonal/2"""
   radius = geo.distance(anotherCornerX, anotherCornerY, cornerX , cornerY)/2.0
   return centreX, centreY, radius # we return the centre coordinates and the radius
Exemple #31
0
def _stations_with_distance(loc: Optional[LatLonTuple]) -> Optional[List]:
    """ Return list of petrol stations w. added distance data. """
    pd = _get_petrol_station_data()
    if not pd:
        return None

    if loc:
        # Calculate distance of all stations
        for s in pd:
            s["distance"] = distance(loc, (s["geo"]["lat"], s["geo"]["lon"]))

    return pd
Exemple #32
0
  def getClosestStep(self):
    """get the geographically closest step"""
    proj = self.m.get('projection', None) # we also need the projection module
    pos = self.get('pos', None) # and current position
    if pos and proj:
      (lat1,lon1) = pos
      tempSteps = self.route.getMessagePoints()
      for step in tempSteps:
        (lat2, lon2) = step.getLL()
        step.setCurrentDistance = geo.distance(lat1,lon1,lat2,lon2)*1000 # km to m
      closestStep = sorted(tempSteps, key=lambda x: x.getCurrentDistance())[0]

      return closestStep
def collision_detect_angle(rs, v):
    
    
    rsv_dot = geo.dot(rs, v)
    
    if rsv_dot < 0 :
        return None
    elif rsv_dot == 0:
        return math.pi/2
    
    rs_value = geo.distance([0,0],rs)
    v_value = geo.distance([0,0],v)

    value = rsv_dot/(rs_value*v_value)

    if value <=1 :
        return_v = math.acos(value)
    else:
        return_v = math.acos(1)


    return return_v
Exemple #34
0
        def _impl(record):
            entry = SearchEntry()
            entry.sign_id = int(record['sign_id'])
            entry.rank = record.get('rank')
            # Min rank threshold
            if entry.rank != None and entry.rank < params.min_rank:
                return
            # Legacy
            if entry.rank == None:
                entry.rank = 0

            location = record['location'].unwrap().get('coordinates')
            entry.distance = geo.distance(params.latitude, params.longitude, location[1], location[0])
            heap.push(entry)
Exemple #35
0
    def getNearestBusStops(self,
                           lat=None,
                           lon=None,
                           radius=1000,
                           limit=10,
                           line=None,
                           via=None):
        #dados = list(csv.reader(open('circular1.csv')))

        #__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))

        if line != None and via != None:
            possible = self.listLinePoints(line, via)
        else:
            possible = None

        if (lat == None or lon == None):
            return "Missing Lat or Lon"

        source = geo.xyz(float(lat), float(lon))
        txt = str(limit) + " Closest Bus Stops in a " + str(
            radius) + "m radius: <br/>"
        ldist = []
        doc = xml.dom.minidom.parse("bus_stops.kml")

        for node in doc.getElementsByTagName("Placemark"):
            name = node.getElementsByTagName("name")[0].childNodes[0].data
            sid = node.getElementsByTagName("stopid")[0].childNodes[0].data
            points = node.getElementsByTagName("Point")
            coord = points[0].getElementsByTagName("coordinates")
            lon = float(coord[0].childNodes[0].data.split(",")[0])
            lat = float(coord[0].childNodes[0].data.split(",")[1])

            point = geo.xyz(lat, lon)
            dist = float('%.2f' % geo.distance(source, point))
            if (float(dist) < float(radius)
                    and (possible == None or possible.index(sid) != -1)):
                ldist.append({
                    'dist': float(dist),
                    'name': name,
                    'lat': lat,
                    'lon': lon,
                    'sid': sid
                })

        if (ldist == []):
            return self.getNearestBusStops(lat, lon, radius + 100, limit)

        return sorted(ldist, key=itemgetter('dist'))[0:int(limit)]
Exemple #36
0
def dist_answer_for_loc(matches, query):
    """ Generate response to distance query. """
    locname = matches.group(1)
    loc_nf = _addr2nom(locname[0].upper() + locname[1:])
    res = query_geocode_api_addr(loc_nf)

    # Verify sanity of API response
    if (not res or not "status" in res or res["status"] != "OK"
            or not res.get("results")):
        return None

    # Try to avoid answering bus queries here
    loc_lower = locname.lower()
    if any(s in loc_lower for s in (
            "strætó",
            "stoppistöð",
            "strætisvagn",
            "biðstöð",
            "stoppustöð",
            "stræto",
            "strædo",
    )):
        return None

    # Extract location coordinates from API result
    topres = res["results"][0]
    coords = topres["geometry"]["location"]
    loc = (coords["lat"], coords["lng"])

    # Calculate distance, round it intelligently and format num string
    km_dist = distance(query.location, loc)

    # Generate answer
    answer = distance_desc(km_dist, abbr=True)
    response = dict(answer=answer)

    loc_nf = loc_nf[0].upper() + loc_nf[1:]
    dist = distance_desc(km_dist, case="þf")
    voice = "{0} er {1} í burtu".format(loc_nf, dist)

    query.set_key(capitalize_placename(loc_nf))

    # Beautify by capitalizing remote loc name
    uc = capitalize_placename(locname)
    bq = query.beautified_query.replace(locname, uc)
    query.set_beautified_query(bq)
    query.set_context(dict(subject=loc_nf))

    return response, answer, voice
Exemple #37
0
	def update_data(self):
		if self.start_pos==None or self.dest_pos==None: return

		self.data_dist.set_text("Distance: %f km" % (geo.distance(self.start_pos,self.dest_pos)/1000.))

		if not self.start_pos==self.dest_pos:
			if HAVE_GEOMAG:
				true_north = geo.great_circle_angle(self.dest_pos,self.start_pos,geo.geographic_northpole)
				angle = geomag.mag_heading(true_north,dlat=self.start_lat,dlon=self.start_lon)
			else:
				angle = geo.great_circle_angle(self.dest_pos,self.start_pos,geo.magnetic_northpole)
				
			self.data_dir.set_text("Direction: %f\xc2\xb0 from north (%s)" % (angle, geo.direction_name(angle)))
		else:
			self.data_dir.set_text("Start point and destination is the same!")	
Exemple #38
0
 def imprime(self):
     heap = [self.root]
     while not (len(heap) == 0):
         atual = heap.pop()
         pi = self.points[atual.initialPoint]
         pf = self.points[atual.finalPoint]
         lenght = geo.distance(pi, pf)
         if lenght < atual.radius*3:
             print "Segmento muito pequeno "
             print atual.initialPoint+1
         #print str(atual.initialPoint) + str(self.points[atual.initialPoint])+ " " + str(atual.finalPoint) + str(self.points[atual.finalPoint])
         #print str(atual.initialPoint) + " " + str(atual.finalPoint)
         if atual.son1 is not None:
             heap.append(atual.son1)
         if atual.son2 is not None:
             heap.append(atual.son2)
Exemple #39
0
def dist_answer_for_loc(locname, query):
    """ Generate response to distance query """
    loc_nf = _addr2nom(locname[0].upper() + locname[1:])
    res = query_geocode_api_addr(loc_nf)

    # Verify sanity of API response
    if (not res or not "status" in res or res["status"] != "OK"
            or not res.get("results")):
        return None

    # Extract location coordinates from API result
    topres = res["results"][0]
    coords = topres["geometry"]["location"]
    loc = (coords["lat"], coords["lng"])

    # Calculate distance, round it intelligently and format num string
    km_dist = distance(query.location, loc)

    # E.g. 7,3 kílómetra
    if km_dist >= 1.0:
        km_dist = round(km_dist, 1 if km_dist < 10 else 0)
        dist = str(km_dist).replace(".", ",")
        dist = re.sub(r",0$", "", dist)
        unit = "kílómetra"
        unit_abbr = "km"
    # E.g. 940 metra
    else:
        dist = int(math.ceil(
            (km_dist * 1000.0) / 10.0) * 10)  # Round to nearest 10 m
        unit = "metra"
        unit_abbr = "m"

    # Generate answer
    answer = "{0} {1}".format(dist, unit_abbr)
    response = dict(answer=answer)
    loc_nf = loc_nf[0].upper() + loc_nf[1:]
    voice = "{2} er {0} {1} í burtu".format(dist, unit, loc_nf)

    query.set_key(loc_nf)

    # Beautify by capitalizing remote loc name
    uc = locname.title()
    bq = query.beautified_query.replace(locname, uc)
    query.set_beautified_query(bq)

    return response, answer, voice
Exemple #40
0
    def routeClosestPoint(self, lat=None, lon=None, line=0, via=0):
        try:
            doc = xml.dom.minidom.parse("Linha" + (line + 1) + ".kml")
        except:
            return []

        source = geo.xyz(float(lat), float(lon))
        md = -1
        point = None
        for node in doc.getElementsByTagName("coordinates"):
            pts = node[0].childNodes[0].data.split(" ")
            for p in pts:
                p = p.split(',')
                pt = geo.xyz(float(p[0]), float(p[1]))
                d = geo.distance(source, pt)
                if md == -1 or d < md:
                    point = {'lat': p[0], 'lon': p[1], 'dist': d}
                    md = d
        return point
Exemple #41
0
 def routeClosestPoint(self, lat=None, lon=None, line=0, via=0):
     try:
         doc = xml.dom.minidom.parse("Linha" + (line + 1) + ".kml")
     except:
         return []
     
     source = geo.xyz(float(lat), float(lon))
     md = -1
     point = None
     for node in doc.getElementsByTagName("coordinates"):
         pts = node[0].childNodes[0].data.split(" ")
         for p in pts:
             p = p.split(',')
             pt = geo.xyz(float(p[0]), float(p[1]))
             d = geo.distance(source, pt)
             if md == -1 or d < md:
                 point = {'lat': p[0], 'lon': p[1], 'dist': d}
                 md = d
     return point
Exemple #42
0
    def getNearestBusStops(self, lat=None, lon=None, radius=1000, limit=10, line=None, via=None):
        #dados = list(csv.reader(open('circular1.csv')))
            
        #__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))

        if line != None and via != None:
            possible = self.listLinePoints(line, via)
        else:
            possible = None

        if(lat == None or lon == None):
            return "Missing Lat or Lon"
                    
        source = geo.xyz(float(lat), float(lon))
        txt = str(limit) + " Closest Bus Stops in a " + str(radius) + "m radius: <br/>"
        ldist = []
        doc = xml.dom.minidom.parse("bus_stops.kml")

        for node in doc.getElementsByTagName("Placemark"):
            name = node.getElementsByTagName("name")[0].childNodes[0].data
            sid = node.getElementsByTagName("stopid")[0].childNodes[0].data
            points = node.getElementsByTagName("Point")
            coord = points[0].getElementsByTagName("coordinates")
            lon = float(coord[0].childNodes[0].data.split(",")[0])
            lat = float(coord[0].childNodes[0].data.split(",")[1])

            point = geo.xyz(lat, lon)
            dist = float('%.2f' % geo.distance(source, point))
            if(float(dist) < float(radius) and (possible == None or possible.index(sid) != -1)):
                ldist.append({
                              'dist':float(dist),
                              'name':name,
                              'lat':lat,
                              'lon':lon,
                              'sid':sid
                              })
           
       
        if(ldist == []):
            return self.getNearestBusStops(lat, lon, radius + 100, limit)
       
        return sorted(ldist, key=itemgetter('dist'))[0:int(limit)]
Exemple #43
0
def analyze(igc):
    igc.min_gps_altitude = 5000
    igc.max_gps_altitude = 0
    igc.min_baro_altitude = 5000
    igc.max_baro_altitude = 0
    previous_record = igc.b_records[0]
    for record in igc.b_records:
        if previous_record and previous_record.validity == 'A' and record.validity == 'A':
            igc.tracklog_length += distance(previous_record.point, record.point)
        if igc.min_gps_altitude > record.gps_altitude:
            igc.min_gps_altitude = record.gps_altitude
        if igc.max_gps_altitude < record.gps_altitude:
            igc.max_gps_altitude = record.gps_altitude
        if igc.min_baro_altitude > record.baro_altitude:
            igc.min_baro_altitude = record.baro_altitude
        if igc.max_baro_altitude < record.baro_altitude:
            igc.max_baro_altitude = record.baro_altitude
        previous_record = record

    igc.flight_duration = igc.b_records[-1].datetime - igc.b_records[0].datetime
Exemple #44
0
 def fixSizes(self):
     heap = [self.root]
     while not (len(heap) == 0):
         atual = heap.pop()
         ip = self.points[atual.initialPoint]
         fp = self.points[atual.finalPoint]
         lenght = geo.distance(ip, fp)
         if lenght < atual.radius*5:
             t=(atual.radius*6)/lenght
             npf = [(1-t)*ip[0]+t*fp[0],((1-t)*ip[1]+t*fp[1]),((1-t)*ip[2]+t*fp[2])]
             #self.points[atual.finalPoint] = npf
             xyz = [npf[0]-fp[0], npf[1]-fp[1], npf[2]-fp[2]]
             if atual.son1 is not None:
                 self.move(atual.son1,xyz)
             if atual.son2 is not None:
                 self.move(atual.son2,xyz)
         if atual.son1 is not None:
             heap.append(atual.son1)
         if atual.son2 is not None:
             heap.append(atual.son2)
Exemple #45
0
 def updateDistance(self):
     if self.localSearchResults:
       position = self.get("pos", None) # our lat lon coordinates
       list = []
       index = 0
       for item in self.localSearchResults['responseData']['results']: # we iterate over the local search results
         if position is not None:
           (lat1,lon1) = position
           (lat2,lon2) = (float(item['lat']), float(item['lng']))
           distance = geo.distance(lat1,lon1,lat2,lon2)
           tupple = (distance, item, index)
           list.append(tupple) # we pack each result into a tupple with ist distance from us
         else:
           tupple = (0, item, index) # in this case, we dont know our position, so we say the distance is 0
           list.append(tupple)
         index += 1
       self.list = list
       return list
     else:
       print "search: error -> distance update on empty results"
Exemple #46
0
def parse_raw(raw):
	result = {}
	num_regexp = re.compile("\d+(\.\d+)?")
	
	last_update = prop_raw_extract("Date et heure du dernier point ", raw, True)
	# remove "(heure d'été)"
	last_update = last_update[0:last_update.rfind("(")].strip()
	result["last_update"] = datetime.strptime(last_update, "%d/%m/%Y %H:%M:%S") 
	
	course = prop_raw_extract("Cap", raw)
	result["course"] = float(re.search(num_regexp, course).group(0))
	
	speed = prop_raw_extract("Vitesse", raw)
	result["speed"] = float(re.search(num_regexp, speed).group(0))

	latitude = prop_raw_extract("Latitude", raw)
	result["str_latitude"] = latitude
	south = latitude[0] == "S"
	split = re.findall("\d+", latitude)
	# N 47 43'30''
	numlatitude = float(split[0]) + float(split[1])/60 + float(split[2])/3600
	if south:
		numlatitude = -numlatitude
	result["latitude"] = numlatitude

	longitude = prop_raw_extract("Longitude", raw)
	result["str_longitude"] = longitude
	est = longitude[0] == "E"
	split = re.findall("\d+", longitude)
	# W 003 20'59''
	numlongitude = float(split[0]) + float(split[1])/60 + float(split[2])/3600
	if est:
		numlongitude = -numlongitude
	result["longitude"] = numlongitude

	pos = geo.xyz(numlatitude, numlongitude)
	# N 47 42,8 W 3 21,5 
	finish = geo.xyz(47.7133,3.3583)
	result["dtf"] = '%0.1f' % (geo.distance(pos, finish) / 1852)

	return result
Exemple #47
0
def cut_into_length(line, length = 5):

    v_add = geo.constance_multi(length, geo.normalize(geo.Vector(line[0],line[1])))
    dis = geo.distance(line[0],line[1])
    v_start = line[0]
    
    points = []
    
    for d in range(0, math.ceil(dis+length), length):
        

        if d > dis:
            v_start = line[1]
        else:
            v_start = geo.vector_add(v_start, v_add)
    
    
        points.append(v_start[:])


    return points
  def testDistanceWithRealworldData(self):
    """ Test the distance function using data I gathered from Google Earth."""
    alcatraz = (37.825685, -122.422586)
    sfo = (37.619057, -122.375483)
    mono_lake = (37.998619, -119.028868)
    nyc = (40.577485, -73.975278)
    gibralter = (35.904513, -5.562047)
    mumbai = (19.010173, 72.910176)

    self.assertAlmostEqual(geo.distance(alcatraz, sfo), 12.5, .1)
    self.assertAlmostEqual(geo.distance(alcatraz, mono_lake), 162, 2)
    self.assertAlmostEqual(geo.distance(alcatraz, nyc), 2233, 25)
    self.assertAlmostEqual(geo.distance(alcatraz, gibralter), 5163, 450)
    self.assertAlmostEqual(geo.distance(nyc, gibralter), 3148, 90)
    self.assertAlmostEqual(geo.distance(mumbai, gibralter), 4193, 65)

    # Here's one that is wildly inaccurate, just as an example.  (The algorithm
    # uses an approximation that's only valid for shorter distances.)
    self.assertAlmostEqual(geo.distance(alcatraz, mumbai), 7291, 3000)
    def testDistanceWithRealworldData(self):
        """ Test the distance function using data I gathered from Google Earth."""
        alcatraz = (37.825685, -122.422586)
        sfo = (37.619057, -122.375483)
        mono_lake = (37.998619, -119.028868)
        nyc = (40.577485, -73.975278)
        gibralter = (35.904513, -5.562047)
        mumbai = (19.010173, 72.910176)

        self.assertAlmostEqual(geo.distance(alcatraz, sfo), 12.5, .1)
        self.assertAlmostEqual(geo.distance(alcatraz, mono_lake), 162, 2)
        self.assertAlmostEqual(geo.distance(alcatraz, nyc), 2233, 25)
        self.assertAlmostEqual(geo.distance(alcatraz, gibralter), 5163, 450)
        self.assertAlmostEqual(geo.distance(nyc, gibralter), 3148, 90)
        self.assertAlmostEqual(geo.distance(mumbai, gibralter), 4193, 65)

        # Here's one that is wildly inaccurate, just as an example.  (The algorithm
        # uses an approximation that's only valid for shorter distances.)
        self.assertAlmostEqual(geo.distance(alcatraz, mumbai), 7291, 3000)
Exemple #50
0
 def getTilesForRoute(self, route, radius, z):
   """get tilenames for tiles around the route for given radius and zoom"""
   """ now we look whats the distance between each two trackpoints,
   if it is larger than the tracklog radius, we add additional interpolated points,
   so we get continuous coverage for the tracklog """
   first = True
   interpolatedPoints = []
   for point in route:
     if first: # the first point has no previous point
       (lastLat, lastLon) = point[0], point[1]
       first = False
       continue
     thisLat, thisLon = point[0], point[1]
     distBtwPoints = geo.distance(lastLat, lastLon, thisLat, thisLon)
     """if the distance between points was greater than the given radius for tiles,
     there would be no continuous coverage for the route"""
     if distBtwPoints > radius:
       """so we call this recursive function to interpolate points between
       points that are too far apart"""
       interpolatedPoints.extend(self.addPointsToLine(lastLat, lastLon, thisLat, thisLon, radius))
     (lastLat, lastLon) = (thisLat, thisLon)
   """because we don't care about what order are the points in this case,
   we just add the interpolated points to the end"""
   route.extend(interpolatedPoints)
   start = clock()
   tilesToDownload = set()
   for point in route: #now we iterate over all points of the route
     lat, lon = point[0], point[1]
     # be advised: the xy in this case are not screen coordinates but tile coordinates
     (x, y) = latlon2xy(lat, lon, z)
     # the spiral gives us tiles around coordinates for a given radius
     currentPointTiles = self.spiral(x, y, z, radius)
     """now we take the resulting list  and process it in such a way,
     that the tiles coordinates can be stored in a set,
     so we will save only unique tiles"""
     outputSet = set(map(lambda x: tuple(x), currentPointTiles))
     tilesToDownload.update(outputSet)
   print "Listing tiles took %1.2f ms" % (1000 * (clock() - start))
   print "unique tiles %d" % len(tilesToDownload)
   return tilesToDownload
Exemple #51
0
  def _updateLogCB(self):
    """add current position at the end of the log"""
    pos = self.get('pos', None)
    if pos and not self.loggingPaused:
      timestamp = geo.timestampUTC()
      lat, lon = pos
      elevation = self.get('elevation', None)
      self.log1.addPointLLET(lat, lon, elevation, timestamp)
      self.log2.addPointLLET(lat, lon, elevation, timestamp)

      # update statistics for the current log
      if self.loggingEnabled and not self.loggingPaused:
        # update the current log speed statistics
        currentSpeed = self.get('speed', None)
        if currentSpeed:
          # max speed
          if currentSpeed > self.maxSpeed:
            self.maxSpeed = currentSpeed
          # avg speed
          self.avg1 += currentSpeed
          self.avg2 += (time.time() - self.lastUpdateTimestamp)
          self.avgSpeed = self.avg1/self.avg2
          self.lastUpdateTimestamp = time.time()

        # update traveled distance
        if self.lastCoords:
          lLat, lLon = self.lastCoords
          self.distance+=geo.distance(lLat, lLon, lat, lon)
          self.lastCoords = lat, lon

        # update the on-map trace
        if self.lastTracePoint:
          lat1, lon1 = self.lastTracePoint
          # check if the point is distant enough from the last added point
          # (which was either the first point or also passed the test)
          if geo.distanceApprox(lat, lon, lat1, lon1)*1000 >= DONT_ADD_TO_TRACE_THRESHOLD:
            self._addLL2Trace(lat, lon)
        else: # this is the first known log point, just add it
          self._addLL2Trace(lat, lon)
Exemple #52
0
def get_variables(data):
    """
	выдает основные переменные
	"""
    x, y = data['x'], data['y']
    s, d = data['s'], data['d']
    end_path_s, end_path_d = data['end_path_s'], data['end_path_d']
    prev_x, prev_y = data['previous_path_x'], data['previous_path_y']

    if len(prev_x) == 0:
        end_path_s, end_path_d = s, d

    ref_yaw = deg2rad(data['yaw'])
    other_cars = np.array([[a[-2], a[-1],
                            sqrt(a[-3]**2 + a[-4]**2)]
                           for a in data['sensor_fusion']])

    #добавляем к s скорость * время
    for i in range(len(other_cars)):
        other_cars[i][0] += other_cars[i][2] * len(prev_x) * 0.02

    #last_s,last_d=data['end_path_s'], data['end_path_d']

    while len(last_coords) > len(prev_x):
        last_coords.pop(0)
    if len(last_coords) == 0:
        last_coords.append((s, d))

    #todo - здесь должен быть cos/sin
    if len(prev_x) == 0:
        prev_x, prev_y = [x - 0.001, x], [y, y]

    if len(prev_x) == 1:
        prev_x, prev_y = [prev_x[0] - 0.001, prev_x[0]], [prev_y[0], prev_y[0]]

    car_speed = distance(prev_x[-1], prev_y[-1], prev_x[-2], prev_y[-2]) / 0.02

    return prev_x, prev_y, end_path_s, end_path_d, car_speed, ref_yaw, other_cars
def finish_game(game_id, latitude, longitude):
    if not game_id in games:
        return bottle.HTTPResponse(status=404, body='game not found')

    game = games[game_id]

    answer_coordinates = (float(latitude), float(longitude))

    d = distance(game.current_coordinates, answer_coordinates)

    if not game.is_finished:
        game.is_finished = True
        game.answer_coordinates = answer_coordinates
        game.distance = d
        game.score = count_score(game)

    return {
        "right_coordinates": game.current_coordinates,
        "distance": d,
        "address": get_text_by_coordinates(game.current_coordinates),
        "route": game.route,
        "score": game.score
    }
def count_score(game):
    dist = distance(game.current_coordinates, game.answer_coordinates)

    return 100_000 / (1 + dist)
Exemple #55
0
def check_circle_fence(lat, lng, clat, clng, radius):
    distance = geo.distance(lat, lng, clat, clng)
    if distance < radius:
        return 1
    return 0
    pass
Exemple #56
0
def dist_answer_for_loc(matches, query: Query):
    """Generate response to distance query, e.g.
    "Hvað er ég langt frá X?" """
    locname = matches.group(1)
    loc_nf = _addr2nom(locname) or locname

    # Try to avoid answering certain queries here
    loc_lower = locname.lower()
    # TODO: Solve this by configuring qmodule priority
    if any(s in loc_lower for s in (
            "strætó",
            "stoppistöð",
            "strætisvagn",
            "biðstöð",
            "stoppustöð",
            "stræto",
            "strædo",
            "jólin",
            "jól",
            "páska",
    )):
        return None

    # Check if user is asking about distance from home address
    is_home = False
    loc: Tuple[float, float]
    if loc_lower in _HOME_LOC:
        ad = query.client_data("address")
        if not ad:
            return gen_answer(
                "Ég veit ekki hvar þú átt heima, en þú getur sagt mér það.")
        elif "lat" not in ad or "lon" not in ad:
            return gen_answer("Ég veit ekki hvar heimili þitt er.")
        else:
            is_home = True
            loc = (cast(float, ad["lat"]), cast(float, ad["lon"]))
            loc_nf = "{0} {1}".format(ad["street"], ad["number"])
    else:
        # Talk to geocode API
        res = query_geocode_api_addr(loc_nf)

        # Verify sanity of API response
        if (not res or "status" not in res or res["status"] != "OK"
                or not res.get("results")):
            return None

        # Extract location coordinates from result
        coords = res["results"][0]["geometry"]["location"]
        loc = (coords["lat"], coords["lng"])

    # Calculate distance, round it intelligently and format num string
    if query.location is None:
        km_dist = 0.0
    else:
        km_dist = distance(query.location, loc)

    # Generate answer
    answer = distance_desc(km_dist, abbr=True)
    response = dict(answer=answer, distance=km_dist)

    loc_nf = capitalize_placename(loc_nf)
    dist = distance_desc(km_dist, case="þf")
    voice = "{0} er {1} í burtu".format(numbers_to_neutral(loc_nf), dist)

    query.set_key(loc_nf)

    # Beautify by capitalizing remote loc name
    uc = locname if is_home else capitalize_placename(locname)
    bq = query.beautified_query.replace(locname, uc)

    # Hack to fix the fact that the voice recognition often misses "ég"
    prefix_fix = "Hvað er langt frá"
    if bq.startswith(prefix_fix):
        bq = bq.replace(prefix_fix, "Hvað er ég langt frá")
    query.set_beautified_query(bq)

    query.set_context(dict(subject=loc_nf))

    return response, answer, voice
def getCPA(rs,angle):
    
    
    return geo.distance([0,0],rs) * math.sin(angle)
Exemple #58
0
def in_range(node, city, radius):
    node_geo = geo.xyz(float(node[0]), float(node[1]))
    city_geo = geo.xyz(float(city[0]), float(city[1]))
    dist = geo.distance(node_geo, city_geo) * METERS_TO_MILES
    return dist < radius
Exemple #59
0
def on_friend(client, dev, command, params, message):
    logging.info("on_friend %s"%(dev.devid()))
    data = decode.decode_ul(message)
    rtime = data[0][5]
    rtime = time.time()
    cells = ['%d_%d_%d_%d'%(x[0], x[1], x[2], x[3]) for x in data[2][0][2]]
    logging.info("friend cells:%s"%(cells))
    gps = (data[2][0][0][0],data[2][0][0][1])
    mode = 1
    if not gps[0] or not gps[1]:
        mode = 0
        gps = cell_location.calc_location(data[2][0][2])
    friend_match_cache = db.cacheobj_get_friend_match_cache()
    removed = []
    matched = None
   
    logging.info("friend cache:%s"%(friend_match_cache))
    if dev.imei in friend_match_cache.keys():
        friend_match_cache[dev.imei] = MatchCache(rtime,cells,gps, mode).__dict__
    
    for imei in friend_match_cache:
        match_cache = friend_match_cache[imei]
        diff_time = abs(rtime - match_cache['time'])        
        logging.info("diff_time=%f",diff_time)
	if( time.time() - match_cache['time'] > config.friend_match.timeout ):
            removed.append(imei)
            continue
        if imei != dev.imei:
            match_mode = mode
            if mode != match_cache['mode'] and mode == 1:
                match_mode = 0
            match_cells = 0
            for c1 in cells:
                if c1 in match_cache['cells']:
                    match_cells = match_cells + 1
            diff_gps = geo.distance(gps[0], gps[1], match_cache['gps'][0], match_cache['gps'][1])
	    logging.info("friend %f %f %f"%(diff_time, match_cells, diff_gps))
            if( diff_time < 10 and (match_cells > 2 or (mode==1 and diff_gps < 20.0) or (mode==0 and diff_gps < 300.0)) ):
                matched = imei
                removed.append(imei)
                break

    for imei in removed:
        del friend_match_cache[imei]
    if matched:
        #db.make_friends(dev, matched)
        friend = db.get_device_record_by_imei(matched)
        dev.new_friend(matched, friend.device_phone, friend.device_name)
        data = db.cacheobj_get_device_host(matched)
        url = 'http://%s:%s/device/%s/newfriend/%s'%(data[2], data[3], matched, dev.imei)
	logging.info("friend url:%s"%(url))
        try:
            res = urllib2.urlopen(url, '{}')
            ret = res.read()
	    logging.info("%s"%(ret))
        except Exception as e:
            logging.info("%s"%(e))
            pass
    else:
        friend_match_cache[dev.imei] = MatchCache(rtime, cells, gps, mode).__dict__
    db.cacheobj_set_friend_match_cache(friend_match_cache) 
    pass
Exemple #60
0
def test_geo():
    """ Test geography and location-related functions in geo.py """
    from geo import (
        icelandic_city_name,
        continent_for_country,
        coords_for_country,
        coords_for_street_name,
        country_name_for_isocode,
        isocode_for_country_name,
        icelandic_addr_info,
        lookup_city_info,
        parse_address_string,
        iceprep_for_street,
        iceprep_for_placename,
        iceprep_for_country,
        iceprep_for_cc,
        capitalize_placename,
        distance,
        in_iceland,
        code_for_us_state,
        coords_for_us_state_code,
        location_info,
    )

    assert icelandic_city_name("London") == "Lundúnir"
    assert icelandic_city_name("Rome") == "Róm"

    assert continent_for_country("IS") == "EU"
    assert continent_for_country("no") == "EU"
    assert continent_for_country("MX") == "NA"

    assert coords_for_country("DE") is not None
    assert coords_for_country("it") is not None

    assert coords_for_street_name("Austurstræti") is not None
    assert coords_for_street_name("Háaleitisbraut") is not None

    assert country_name_for_isocode("DE", lang="is") == "Þýskaland"
    assert country_name_for_isocode("DE") == "Þýskaland"

    assert isocode_for_country_name("Danmörk", lang="is") == "DK"
    assert isocode_for_country_name("Danmörk", lang="IS") == "DK"
    assert isocode_for_country_name("Noregur") == "NO"

    addr_info = icelandic_addr_info("Fiskislóð 31")
    assert addr_info and addr_info["stadur_tgf"] == "Reykjavík"

    # Test city info lookup
    city_info = lookup_city_info("Kænugarður")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "UA"

    city_info = lookup_city_info("Kaupmannahöfn")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "DK"

    city_info = lookup_city_info("Pjongjang")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "KP"

    city_info = lookup_city_info("Pyongyang")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "KP"

    # Test address string parsing
    assert parse_address_string("   Fiskislóð  31") == {
        "street": "Fiskislóð",
        "number": 31,
        "letter": "",
    }
    assert parse_address_string("Öldugata 19c ") == {
        "street": "Öldugata",
        "number": 19,
        "letter": "c",
    }
    assert parse_address_string("    Dúfnahólar   10   ") == {
        "street": "Dúfnahólar",
        "number": 10,
        "letter": "",
    }

    # Test prepositions for street names
    assert iceprep_for_street("Öldugata") == "á"
    assert iceprep_for_street("Fiskislóð") == "á"
    assert iceprep_for_street("Austurstræti") == "í"
    assert iceprep_for_street("Hamrahlíð") == "í"

    # Test prepositions for placenames
    assert iceprep_for_placename("Dalvík") == "á"
    assert iceprep_for_placename("Akureyri") == "á"
    assert iceprep_for_placename("Ísafjörður") == "á"
    assert iceprep_for_placename("Reykjavík") == "í"
    assert iceprep_for_placename("Hafnarfjörður") == "í"
    assert iceprep_for_placename("London") == "í"
    assert iceprep_for_placename("Dyflinni") == "í"

    # Test prepositions for countries
    assert iceprep_for_country("Ítalía") == "á"
    assert iceprep_for_country("Ísland") == "á"
    assert iceprep_for_country("Þýskaland") == "í"
    assert iceprep_for_country("Japan") == "í"
    assert iceprep_for_country("spánn") == "á"

    # Test prepositions for countries, queried by CC
    assert iceprep_for_cc("IS") == "á"
    assert iceprep_for_cc("US") == "í"
    assert iceprep_for_cc("ES") == "á"
    assert iceprep_for_cc("es") == "á"

    # Test placename capitalization
    assert capitalize_placename("ríó de janeiro") == "Ríó de Janeiro"
    assert capitalize_placename("vík í mýrdal") == "Vík í Mýrdal"
    assert capitalize_placename("Vík í mýrdal") == "Vík í Mýrdal"
    assert capitalize_placename("frankfúrt am main") == "Frankfúrt am Main"
    assert capitalize_placename("mið-afríkulýðveldið") == "Mið-Afríkulýðveldið"
    assert capitalize_placename("Norður-kórea") == "Norður-Kórea"
    assert capitalize_placename("norður-Kórea") == "Norður-Kórea"
    assert capitalize_placename(
        "bosnía og hersegóvína") == "Bosnía og Hersegóvína"
    assert capitalize_placename("Norður-Makedónía") == "Norður-Makedónía"

    # Distance
    assert int(distance((64.141439, -21.943944),
                        (65.688131, -18.102528))) == 249
    assert in_iceland((66.462205, -15.968417))
    assert not in_iceland((62.010846, -6.776709))
    assert not in_iceland((62.031342, -18.539553))

    # US States
    assert code_for_us_state("Flórída") == "FL"
    assert code_for_us_state("Norður-Karólína") == "NC"
    assert code_for_us_state("Kalifornía") == "CA"
    assert coords_for_us_state_code("CA") == [36.778261, -119.417932]

    # Generic location info lookup functions
    assert "country" in location_info("Reykjavík", "placename")
    assert "continent" in location_info("Minsk", "placename")
    assert location_info("Japan", "country")["continent"] == "AS"
    assert location_info("Danmörk", "country")["continent"] == "EU"
    assert location_info("Mexíkó", "country")["continent"] == "NA"
    assert location_info("ísafjörður", "placename")["continent"] == "EU"
    assert location_info("Meðalfellsvatn", "placename")["country"] == "IS"
    assert location_info("Georgía", "country")["country"] != "US"
    assert location_info("Virginía", "placename")["country"] == "US"
    assert location_info("Norður-Dakóta", "country")["country"] == "US"
    assert location_info("Kænugarður", "placename")["continent"] == "EU"
    assert location_info("Fiskislóð 31", "address")["country"] == "IS"