Exemple #1
0
    def get_busses_in_circle(self, key, lat, lng, dist):
        cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
        circle = Point(float(lat), float(lng)).buffer(float(dist))
        ourRoutes = []
        city_data = []
        with open(os.path.join(PATH, 'stops.pickle'), 'rb') as f:
            stops = pickle.load(f)
            for stopid, stop in stops.items():
                point = Point(float(stop.lat), float(stop.lng))
                if circle.contains(point):
                    ourRoutes.extend(stop.routes)

        ten = []
        while (len(ourRoutes) > 10):
            ten.append(ourRoutes.pop())
            print ten
            if (len(ten) == 10):
                url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key=" + keys[
                    0] + "&rt=" + ",".join(
                        ten) + "&format=json&diagnostics=true&callback="
                r = requests.get(url)
                i = 0
                while (r.text.find("exceeded") != -1):
                    url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key=" + keys[
                        i] + "&rt=" + ",".join(
                            ten) + "&format=json&diagnostics=true&callback="
                    r = requests.get(url)
                    i = i + 1

                ten = []
                j = r.json()
                for bus in j['bustime-response'][0]['vehicle']:
                    city_data.append(bus)
        url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key=" + keys[
            0] + "&rt=" + ",".join(
                ourRoutes) + "&format=json&diagnostics=true&callback="
        r = requests.get(url)
        i = 0
        while (r.text.find("exceeded") != -1):
            url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key=" + keys[
                i] + "&rt=" + ",".join(
                    ourRoutes) + "&format=json&diagnostics=true&callback="
            r = requests.get(url)
            i = i + 1

        j = r.json()
        for bus in j['bustime-response'][0]['vehicle']:
            city_data.append(bus)

        ret_busses = []
        for bus in city_data:
            point = Point(float(bus['lat']), float(bus['lon']))
            if circle.contains(point):
                ret_busses.append(bus)
        return json.dumps(ret_busses)
Exemple #2
0
    def update_after_explosion(self, explosion_point, explosion_radius):
        left_ground = []
        explosion_circle = Point(explosion_point).buffer(
            explosion_radius).boundary
        max_left = max(0, explosion_point[0] - explosion_radius)
        max_right = min(display_width, explosion_point[0] + explosion_radius)
        for i in range(max_left, max_right):
            ground_line = LineString([[i, display_height], self.points[i]])
            intersection = explosion_circle.intersection(ground_line)
            if explosion_point[1] + explosion_radius > display_height:
                left_start = explosion_point[1] - explosion_radius
                if self.points[i][1] < left_start:
                    left_ground.append([[i, left_start],
                                        [i, self.points[i][1]]])
                    self.points[i][1] = display_height
                else:
                    self.points[i][1] = display_height
            elif isinstance(intersection, MultiPoint):
                first_point = intersection.geoms[0]
                second_point = intersection.geoms[1]
                fst_coordinate = i, min(int(first_point.coords[0][1]),
                                        int(second_point.coords[0][1]))
                snd_coordinate = i, max(int(first_point.coords[0][1]),
                                        int(second_point.coords[0][1]))

                left_length = fst_coordinate[1] - self.points[i][1]
                if left_length > 0:
                    left_ground.append([[i, fst_coordinate[1]],
                                        [i, self.points[i][1]]])
                self.points[i][1] = snd_coordinate[1]
            elif isinstance(intersection, Point):
                if not explosion_circle.contains(intersection):
                    self.points[i][1] = int(intersection.coords[0][1])

        return left_ground
Exemple #3
0
        def get_busses_in_circle(self,key,lat,lng,dist):
          cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
          circle = Point(float(lat),float(lng)).buffer(float(dist))
          ourRoutes = []
          city_data = []
          with open(os.path.join(PATH, 'stops.pickle'), 'rb') as f:
            stops = pickle.load(f)
            for stopid, stop in stops.items():
              point = Point(float(stop.lat), float(stop.lng))
              if circle.contains(point):
                ourRoutes.extend(stop.routes)
         
          ten = []
          while (len(ourRoutes) > 10):
            ten.append(ourRoutes.pop()) 
            print ten
            if (len(ten) == 10):
              url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[0]+"&rt="+",".join(ten)+"&format=json&diagnostics=true&callback="
              r = requests.get(url)
              i=0
	      while (r.text.find("exceeded") != -1):
                url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[i]+"&rt="+",".join(ten)+"&format=json&diagnostics=true&callback="
                r = requests.get(url)
                i=i+1

              ten = []
              j = r.json()
              for bus in j['bustime-response'][0]['vehicle']:
                city_data.append(bus)
          url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[0]+"&rt="+",".join(ourRoutes)+"&format=json&diagnostics=true&callback="
          r = requests.get(url)
          i=0
          while (r.text.find("exceeded") != -1):
            url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[i]+"&rt="+",".join(ourRoutes)+"&format=json&diagnostics=true&callback="
            r = requests.get(url)
            i=i+1

          j = r.json()
          for bus in j['bustime-response'][0]['vehicle']:
            city_data.append(bus)

          ret_busses = []
          for bus in city_data:
            point = Point(float(bus['lat']), float(bus['lon']))
            if circle.contains(point):
              ret_busses.append(bus)
          return json.dumps(ret_busses)
Exemple #4
0
 def get_nearby_stations(self, lat, lng, dist):
     cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
     r = requests.get('http://www.divvybikes.com/stations/json/')
     jsonData = r.json()
     stations = jsonData['stationBeanList']
     ret_stations = []
     circle = Point(float(lat), float(lng)).buffer(float(dist))
     for station in stations:
         point = Point(station['latitude'], station['longitude'])
         if circle.contains(point):
             ret_stations.append(station)
     return json.dumps(ret_stations)
Exemple #5
0
	def get_nearby_stations(self, lat, lng, dist):
		cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
		r = requests.get('http://www.divvybikes.com/stations/json/')
		jsonData = r.json()
		stations = jsonData['stationBeanList']
		ret_stations = []
		circle = Point(float(lat),float(lng)).buffer(float(dist))
		for station in stations:
			point = Point(station['latitude'], station['longitude'])
			if circle.contains(point):
				ret_stations.append(station)
		return json.dumps(ret_stations)
Exemple #6
0
    def test_binary_predicates(self):

        point = Point(0.0, 0.0)

        self.assertTrue(point.disjoint(Point(-1.0, -1.0)))
        self.assertFalse(point.touches(Point(-1.0, -1.0)))
        self.assertFalse(point.crosses(Point(-1.0, -1.0)))
        self.assertFalse(point.within(Point(-1.0, -1.0)))
        self.assertFalse(point.contains(Point(-1.0, -1.0)))
        self.assertFalse(point.equals(Point(-1.0, -1.0)))
        self.assertFalse(point.touches(Point(-1.0, -1.0)))
        self.assertTrue(point.equals(Point(0.0, 0.0)))
Exemple #7
0
    def test_binary_predicates(self):

        point = Point(0.0, 0.0)

        self.assertTrue(point.disjoint(Point(-1.0, -1.0)))
        self.assertFalse(point.touches(Point(-1.0, -1.0)))
        self.assertFalse(point.crosses(Point(-1.0, -1.0)))
        self.assertFalse(point.within(Point(-1.0, -1.0)))
        self.assertFalse(point.contains(Point(-1.0, -1.0)))
        self.assertFalse(point.equals(Point(-1.0, -1.0)))
        self.assertFalse(point.touches(Point(-1.0, -1.0)))
        self.assertTrue(point.equals(Point(0.0, 0.0)))
Exemple #8
0
def get_candidate_centerlines(avm, traj, city_name):
    """
    Returns nearby closest centerlines to given trajectory
    """
    #region ROI

    roi_center = traj[-1]
    roi_radius = 20

    roi = Point(roi_center).buffer(roi_radius)

    #endregion

    line_ids = avm.get_lane_ids_in_xy_bbox(
        roi_center[0],
        roi_center[1],
        city_name,
        query_search_range_manhattan=roi_radius)

    traj_direction = vector_direction(displacement_vector(traj))

    line_ids = [
        id for id in line_ids if any([
            roi.contains(Point(p))
            for p in avm.get_lane_segment_centerline(id, city_name)
        ])
    ]

    lines = [[(id, avm.get_lane_segment_centerline(id, city_name)[:, :2])
              for id in ids] for ids in combine_lines(
                  line_ids, avm.city_lane_centerlines_dict[city_name])]

    lines = [process_line(avm, traj[-1], line, city_name) for line in lines]

    # Distance cutting
    distance_threshold = 15
    lines = [
        line for line in lines if len(line) > 1
        and LineString(line).distance(Point(traj[-1])) < distance_threshold
    ]

    limit = 6

    lines = sorted(lines,
                   key=lambda line:
                   (LineString(line).distance(Point(traj[-1])),
                    direction_difference(
                        traj_direction,
                        vector_direction(displacement_vector(line)))))[:limit]

    return lines, roi.exterior.coords
Exemple #9
0
 def rrt_goalBias(self):
     G = nx.Graph()
     G.add_node(0, pos=self.start)
     self.s_id = 0
     free_nodes = []
     time_nodes = [[self.start, 0]]
     count = 0
     free_nodes.append(self.start)
     i = 1
     while count < self.max_iter:
         point = self.sample_point(count)
         edge, point, time_node = self.add_edge(free_nodes, point,
                                                time_nodes)
         is_connectable = False
         if self.speed:
             is_connectable = self.is_timed_free(edge, time_node)
         else:
             is_connectable = self.is_connectable(edge)
         if is_connectable:
             id_t = self.get_node_id(G, edge[1])
             circle = Point(self.goal[0], self.goal[1]).buffer(self.eps)
             p = Point(point[0], point[1])
             if circle.contains(p):
                 self.g_id = i
                 G.add_node(i, pos=self.goal)
                 p1 = Point(self.goal[0], self.goal[1])
                 p2 = Point(edge[1][0], edge[1][1])
                 G.add_edge(
                     i,
                     id_t,
                 )
                 return G, free_nodes, time_nodes
             p1 = Point(edge[0][0], edge[0][1])
             p2 = Point(edge[1][0], edge[1][1])
             G.add_node(i, pos=edge[0])
             G.add_node(id_t, pos=edge[1])
             G.add_edge(i, id_t, weight=p1.distance(p2))
             if self.plot_tree:
                 plt.scatter(point[0], point[1], s=5, c="y")
                 x, y = list(zip(*edge))
                 plt.plot(x, y, c="y")
                 plt.pause(0.001)
             free_nodes.append(point)
             i += 1
             time_nodes.append(time_node)
         count += 1
     return G, free_nodes, time_nodes
Exemple #10
0
def _sensor_nodes(mitte, fog_nodes, sigma=0.03) -> List[Dict]:
    for i in count():
        position = (random.gauss(13.39, sigma), random.gauss(52.522297, sigma))
        if not mitte.contains(Point(position)):
            continue
        radius = Point(position).buffer(0.015)
        edges = []
        node = Sensor(name=str(i))
        for fog in fog_nodes:
            point = Point(*fog["pos"])
            if radius.contains(point):
                edges.append({
                    "source": node,
                    "target": fog["id"],
                    "link": Link4G()
                })
        if len(edges) > 0:
            yield {"id": node, "pos": position}, edges
Exemple #11
0
class Unit:
    def __init__(self, Power, UnitsForIncrement, AddedPower, MaxUnits):
        self.CoherencyRange = None
        self.Units = []
        self.Abilities = []
        self.Keywords = []
        self.FactionKeywords = []
        self.Points = 0
        self.SquadPosition = -1
        self.TeamPosition = -1
        self.Power = Power
        self.PowerStage = -1
        self.UnitsForIncrement = UnitsForIncrement
        self.PowerAdded = AddedPower
        self.MaxUnits = MaxUnits

    def calculate_points(self):
        self.Points = 0
        for unit in self.Units:
            self.Points += unit.Points

    def add_soldier(self, unit):
        if len(self.Units) < self.MaxUnits:
            self.Units.append(unit)
            if self.UnitsForIncrement is not None:
                for i in range(len(self.UnitsForIncrement)):
                    if len(
                            self.Units
                    ) >= self.UnitsForIncrement[i] and i > self.PowerStage:
                        self.Power += self.PowerAdded[i]
                        self.PowerStage = i
                        break
            self.calculate_points()
        else:
            print(Messages.MaxSoldiers)

    def info(self):
        print('Name: ', self.__class__.__name__)
        print('Points: ', self.Points)
        print('Power: ', self.Power)
        print('Models: ')
        [
            print('\t' + str(i) + ': ' + model.__class__.__name__)
            for i, model in enumerate(self.Units)
        ]
        print('Abilities: ')
        [
            print('\t' + str(i) + ': ' + ability)
            for i, ability in enumerate(self.Abilities)
        ]
        print('FactionKeywords: ')
        [
            print('\t' + str(i) + ': ' + factionKeyword)
            for i, factionKeyword in enumerate(self.FactionKeywords)
        ]
        print('Keywords: ')
        [
            print('\t' + str(i) + ': ' + keyword)
            for i, keyword in enumerate(self.Keywords)
        ]
        print('Available Methods: ')
        [
            print('\t' + func + '()') for func in dir(self)
            if callable(getattr(self, func)) and '__' not in func
        ]

    def init_positions_randomly(self, x, y):
        self.Units[0].set_position(x=0 + x, y=0 + y)
        self.CoherencyRange = Point(
            self.Units[0].Position.x,
            self.Units[0].Position.y).buffer(self.Units[0].BodyInfo['radius'] +
                                             2)
        for index, unit in enumerate(self.Units):
            if index > 0:
                minX, minY, maxX, maxY = self.CoherencyRange.bounds
                ok = False
                overlap = True
                pnt = None
                while not ok or overlap:
                    pnt = Point(numpy.random.uniform(minX, maxX),
                                numpy.random.uniform(minY, maxY))
                    if self.CoherencyRange.contains(pnt):
                        ok = True
                        overlap = False
                        for point in self.Units:
                            if not point.Body.intersection(
                                    Point(pnt.x, pnt.y).buffer(
                                        self.Units[index].BodyInfo['radius'])
                            ).is_empty:
                                overlap = True
                self.Units[index].set_position(x=pnt.x, y=pnt.y)
                auxCohesion = Point(self.Units[index].Position.x,
                                    self.Units[index].Position.y).buffer(
                                        self.Units[index].BodyInfo['radius'] +
                                        2)
                self.CoherencyRange = self.CoherencyRange.union(auxCohesion)

    def update_coherency_range(self, index):
        if index == 0:
            self.CoherencyRange = Point(
                self.Units[0].Position.x, self.Units[0].Position.y).buffer(
                    self.Units[0].BodyInfo['radius'] + 2)
        else:
            auxCoherency = Point(self.Units[index].Position.x,
                                 self.Units[index].Position.y).buffer(
                                     self.Units[index].BodyInfo['radius'] + 2)
            self.CoherencyRange = self.CoherencyRange.union(auxCoherency)

    def move_models(self, board, target):
        self.Units[0].move(model=self.Units[0],
                           objectsBoard=board.Objects,
                           target=target,
                           isSergeant=True)  # For testing
        overlap = []
        for unit in self.Units:
            overlap.append(unit.Body)
        self.update_coherency_range(0)
        if len(self.Units) > 1:
            for i, model in enumerate(self.Units[1:]):
                overlap.pop(i + 1)
                model.move(model=model,
                           coherencyRegion=self.CoherencyRange,
                           objectsBoard=board.Objects,
                           overlapRange=overlap,
                           target=target)
                self.update_coherency_range(i + 1)
                overlap = []
                for unit in self.Units:
                    overlap.append(unit.Body)
          (24.953510, 60.170104), (24.950958, 60.169990)]
poly = Polygon(coords)

# In[2]:

print(p1)

# In[3]:

print(p2)

# In[4]:

print(poly)

# In[5]:

p1.within(poly)

# In[6]:

p2.within(poly)

# In[7]:

p1.contains(poly)

# In[8]:

p2.contains(poly)
sCircle = Point(circleX, circleY)
sCircle = sCircle.buffer(circleRadius, 16)

pointList = []
for i in range(numberOfPoints):
	x = random.randint(0, gridWidth)
	y = random.randint(0, gridHeight)
	pointList.append((x, y))
	iPoint = Point(x, y)
	iPoint.idx = i # set our custom attribute. (if this doesnt work I have other ways)
	shapePoints.append(iPoint)

matchingPoints = []
searchBench = time.time()
for idx, point in enumerate(shapePoints):
	if sCircle.contains(point):
		matchingPoints.append(idx)

searchBench = time.time() - searchBench

print "There were %d points within the circle [%d, %d] - r[%d]\n" % (len(matchingPoints), circleX, circleY, circleRadius)
print "Calculation Took %s seconds for %s points" % (searchBench, numberOfPoints)
print "Saving Graph to %s" % (filename)


#_-------------------------------------------------------------------------------
# DRAW A REPRESENTATION OF THE LOGIC ABOVE:
import matplotlib
matplotlib.use('Agg') # Do NOT attempt to open X11 instance
from pylab import *
from matplotlib.patches import Circle
Exemple #14
0
    def get_goals(self,
                  observation: ip.Observation,
                  threshold: float = 2.0) -> List[ip.Goal]:
        """Retrieve all possible goals reachable from the current position on the map in any direction. If more than
        one goal is found on a single lane, then only choose the one furthest along the midline of the lane.

        Args:
            observation: Observation of the environment
            threshold: The goal checking threshold
        """
        # TODO Replace with box goals that cover all lanes in same direction

        scenario_map = observation.scenario_map
        state = observation.frame[self.agent_id]
        view_circle = Point(*state.position).buffer(self.view_radius)

        # Retrieve relevant roads and check intersection of its lanes' midlines
        possible_goals = []
        for road in scenario_map.roads.values():
            if not road.boundary.intersects(view_circle):
                continue

            for lane_section in road.lanes.lane_sections:
                for lane in lane_section.all_lanes:
                    if lane.id == 0 or lane.type != "driving":
                        continue

                    new_point = None

                    # First check if the lane intersects the view boundary anywhere
                    intersection = lane.midline.intersection(view_circle.boundary)
                    if not intersection.is_empty:
                        if isinstance(intersection, Iterable):
                            max_distance = np.inf
                            for point in intersection:
                                if lane.distance_at(point) < max_distance:
                                    new_point = point
                        else:
                            new_point = intersection

                    # If not, and the lane is completely within the circle then choose the lane end-point
                    elif view_circle.contains(lane.boundary):
                        # if lane.link.predecessor is None:
                        #     new_point = lane.midline.coords[-1]
                        if lane.link.successor is None:
                            new_point = lane.midline.coords[-1]
                        else:
                            continue

                    else:
                        continue

                    # Do not add point if within threshold distance to an existing goal
                    if not any([np.allclose(new_point, g.center, atol=threshold) for _, g in possible_goals]):
                        new_goal = ip.PointGoal(np.array(new_point), threshold=threshold)
                        possible_goals.append((lane, new_goal))

        # Group goals that are in neighbouring lanes
        goals = []
        used = []
        for lane, goal in possible_goals:
            if goal in used:
                continue

            neighbouring_goals = [goal]
            for other_lane, other_goal in possible_goals:
                if goal == other_goal:
                    continue

                if lane.parent_road == other_lane.parent_road and np.abs(lane.id - other_lane.id) == 1:
                    neighbouring_goals.append(other_goal)
                    used.append(other_goal)

            if len(neighbouring_goals) > 1:
                goals.append(ip.PointCollectionGoal(neighbouring_goals))
            else:
                goals.append(goal)

        return goals
Exemple #15
0
class Landmark:
    ''' Contains information about user-defined landmarks.'''
    log = getLogger('landmarks')

    def __init__(self, name, shortname=None, points=None, query=None,
                 hashtags=None, phrase=None, is_area=False, query_suffix=None):
        self.name = name
        self.shortname = shortname
        self.is_area = is_area

        if not points and not query:
            query = name.lstrip('the ')

        if ((query_suffix and query) and
                query_suffix.lower() not in query.lower()):
            query = '{} {}'.format(query, query_suffix)

        self.location = None
        if query:
            self.query_location(query)
        elif points:
            try:
                length = len(points)
                if length > 2:
                    self.location = Polygon(points)
                elif length == 2:
                    self.location = box(points[0][0], points[0][1],
                                        points[1][0], points[1][1])
                elif length == 1:
                    self.location = Point(*points[0])
            except TypeError:
                raise ValueError('points must be a list/tuple of lists/tuples'
                                 ' containing 2 coordinates each')

        if not self.location:
            raise ValueError('No location provided for {}. Must provide'
                             ' either points, or query.'.format(self.name))
        elif not isinstance(self.location, (Point, Polygon, LineString)):
            raise NotImplementedError('{} is a {} which is not supported'
                                      .format(self.name, self.location.type))
        self.south, self.west, self.north, self.east = self.location.bounds

        # very imprecise conversion to square meters
        self.size = self.location.area * 12100000000

        if phrase:
            self.phrase = phrase
        elif is_area:
            self.phrase = 'in'
        else:
            self.phrase = 'at'

        self.hashtags = hashtags

    def __contains__(self, coordinates):
        """determine if a point is within this object range"""
        lat, lon = coordinates
        if (self.south <= lat <= self.north and
                self.west <= lon <= self.east):
            return self.location.contains(Point(lat, lon))
        return False

    def query_location(self, query):
        def swap_coords(geojson):
            out = []
            for x in geojson:
                if isinstance(x, list):
                    out.append(swap_coords(x))
                else:
                    return geojson[1], geojson[0]
            return out

        nom = Nominatim()
        try:
            geo = nom.geocode(query=query, geometry='geojson', timeout=3).raw
            geojson = geo['geojson']
        except (AttributeError, KeyError):
            raise FailedQuery('Query for {} did not return results.'.format(query))
        self.log.info('Nominatim returned {} for {}'.format(geo['display_name'], query))
        geojson['coordinates'] = swap_coords(geojson['coordinates'])
        self.location = shape(geojson)

    def get_coordinates(self):
        if isinstance(self.location, Polygon):
            return tuple(self.location.exterior.coordinates)
        else:
            return self.location.coords[0]

    def generate_string(self, coordinates):
        if coordinates in self:
            return '{} {}'.format(self.phrase, self.name)
        distance = self.distance_from_point(coordinates)
        if distance < 50 or (self.is_area and distance < 100):
            return '{} {}'.format(self.phrase, self.name)
        else:
            return '{:.0f} meters from {}'.format(distance, self.name)

    def distance_from_point(self, coordinates):
        point = Point(*coordinates)
        if isinstance(self.location, Point):
            nearest = self.location
        else:
            nearest = self.nearest_point(point)
        return get_distance(coordinates, nearest.coords[0])

    def nearest_point(self, point):
        '''Find nearest point in geometry, measured from given point.'''
        if isinstance(self.location, Polygon):
            segs = self.pairs(self.location.exterior.coords)
        elif isinstance(self.location, LineString):
            segs = self.pairs(self.location.coords)
        else:
            raise NotImplementedError('project_point_to_object not implemented'
                                      "for geometry type '{}'.".format(
                                      self.location.type))

        nearest_point = None
        min_dist = float("inf")

        for seg_start, seg_end in segs:
            line_start = Point(seg_start)
            line_end = Point(seg_end)

            intersection_point = self.project_point_to_line(
                point, line_start, line_end)
            cur_dist = point.distance(intersection_point)

            if cur_dist < min_dist:
                min_dist = cur_dist
                nearest_point = intersection_point
        return nearest_point

    @staticmethod
    def pairs(lst):
        """Iterate over a list in overlapping pairs."""
        i = iter(lst)
        prev = next(i)
        for item in i:
            yield prev, item
            prev = item

    @staticmethod
    def project_point_to_line(point, line_start, line_end):
        '''Find nearest point on a straight line,
           measured from given point.'''
        line_magnitude = line_start.distance(line_end)

        u = (((point.x - line_start.x) * (line_end.x - line_start.x) +
              (point.y - line_start.y) * (line_end.y - line_start.y))
             / (line_magnitude ** 2))

        # closest point does not fall within the line segment,
        # take the shorter distance to an endpoint
        if u < 0.00001 or u > 1:
            ix = point.distance(line_start)
            iy = point.distance(line_end)
            if ix > iy:
                return line_end
            else:
                return line_start
        else:
            ix = line_start.x + u * (line_end.x - line_start.x)
            iy = line_start.y + u * (line_end.y - line_start.y)
            return Point([ix, iy])
Exemple #16
0
 def is_done(self, point):
     circle = Point(self.goal[0], self.goal[1]).buffer(self.eps)
     p = Point(point[0], point[1])
     if circle.contains(p):
         return True
     return False
Exemple #17
0
# check points in each circle
for id_circle, coordinate in enumerate(listCircle):
    # narrow the field of grids to almost one circle
    mask = (lon2d > coordinate[0]-0.1) & (lon2d < coordinate[0]+0.1) &\
    (lat2d > coordinate[1]-0.1) & (lat2d < coordinate[1]+0.1)
    # draw circle (r=0.1 deg ~ 12 km)
    circle = Point(coordinate).buffer(0.1)
    # get center point of grids in rectangle (0.1 * 0.1)
    listPoint = np.stack((lon2d[mask], lat2d[mask]), axis=-1)

    # get index of chosen grid's center points in each circle
    index = []
    for id, position in enumerate(listPoint):
        point = Point(position)
        if circle.contains(point):
            index.append(id)

    # average of profiles in each circle
    d = plevel.shape[0]
    for l in np.arange(d):
        species_mean[l,
                     id_circle] = np.nanmean(species_nearest[l][mask][index])
    # filter nan of WRF-Chem
    nonan_wrf_index = np.argwhere(
        ~(np.isnan(species_mean[:, id_circle]))).ravel()
    start = nonan_wrf_index[0]
    end = nonan_wrf_index[-1]

    # Calculate averaging kernel (A = I - Cx*Ca^-1)
    Ca = np.zeros((d, d))
    # Add the points to a python list of lists
    pointList.append((x, y))
    # Create a Shapely point object
    iPoint = Point(x, y)
    iPoint.idx = i  # set our custom attribute. (if this doesnt work I have other ways)
    shapePoints.append(iPoint)

    # Add the point to an RTREE index
    # index.add(id=id, (left, bottom, right, top))
    # Note that this would work if the
    RtreeIndex.add(i, (x, y, x, y))

matchingPoints = []
searchBench = time.time()
for idx, point in enumerate(shapePoints):
    if sCircle.contains(point):
        matchingPoints.append(idx)

searchBench = time.time() - searchBench

#-------------------------------------------------------------------------------
# NOW TEST RTREE
RtreeBench = time.time()
RtreeIndex
rtreeMatches = list(
    RtreeIndex.intersection((boxLeft, boxBottom, boxRight, boxTop)))

RtreeBench = time.time() - RtreeBench

print("\n\n")
print(
Exemple #19
0
class Landmark:
    ''' Contains information about user-defined landmarks.'''
    def __init__(self,
                 name,
                 shortname=None,
                 points=None,
                 query=None,
                 hashtags=None,
                 phrase=None,
                 is_area=False,
                 query_suffix=None):
        self.name = name
        self.shortname = shortname
        self.is_area = is_area

        if not points and not query:
            query = name.lstrip('the ')

        if ((query_suffix and query)
                and query_suffix.lower() not in query.lower()):
            query = '{q} {qs}'.format(q=query, qs=query_suffix)

        self.location = None
        if query:
            self.query_location(query)
        elif points:
            try:
                if len(points) > 2:
                    self.location = Polygon(points)
                elif len(points) == 2:
                    self.location = box(points[0][0], points[0][1],
                                        points[1][0], points[1][1])
                elif len(points) == 1:
                    self.location = Point(*points[0])
            except (TypeError, IndexError):
                raise ValueError('points must be a list/tuple of lists/tuples'
                                 ' containing 2 coordinates each')

        if not self.location:
            raise ValueError('No location provided for {}. Must provide'
                             ' either points, or query.'.format(self.name))
        elif not isinstance(self.location, (Point, Polygon, LineString)):
            raise NotImplementedError('{n} is a {t} which is not '
                                      'supported.'.format(
                                          n=self.name, t=self.location.type))

        # very imprecise conversion to square meters
        self.size = self.location.area * 12100000000

        if phrase:
            self.phrase = phrase
        elif is_area:
            self.phrase = 'in'
        else:
            self.phrase = 'at'

        self.hashtags = hashtags

    def query_location(self, query):
        def swap_coords(coordinates):
            out = []
            for iterable in coordinates:
                if isinstance(iterable, list):
                    out.append(swap_coords(iterable))
                else:
                    return (coordinates[1], coordinates[0])
            return out

        nom = Nominatim()
        try:
            geo = nom.geocode(query=query, geometry='geojson').raw
            geojson = geo['geojson']
        except (AttributeError, KeyError):
            raise FailedQuery(
                'Query for {} did not return results.'.format(query))
        print(geo['display_name'])
        geojson['coordinates'] = swap_coords(geojson['coordinates'])
        self.location = shape(geojson)

    def get_coordinates(self):
        if isinstance(self.location, Polygon):
            return tuple(self.location.exterior.coordinates)
        elif isinstance(self.location, Point):
            return self.location.coords[0]
        else:
            return self.location

    def generate_string(self, coordinates):
        if self.contains(coordinates):
            return '{p} {n}'.format(p=self.phrase, n=self.name)
        distance = self.distance_from_point(coordinates)
        if (self.is_area and distance < 100) or distance < 40:
            return '{} {}'.format(self.phrase, self.name)
        else:
            return '{:.0f} meters from {}'.format(distance, self.name)

    def contains(self, coordinates):
        """determine if a point is within this object range"""
        return self.location.contains(Point(*coordinates))

    def distance_from_point(self, coordinates):
        if self.contains(coordinates):
            return 0
        point = Point(*coordinates)
        if isinstance(self.location, Point):
            nearest = self.location
        else:
            nearest = self.nearest_point(point)
        return get_distance(point.coords[0], nearest.coords[0])

    def nearest_point(self, point):
        '''Find nearest point in geometry, measured from given point.'''
        def pairs(lst):
            """Iterate over a list in overlapping pairs."""
            i = iter(lst)
            prev = next(i)
            for item in i:
                yield prev, item
                prev = item

        def project_point_to_line(point, line_start, line_end):
            '''Find nearest point on a straight line,
               measured from given point.'''
            line_magnitude = line_start.distance(line_end)

            u = (((point.x - line_start.x) * (line_end.x - line_start.x) +
                  (point.y - line_start.y) * (line_end.y - line_start.y)) /
                 (line_magnitude**2))

            # closest point does not fall within the line segment,
            # take the shorter distance to an endpoint
            if u < 0.00001 or u > 1:
                ix = point.distance(line_start)
                iy = point.distance(line_end)
                if ix > iy:
                    return line_end
                else:
                    return line_start
            else:
                ix = line_start.x + u * (line_end.x - line_start.x)
                iy = line_start.y + u * (line_end.y - line_start.y)
                return Point([ix, iy])

        nearest_point = None
        min_dist = float("inf")

        if isinstance(self.location, Polygon):
            for seg_start, seg_end in pairs(
                    tuple(self.location.exterior.coords)):
                line_start = Point(seg_start)
                line_end = Point(seg_end)

                intersection_point = project_point_to_line(
                    point, line_start, line_end)
                cur_dist = point.distance(intersection_point)

                if cur_dist < min_dist:
                    min_dist = cur_dist
                    nearest_point = intersection_point
        elif isinstance(self.location, LineString):
            for seg_start, seg_end in pairs(list(self.location.coords)):
                line_start = Point(seg_start)
                line_end = Point(seg_end)

                intersection_point = project_point_to_line(
                    point, line_start, line_end)
                cur_dist = point.distance(intersection_point)

                if cur_dist < min_dist:
                    min_dist = cur_dist
                    nearest_point = intersection_point
        else:
            raise NotImplementedError('project_point_to_object not implemented'
                                      "for geometry type '{}'.".format(
                                          self.location.type))
        return nearest_point
Exemple #20
0
tt = []
h1 = []
h2 = []
h3 = []
h4 = []
h5 = []
for i in range(0, len(tcmonth)):
    tc = tcmonth[i]
    ver = tc[0]
    fecha = tc[0, 0]
    fecha = fecha[0:4]
    locx = float(ver[1])
    locy = float(ver[2])
    pt = Point(locx, locy)
    if fecha >= str(yearini):
        if pos.contains(pt) == True:
            tcloc.extend(tc)
            tcloc.extend(nx)
            k.append(1)
            vermax = np.max(tc[:, 3].astype('float'))
            if vermax < 34:  # para DT
                tcolor = [0.00000, 1.00000, 1.00000]
                dt.append(1)
                print('year: ', fecha[2::], 'cat: DT')
            elif vermax >= 34 and vermax <= 63:
                tcolor = [0.00000, 0.20000, 1.00000]
                tt.append(1)
                print('year: ', fecha[2::], 'cat: TT')
            elif vermax >= 64 and vermax <= 82:
                tcolor = [1.00000, 1.00000, 0.00000]
                h1.append(1)