Пример #1
0
    def getROI(self, point, distCutoff, append=False):
        '''
        Performs checks and additions to interacting with an ROI. Does not alter ROI
        point: global point to check
        returns a new list of tuples of the ROI
        '''
        result = self.ROI.copy()
        if point is not None and len(self.ROI) > 2 and append == False:
            #find distances between point and ROI
            dists = pdist([point] + result)[:len(result)]
            #remove first point with dist <= ROI_DIST
            for i, d in enumerate(dists):
                if d < distCutoff:
                    result.pop(i)
                    return result

            #add between the two closest dists
            dists = np.append(dists, dists[0])
            dist2 = []
            for i in range(len(dists) - 1):
                dist2.append(dists[i] + dists[i + 1])
            #quick, no check for intersection
            #result.insert(np.argmin(dist2)+1, point)

            #slower, checks for overlapping, returns the shortest distance without overlap
            pos = np.argsort(dist2)
            for p in pos:
                #check first leg of path
                segment = Path([result[p], point])
                testSeg = Path(result[p + 1:] + result[:p], [Path.MOVETO] +
                               [Path.LINETO] * (len(result) - 2))
                if testSeg.intersects_path(segment):
                    continue

                #check second leg of path
                if p + 1 == len(result):
                    segment = Path([point, result[0]])
                    testSeg = Path(result[1:], [Path.MOVETO] + [Path.LINETO] *
                                   (len(result) - 2))
                    if testSeg.intersects_path(segment):
                        continue
                else:
                    segment = Path([point, result[p + 1]])
                    testSeg = Path(result[p + 2:] + result[:p + 1],
                                   [Path.MOVETO] + [Path.LINETO] *
                                   (len(result) - 2))
                    if testSeg.intersects_path(segment):
                        continue

                #passed, return:
                result.insert(p + 1, point)
                return result

        elif point is not None:
            result.append(point)

        return result
Пример #2
0
def test_disjoint_zero_length_segment():
    this_path = Path(
        np.array([[824.85064295, 2056.26489203], [861.69033931, 2041.00539016],
                  [868.57864109, 2057.63522175], [831.73894473, 2072.89472361],
                  [824.85064295, 2056.26489203]]),
        np.array([1, 2, 2, 2, 79], dtype=Path.code_type))

    outline_path = Path(
        np.array([[859.91051028, 2165.38461538], [859.06772495, 2149.30331334],
                  [859.06772495, 2181.46591743], [859.91051028, 2165.38461538],
                  [859.91051028, 2165.38461538]]),
        np.array([1, 2, 2, 2, 2], dtype=Path.code_type))

    assert not outline_path.intersects_path(this_path)
    assert not this_path.intersects_path(outline_path)
Пример #3
0
def test_intersect_zero_length_segment():
    this_path = Path(np.array([
        [0, 0],
        [1, 1],
    ]))

    outline_path = Path(np.array([
        [1, 0],
        [.5, .5],
        [.5, .5],
        [0, 1],
    ]))

    assert outline_path.intersects_path(this_path)
    assert this_path.intersects_path(outline_path)
Пример #4
0
def lineWithinPoly(polygons, line):
    for poly in polygons:
        patch = createPolygonPatch(poly, 'grey')

        vcount = 0
        verts = []
        for vertex in poly:
            verts.append(vertex)
            vcount += 1
        verts.append(verts[0])

        codes = [Path.MOVETO]
        for i in range(0, vcount - 1):
            codes.append(Path.LINETO)
        codes.append(Path.CLOSEPOLY)

        path = Path(verts, codes)
        line = np.array([line[0][0], line[0][1], line[1][0],
                         line[1][1]]).reshape(2, 2)
        linecodes = [Path.MOVETO, Path.LINETO, Path.CLOSEPOLY]
        line_path = Path(line)

        if (Path.intersects_path(line_path, path)):
            return True
    return False
Пример #5
0
def intersect(f, s):
    '''
    Return a new patches.Rectangle with the intersection between two patches.Rectangle (f and s parameters) there's one.
    '''
    path_f = Path(f.get_verts())
    path_s = Path(s.get_verts())
    pc = path_f.intersects_path(path_s, filled=False)
    if pc:
        this_boxes = [f, s]
        min_x = min(f.get_verts()[0][0], s.get_verts()[0][0])
        min_y = min(f.get_verts()[0][1], s.get_verts()[0][1])
        max_x = max(f.get_verts()[2][0], s.get_verts()[2][0])
        max_y = max(f.get_verts()[2][1], s.get_verts()[2][1])
        for b in this_boxes:
            min_x = max(min_x, b.get_verts()[0][0])
            min_y = max(min_y, b.get_verts()[0][1])
            max_x = min(max_x, b.get_verts()[2][0])
            max_y = min(max_y, b.get_verts()[2][1])
        dist_x = abs(max_x - min_x)
        dist_y = abs(max_y - min_y)
        inter_box = patches.Rectangle((min_x, min_y),
                                      dist_x,
                                      dist_y,
                                      linewidth=1,
                                      fill=True,
                                      color='r')
        return inter_box
    return None
Пример #6
0
def isCollisionFree(robot, point, obstacles):

    # Your code goes here.

    # Place the robot coordinates at the point
    tempRobot = []
    for i in range(0, len(robot)):
        lst = list(robot[i])
        lst[0] = lst[0] + point[0]
        lst[1] = lst[1] + point[1]
        tempRobot.append(tuple(lst))

    # See the robot is inside an obstacle or vice versa
    for polygon in obstacles:
        polyBorders = Path(polygon)
        for point in tempRobot:
            if polyBorders.contains_point(point):
                return False
    # Vice versa
    roboBorders = Path(tempRobot)
    for polygon in obstacles:
        for point in polygon:
            if roboBorders.contains_point(point):
                return False

    # Check for intersects
    for polygon in obstacles:
        for i in range(0, len(polygon)):
            curr1 = tuple(polygon[i])
            next1 = (0, 0)
            if i == (len(polygon) - 1):
                next1 = tuple(polygon[0])
            else:
                next1 = tuple(polygon[i + 1])
            # robot lines
            for k in range(0, len(tempRobot)):
                curr2 = tempRobot[k]
                next2 = (0, 0)
                if k == (len(tempRobot) - 1):
                    next2 = tempRobot[0]
                else:
                    next2 = tempRobot[k + 1]
                # Check intersection
                line1 = Path([curr1, next1])
                line2 = Path([curr2, next2])
                if line1.intersects_path(line2, filled=False):
                    return False

    # Make sure it's in the graph area
    boundaries = Path([[0.0, 0.0], [0.0, 10.0], [10.0, 10.0], [10.0, 0.0]])
    catch = True
    for point in tempRobot:
        if not boundaries.contains_point(point):
            catch = False

    if catch:
        return True

    return False
Пример #7
0
def edgesIntersect(startVertex1, endVertex1, startVertex2, endVertex2):
    edge1_verts = [startVertex1, endVertex1]
    edge2_verts = [startVertex2, endVertex2]
    edge1 = Path(edge1_verts, codes(len(edge1_verts) - 1))
    edge2 = Path(edge2_verts, codes(len(edge2_verts) - 1))
    if edge1.intersects_path(edge2):
        return True
    else:
        return False
def isCollisionFree(robot, point, obstacles):

    # Your code goes here.
    #define robot path
    verts_b = [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]
    codes_b = [
        Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY
    ]
    boundary_path = Path(verts_b, codes_b)
    verts_r = []
    codes_r = []
    #codes_r.append(Path.MOVETO)
    for i in range(len(robot)):
        x = robot[i][0] + point[0]
        y = robot[i][1] + point[1]
        r_adjusted = (x, y)
        verts_r.append(r_adjusted)
        if i == 0:
            codes_r.append(Path.MOVETO)
        else:
            codes_r.append(Path.LINETO)
    verts_r.append(verts_r[0])
    codes_r.append(Path.CLOSEPOLY)
    robot_path = Path(verts_r, codes_r)

    if not boundary_path.contains_path(robot_path):
        return False

    obstacle_paths = []
    for j in range(len(obstacles)):
        verts_o = []
        codes_o = []
        for i in range(len(obstacles[j])):
            verts_o.append(obstacles[j][i])
            if i == 0:
                codes_o.append(Path.MOVETO)
            else:
                codes_o.append(Path.LINETO)
        verts_o.append(verts_o[0])
        codes_o.append(Path.CLOSEPOLY)
        obstacle_paths.append(Path(verts_o, codes_o))

    for i in range(len(obstacle_paths)):
        if robot_path.intersects_path(obstacle_paths[i], filled=True):
            return False
        else:
            continue

    return True
Пример #9
0
    def detect_all(cls, traf, dtlookahead=None):
        #dtlookahead: lookahead time in s
        if dtlookahead is None:
            dtlookahead = settings.geofence_dtlookahead

        # Linearly extrapolate current state to prefict future position
        pred_lat, pred_lon = geo.kwikpos(traf.lat, traf.lon, traf.hdg,
                                         (dtlookahead * traf.gs) / aero.nm)
        pred_alt = traf.alt + dtlookahead * traf.vs

        # Check intersections with geofences for each aircraft separately
        hits_per_ac = []
        for lat1, lon1, alt1, lat2, lon2, alt2 in zip(traf.lat, traf.lon,
                                                      traf.alt, pred_lat,
                                                      pred_lon, pred_alt):
            hits = []
            # First a course detection based on geofence bounding boxes
            potential_hits = areafilter.get_intersecting(
                min(lat1, lat2), min(lon1, lon2), max(lat1, lat2),
                max(lon1, lon2))

            # Create linearly extrapolated 2D flight path
            flightpath = Path([(lat1, lon1), (lat2, lon2)])

            # Loop through all detected areas from the course detection
            for geofence in potential_hits:
                # Check if the area is a geofence
                if type(geofence) is Geofence:
                    # Check if the 2D horizontal flight path intersects the geofence border
                    if flightpath.intersects_path(geofence.border):
                        # Check if the vertical flight path intersects simultaneously
                        if geofence.bottom <= alt1 <= geofence.top and geofence.bottom <= alt2 <= geofence.top:
                            hits.append(
                                geofence
                            )  # always a hit: entire vertical flight path lies inside
                        else:  # linearly extrapolate flightpath and check points separately
                            lats = np.linspace(
                                lat1, lat2, 100)  # for now use 100 iterations
                            lons = np.linspace(lon1, lon2, 100)
                            alts = np.linspace(alt1, alt2, 100)
                            hit_ver = geofence.checkInside(lats, lons, alts)
                            if np.any(hit_ver):
                                hits.append(geofence)

            # Finally append all geofence hits to the overall list
            hits_per_ac.append(hits)

        return hits_per_ac
Пример #10
0
class Room(Location):
    priority = 2

    def __init__(self, graph, name, level, titles, shape):
        super().__init__(name, titles)
        self.graph = graph
        self.level = level
        self.shape = shape
        self.nodes = []
        self.pois = []
        self.barriers = []
        self.groups = []

        mpl_xy = self.shape + self.shape[-1:]
        mpl_codes = [Path.MOVETO] + [Path.LINETO] * len(self.shape)
        self.mpl_path = Path(np.array(mpl_xy), codes=mpl_codes)

    @property
    def priority(self):
        return 1 if self.groups else 2

    def contains_position(self, position):
        if position.level != self.level:
            return False

        return self.mpl_path.contains_point((position.x, position.y))

    def get_barriers(self):
        return (b for b in self.graph.barriers if b.level == self.level
                and self.mpl_path.intersects_path(b.mpl_path, True))

    def barrier_paths(self):
        return [self.mpl_path] + [b.mpl_path for b in self.barriers]

    @property
    def subtitle(self):
        if not self.groups:
            return _('Level %(level)d', level=self.level)
        else:
            return _('%(roomgroup)s, Level %(level)d',
                     roomgroup=self.groups[0].collection_title,
                     level=self.level)

    def __repr__(self):
        return 'Room(%s)' % repr(self.name)
Пример #11
0
class Room(Location):
    ltype = 'room'
    priority = 2

    def __init__(self, graph, name, level, titles, shape):
        super().__init__(name, titles)
        self.graph = graph
        self.level = level
        self.shape = shape
        self.nodes = []
        self.pois = []
        self.barriers = []
        self.groups = []

        mpl_xy = self.shape+self.shape[-1:]
        mpl_codes = [Path.MOVETO] + [Path.LINETO]*len(self.shape)
        self.mpl_path = Path(np.array(mpl_xy), codes=mpl_codes)

    @property
    def priority(self):
        return 1 if self.groups else 2

    def contains_position(self, position):
        if position.level != self.level:
            return False

        return self.mpl_path.contains_point((position.x, position.y))

    def get_barriers(self):
        return (b for b in self.graph.barriers
                if b.level == self.level and self.mpl_path.intersects_path(b.mpl_path, True))

    def barrier_paths(self):
        return [self.mpl_path] + [b.mpl_path for b in self.barriers]

    @property
    def subtitle(self):
        if not self.groups:
            return _('Level %(level)d', level=self.level)
        else:
            return _('%(roomgroup)s, Level %(level)d', roomgroup=self.groups[0].collection_title, level=self.level)

    def __repr__(self):
        return 'Room(%s)' % repr(self.name)
Пример #12
0
def removeConvex(S):
    S_prime = []
    for i in range(0, len(S)):
        S_prime.append(S[i])
        S[i].append(S[i][0])
        polygon_path = Path(S[i], codes(len(S[i]) - 1))
        del S[i][-1]
        for j in range(0, len(S[i])):
            if j == len(S[i]) - 1:
                verts = [S[i][j], S[i][1]]
            elif j == len(S[i]) - 2:
                verts = [S[i][j], S[i][0]]
            else:
                verts = [S[i][j], S[i][j + 2]]
            line = Path(verts, codes(1))
            inside = polygon_path.intersects_path(line)
            if inside == False:
                S_prime[i].remove(S[i][j])
    return S_prime
Пример #13
0
def intersectLines(line, tree, points):
    firstline = np.array([line[0][0], line[0][1], line[1][0],
                          line[1][1]]).reshape(2, 2)
    for i in tree:
        for j in tree[i]:
            if points[i] == line[0] or points[i] == line[1] or points[
                    j] == line[0] or points[j] == line[1]:
                continue
            line2 = [points[i], points[j]]
            secondline = np.array(
                [line2[0][0], line2[0][1], line2[1][0],
                 line2[1][1]]).reshape(2, 2)

            linecodes = [Path.MOVETO, Path.LINETO, Path.CLOSEPOLY]
            line_path = Path(firstline)
            line_path2 = Path(secondline)

            if (Path.intersects_path(line_path, line_path2, filled=True)):
                return True
    return False
Пример #14
0
def traceArm2(edgeMap, traceStart, vD, dir1, dir2, paths, shortestPaths=None, G=None, lineStart=None):
   if lineStart is None:
      lineStart = traceStart
   dirvec = normalize(np.mean([normalize(dir1),normalize(dir2)],0))
   maxAngle = abs(angle(dir1,dir2))/2
   
   path = [start]
   oldlength = 0
   candidates = list(edgeMap[start].difference(path))
   while len(candidates)>0:
      angles = map(lambda x: abs(angle(vD.vertices[x,:]-vD.vertices[lineStart,:], dirvec, np.inf)), nodes)
      
      newCoordinate = vD.vertices[candidates[np.argmin(angles)]]
      newlength = np.linalg.norm(new-coordinate - vD.vertices[start])
      curEdge = Path([vD.vertices[start], new-coordinate], [1, 2])
      if np.any(map(lambda p: curEdge.intersects_path(p, False), paths)) or oldlength > newlength or min(angles) > maxAngle:
         break
      oldlength = newlength
      path.append(candidates[np.argmin(angles)])
      candidates = list(edgeMap[path[-1]].difference(path))
   return path
Пример #15
0
    def check_connection(self, point1, point2):
        path = Path(np.vstack((point1, point2)))
        distance = abs(np.linalg.norm(point1 - point2))

        # lies within room
        if self.mpl_clear.intersects_path(path):
            return None, None, None

        if self.room.stuffedareas.intersects_path(path, filled=True):
            distance *= 2.5

        # stair checker
        angle = coord_angle(point1, point2)
        stair_direction_up = None
        for stair_path, stair_angle in self.mpl_stairs:
            if not path.intersects_path(stair_path):
                continue

            angle_diff = ((stair_angle - angle + 180) % 360) - 180

            new_direction_up = (angle_diff > 0)
            if stair_direction_up is None:
                stair_direction_up = new_direction_up
            elif stair_direction_up != new_direction_up:
                return None, None, None

            if not (40 < abs(angle_diff) < 150):
                return None, None, None

        # escalator checker
        angle = coord_angle(point1, point2)
        escalator_direction_up = None
        escalator_swap_direction = False
        for escalator in self.escalators:
            if not escalator.mpl_geom.intersects_path(path, filled=True):
                continue

            if escalator_direction_up is not None:
                # only one escalator per connection
                return None, None, None

            angle_diff = ((escalator.angle - angle + 180) % 360) - 180

            escalator_direction_up = (angle_diff > 0)
            escalator_swap_direction = (escalator_direction_up !=
                                        escalator.direction_up)

        if stair_direction_up is not None:
            return (
                ('stairs_up' if stair_direction_up else 'stairs_down'),
                ('stairs_down' if stair_direction_up else 'stairs_up'),
                distance,
            )
        elif escalator_direction_up is not None:
            if not escalator_swap_direction:
                return ('escalator_up' if escalator_direction_up else
                        'escalator_down'), None, distance
            else:
                return None, ('escalator_down' if escalator_direction_up else
                              'escalator_up'), distance

        return '', '', distance
Пример #16
0
    obstacle_paths = []
    for j in range(len(obstacles)):
        verts_o = []
        codes_o = []
        for i in range(len(obstacles[j])):
            verts_o.append(obstacles[j][i])
            if i == 0:
                codes_o.append(Path.MOVETO)
            else:
                codes_o.append(Path.LINETO)
        verts_o.append(verts_o[0])
        codes_o.append(Path.CLOSEPOLY)
        obstacle_paths.append(Path(verts_o, codes_o))

    for i in range(len(obstacle_paths)):
        if line_path.intersects_path(obstacle_paths[i], filled=True):
            return False
        else:
            continue
    return True


def findPoints(px, py, pi, points, adjListMap):
    min_dist = 1000
    x_min = -5
    y_min = -5
    i_min = -1
    j_min = -1
    for i in adjListMap:
        if adjListMap[i]:
            wx = points[i][0]
Пример #17
0
class Polygon(Region):
    def __init__(self, lon_list, lat_list):
        assert len(lon_list) == len(lat_list)
        assert len(lon_list) > 2

        # Check that input is a list
        lon_list = list(lon_list)
        lat_list = list(lat_list)
        
        # Save the longitude and the latitude lists
        self.__lon_list = lon_list
        self.__lat_list = lat_list

        # Ensure that the input is close
        if lon_list[-1] != lon_list[0] or lat_list[-1] != lat_list[0]:
            lon_list.append(lon_list[0])
            lat_list.append(lat_list[0])
        
        # Create a path object
        codes = [Path.LINETO] * len(lon_list)
        codes[0]  = Path.MOVETO
        codes[-1] = Path.CLOSEPOLY
        
        coords = [ (lon_list[i], lat_list[i]) for i in range(len(lon_list))]
        
        self.path = Path(coords, codes)
        
    def is_inside(self, lon, lat):
        points_coord = np.array((lon,lat)).T

        reshaped = False
        if len(points_coord.shape) < 2:
            points_coord = points_coord.reshape(1,2)
            reshaped = True

        inside = self.path.contains_points(points_coord)

        if reshaped:
            return inside[0]
        else:
            return inside
    
    @property 
    def border_latitudes(self):
        return self.__lat_list

    @property 
    def border_longitudes(self):
        return self.__lon_list

    @property 
    def borders(self):
        output = []
        for i in range(len(self.__lon_list)):
            lon = self.border_longitudes[i]
            lat = self.border_latitudes[i]
            output.append((lon, lat))
        return tuple(output)

    def cross(self, another_region):
        # The following lines are useful if another_region is a basin
        if hasattr(another_region, "region"):
            another_region = another_region.region

        if isinstance(another_region, Polygon):
            return np.bool_(self.path.intersects_path(another_region.path, filled=True))
        elif isinstance(another_region, RegionUnion):
            return another_region.cross(self)
        elif isinstance(another_region, EmptyRegion):
            return False
        else:
            raise NotImplementedError
Пример #18
0
    def get_track(self, jnu, lon, lat):  #,b_index,nvdepth,,bcon
        '''
        Get forecast points start at lon,lat
        '''
        modpts = dict(lon=[lon], lat=[lat], time=[],
                      spd=[])  #model forecast points, layer=[]
        #uvz = netCDF4.Dataset(self.url)
        #u = uvz.variables['u']; v = uvz.variables['v']; zeta = uvz.variables['zeta']
        #print 'len u',len(u)
        '''if lon>90:
            lon, lat = dm2dd(lon, lat)#'''

        try:
            if self.modelname == "GOM3" or self.modelname == "30yr":
                lonp, latp = self.nearest_point(lon, lat, self.lonl, self.latl,
                                                0.2)
                #lonn,latn = self.nearest_point(lon,lat,self.lonk,self.latk,0.3)
            if self.modelname == "massbay":
                lonp, latp = self.nearest_point(lon, lat, self.lonl, self.latl,
                                                0.03)
                #lonn,latn = self.nearest_point(lon,lat,self.lonk,self.latk,0.05)
            index1 = np.where(self.lonc == lonp)
            index2 = np.where(self.latc == latp)
            elementindex = np.intersect1d(index1, index2)
            #index3 = np.where(self.lons==lonn)
            #index4 = np.where(self.lats==latn)
            #nodeindex = np.intersect1d(index3,index4); #print 'here index'
            ################## boundary 1 ####################
            modpts['time'].append(self.mTime[0])
            pa = self.eline_path(lon, lat)
            #print 'here boundary_path'

        except:
            return modpts, 0

        t = abs(self.hours)
        #layer = 0
        #mapx = Basemap(projection='ortho',lat_0=lat,lon_0=lon,resolution='l')
        for i in xrange(t):
            '''if i!=0 and i%24==0 :
                #print 'layer,lon,lat,i',layer,lon,lat,i
                lonl,latl = self.shrink_data(lon,lat,self.lonc,self.latc,0.5)
                lonk,latk = self.shrink_data(lon,lat,self.lons,self.lats,0.5)#'''
            if i < jnu: continue

            u_t1 = self.u[i, elementindex][0]
            v_t1 = self.v[i, elementindex][0]
            #u_t2 = self.u[i+1,layer,elementindex][0]; v_t2 = self.v[i+1,layer,elementindex][0]
            #u_t,v_t = self.uvt(u_t1,v_t1,u_t2,v_t2)
            #u_t = (u_t1+u_t2)/2; v_t = (v_t1+v_t2)/2

            dx = 60 * 60 * u_t1
            dy = 60 * 60 * v_t1
            pspeed = math.sqrt(u_t1**2 + v_t1**2)
            modpts['spd'].append(pspeed)
            if i == t - 1:  # stop when got the last point speed.
                return modpts, 2
            if i >= jnu + 12:  # break
                return modpts, 2
            #x,y = mapx(lon,lat)
            #temlon,temlat = mapx(x+dx,y+dy,inverse=True)
            temlon = lon + (dx / (111111 * np.cos(lat * np.pi / 180)))
            temlat = lat + dy / 111111  #'''
            if not self.sp.contains_point((temlon, temlat)):
                #break;
                return modpts, 3
            #########case for boundary 1 #############
            if pa:
                pat = Path(pa)
                teml = [(lon, lat), (temlon, temlat)]
                #print temlon,temlat
                tempa = Path(teml)
                if pat.intersects_path(tempa):
                    #if bcon == 'stop':
                    modpts['lon'].append(temlon)
                    modpts['lat'].append(temlat)  #; modpts['layer'].append(0)
                    print 'Sorry, point hits land here. Path. Last point:', temlon, temlat
                    return modpts, 1  #''''
            #########################
            lon = temlon
            lat = temlat
            #if i!=(t-1):
            try:
                if self.modelname == "GOM3" or self.modelname == "30yr":
                    lonp, latp = self.nearest_point(lon, lat, self.lonl,
                                                    self.latl, 0.2)
                    #lonn,latn = self.nearest_point(lon,lat,self.lonk,self.latk,0.3)
                if self.modelname == "massbay":
                    lonp, latp = self.nearest_point(lon, lat, self.lonl,
                                                    self.latl, 0.03)
                    #lonn,latn = self.nearest_point(lon,lat,self.lonk,self.latk,0.05)
                index1 = np.where(self.lonc == lonp)
                index2 = np.where(self.latc == latp)
                elementindex = np.intersect1d(index1, index2)
                #print 'elementindex',elementindex
                #index3 = np.where(self.lons==lonn)
                #index4 = np.where(self.lats==latn)
                #nodeindex = np.intersect1d(index3,index4)

                ################## boundary 1 ####################
                modpts['time'].append(self.mTime[i + 1])
                pa = self.eline_path(lon, lat)

                modpts['lon'].append(lon)
                modpts['lat'].append(lat)  #; modpts['layer'].append(layer);
                print '%d,Lat,Lon,Speed' % (i + 1), temlat, temlon, pspeed

            except:
                return modpts, 1
Пример #19
0
def test_path_intersect_path():
    # test for the range of intersection angles
    base_angles = np.array([0, 15, 30, 45, 60, 75, 90, 105, 120, 135])
    angles = np.concatenate([base_angles, base_angles + 1, base_angles - 1])
    eps_array = [1e-5, 1e-8, 1e-10, 1e-12]

    for phi in angles:

        transform = transforms.Affine2D().rotate(np.deg2rad(phi))

        # a and b intersect at angle phi
        a = Path([(-2, 0), (2, 0)])
        b = transform.transform_path(a)
        assert a.intersects_path(b) and b.intersects_path(a)

        # a and b touch at angle phi at (0, 0)
        a = Path([(0, 0), (2, 0)])
        b = transform.transform_path(a)
        assert a.intersects_path(b) and b.intersects_path(a)

        # a and b are orthogonal and intersect at (0, 3)
        a = transform.transform_path(Path([(0, 1), (0, 3)]))
        b = transform.transform_path(Path([(1, 3), (0, 3)]))
        assert a.intersects_path(b) and b.intersects_path(a)

        # a and b are collinear and intersect at (0, 3)
        a = transform.transform_path(Path([(0, 1), (0, 3)]))
        b = transform.transform_path(Path([(0, 5), (0, 3)]))
        assert a.intersects_path(b) and b.intersects_path(a)

        # self-intersect
        assert a.intersects_path(a)

        # a contains b
        a = transform.transform_path(Path([(0, 0), (5, 5)]))
        b = transform.transform_path(Path([(1, 1), (3, 3)]))
        assert a.intersects_path(b) and b.intersects_path(a)

        # a and b are collinear but do not intersect
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(3, 0), (3, 3)]))
        assert not a.intersects_path(b) and not b.intersects_path(a)

        # a and b are on the same line but do not intersect
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0, 6), (0, 7)]))
        assert not a.intersects_path(b) and not b.intersects_path(a)

        # Note: 1e-13 is the absolute tolerance error used for
        # `isclose` function from src/_path.h

        # a and b are parallel but do not touch
        for eps in eps_array:
            a = transform.transform_path(Path([(0, 1), (0, 5)]))
            b = transform.transform_path(Path([(0 + eps, 1), (0 + eps, 5)]))
            assert not a.intersects_path(b) and not b.intersects_path(a)

        # a and b are on the same line but do not intersect (really close)
        for eps in eps_array:
            a = transform.transform_path(Path([(0, 1), (0, 5)]))
            b = transform.transform_path(Path([(0, 5 + eps), (0, 7)]))
            assert not a.intersects_path(b) and not b.intersects_path(a)

        # a and b are on the same line and intersect (really close)
        for eps in eps_array:
            a = transform.transform_path(Path([(0, 1), (0, 5)]))
            b = transform.transform_path(Path([(0, 5 - eps), (0, 7)]))
            assert a.intersects_path(b) and b.intersects_path(a)

        # b is the same as a but with an extra point
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0, 1), (0, 2), (0, 5)]))
        assert a.intersects_path(b) and b.intersects_path(a)

    return
Пример #20
0
    def get_track(self, jnu, lon, lat, depth, track_way, leh,
                  bcon):  #,b_index,nvdepth,
        '''
        Get forecast points start at lon,lat
        '''
        modpts = dict(lon=[lon], lat=[lat], layer=[], time=[],
                      spd=[])  #model forecast points
        #uvz = netCDF4.Dataset(self.url)
        #u = uvz.variables['u']; v = uvz.variables['v']; zeta = uvz.variables['zeta']
        #print 'len u',len(u)
        '''if lon>90:
            lon, lat = dm2dd(lon, lat)#'''

        try:
            if self.modelname == "GOM3" or self.modelname == "30yr":
                lonp, latp = self.nearest_point(lon, lat, self.lonl, self.latl,
                                                0.2)
                lonn, latn = self.nearest_point(lon, lat, self.lonk, self.latk,
                                                0.3)
            if self.modelname == "massbay":
                lonp, latp = self.nearest_point(lon, lat, self.lonl, self.latl,
                                                0.03)
                lonn, latn = self.nearest_point(lon, lat, self.lonk, self.latk,
                                                0.05)
            index1 = np.where(self.lonc == lonp)
            index2 = np.where(self.latc == latp)
            elementindex = np.intersect1d(index1, index2)
            index3 = np.where(self.lons == lonn)
            index4 = np.where(self.lats == latn)
            nodeindex = np.intersect1d(index3, index4)
            #print 'here index'
            ################## boundary 1 ####################
            pa = self.eline_path(lon, lat)
            #print 'here boundary_path'

            if track_way == 'backward':  # backwards case
                if self.modelname == "30yr":
                    waterdepth = self.h[nodeindex]
                else:
                    waterdepth = self.h[nodeindex] + self.zeta[-1, nodeindex]
                modpts['time'].append(self.mTime[-1])
            else:
                #print 'h,zeta',self.h[nodeindex],self.zeta[0,nodeindex]
                if self.modelname == "30yr":
                    waterdepth = self.h[nodeindex]
                else:
                    waterdepth = self.h[nodeindex] + self.zeta[0, nodeindex]
                modpts['time'].append(self.mTime[0])
            depth_total = self.siglay[:, nodeindex] * waterdepth
            #print 'Here one'
            layer = np.argmin(abs(depth_total + depth))
            #print 'layer',layer
            modpts['layer'].append(layer)
            if waterdepth < (abs(depth)):
                print 'This point is too shallow.Less than %d meter.' % abs(
                    depth)
                raise Exception()
        except:
            return modpts, 0

        t = abs(self.hours)
        #mapx = Basemap(projection='ortho',lat_0=lat,lon_0=lon,resolution='l')
        for i in xrange(t):
            '''if i!=0 and i%24==0 :
                #print 'layer,lon,lat,i',layer,lon,lat,i
                lonl,latl = self.shrink_data(lon,lat,self.lonc,self.latc,0.5)
                lonk,latk = self.shrink_data(lon,lat,self.lons,self.lats,0.5)#'''
            if i < jnu: continue
            if track_way == 'backward':  # backwards case
                u_t1 = self.u[t - i, layer, elementindex][0] * (-1)
                v_t1 = self.v[t - i, layer, elementindex][0] * (-1)
                #u_t2 = self.u[t-i-1,layer,elementindex][0]*(-1); v_t2 = self.v[t-i-1,layer,elementindex][0]*(-1)
            else:
                u_t1 = self.u[i, layer, elementindex][0]
                v_t1 = self.v[i, layer, elementindex][0]
                #u_t2 = self.u[i+1,layer,elementindex][0]; v_t2 = self.v[i+1,layer,elementindex][0]
            #u_t,v_t = self.uvt(u_t1,v_t1,u_t2,v_t2)
            #u_t = (u_t1+u_t2)/2; v_t = (v_t1+v_t2)/2
            '''if u_t==0 and v_t==0: #There is no water
                print 'Sorry, hits the land,u,v==0'
                return modpts,1 #'''
            #print "u[i,layer,elementindex]",u[i,layer,elementindex]
            dx = 60 * 60 * u_t1
            dy = 60 * 60 * v_t1
            pspeed = math.sqrt(u_t1**2 + v_t1**2)
            modpts['spd'].append(pspeed)
            if i == t - 1:  # stop when got the last point speed.
                return modpts, 2
            #x,y = mapx(lon,lat)
            #temlon,temlat = mapx(x+dx,y+dy,inverse=True)
            temlon = lon + (dx / (111111 * np.cos(lat * np.pi / 180)))
            temlat = lat + dy / 111111  #'''
            if not self.sp.contains_point((temlon, temlat)):
                #break;
                return modpts, 3
            #########case for boundary 1 #############
            if pa:
                pat = Path(pa)
                teml = [(lon, lat), (temlon, temlat)]
                #print temlon,temlat
                tempa = Path(teml)
                if pat.intersects_path(tempa):
                    if bcon == 'stop':
                        modpts['lon'].append(temlon)
                        modpts['lat'].append(temlat)
                        modpts['layer'].append(0)
                        print 'Sorry, point hits land here. Path. Last point:', temlon, temlat
                        return modpts, 1  #'''
                    if bcon == 'reflection':
                        f1 = (lon, lat)
                        f2 = (temlon, temlat)
                        v = (u_t1, v_t1)
                        #fl = Path([f1,f2])
                        for k in range(len(pa) - 1):
                            kl = Path([pa[k], pa[k + 1]])
                            if tempa.intersects_path(kl):
                                print 'Reflection^^^^>>>>>>>>>>>>'
                                (temlon, temlat) = self.uvreflection(
                                    f1, f2, pa[k], pa[k + 1], v)
                                break

            #########case for boundary 2 #############
            '''if pa :
                if not pa.contains_point([temlon,temlat]):
                    print 'Sorry, point hits land here.path'
                    return modpts,1 #'''
            #########################
            lon = temlon
            lat = temlat
            #if i!=(t-1):
            try:
                if self.modelname == "GOM3" or self.modelname == "30yr":
                    lonp, latp = self.nearest_point(lon, lat, self.lonl,
                                                    self.latl, 0.2)
                    lonn, latn = self.nearest_point(lon, lat, self.lonk,
                                                    self.latk, 0.3)
                if self.modelname == "massbay":
                    lonp, latp = self.nearest_point(lon, lat, self.lonl,
                                                    self.latl, 0.03)
                    lonn, latn = self.nearest_point(lon, lat, self.lonk,
                                                    self.latk, 0.05)
                index1 = np.where(self.lonc == lonp)
                index2 = np.where(self.latc == latp)
                elementindex = np.intersect1d(index1, index2)
                #print 'elementindex',elementindex
                index3 = np.where(self.lons == lonn)
                index4 = np.where(self.lats == latn)
                nodeindex = np.intersect1d(index3, index4)

                ################## boundary 1 ####################

                pa = self.eline_path(lon, lat)

                if track_way == 'backward':  # backwards case
                    if self.modelname == "30yr":
                        waterdepth = self.h[nodeindex]
                    else:
                        waterdepth = self.h[nodeindex] + self.zeta[t - i - 1,
                                                                   nodeindex]
                    modpts['time'].append(self.mTime[t - i - 1])
                else:
                    #print 'h,zeta',self.h[nodeindex],self.zeta[0,nodeindex]
                    if self.modelname == "30yr":
                        waterdepth = self.h[nodeindex]
                    else:
                        waterdepth = self.h[nodeindex] + self.zeta[i + 1,
                                                                   nodeindex]
                    modpts['time'].append(self.mTime[i + 1])

                depth_total = self.siglay[:, nodeindex] * waterdepth
                layer = np.argmin(abs(depth_total + depth))
                modpts['lon'].append(lon)
                modpts['lat'].append(lat)
                modpts['layer'].append(layer)
                print '%d,Lat,Lon,Layer,Speed' % (
                    i + 1), temlat, temlon, layer, pspeed
                if waterdepth < (abs(depth)):
                    print 'This point hits the land here.Less than %d meter.' % abs(
                        depth)
                    raise Exception()
            except:
                return modpts, 1
Пример #21
0
def test_path_intersect_path(phi):
    # test for the range of intersection angles
    eps_array = [1e-5, 1e-8, 1e-10, 1e-12]

    transform = transforms.Affine2D().rotate(np.deg2rad(phi))

    # a and b intersect at angle phi
    a = Path([(-2, 0), (2, 0)])
    b = transform.transform_path(a)
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b touch at angle phi at (0, 0)
    a = Path([(0, 0), (2, 0)])
    b = transform.transform_path(a)
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b are orthogonal and intersect at (0, 3)
    a = transform.transform_path(Path([(0, 1), (0, 3)]))
    b = transform.transform_path(Path([(1, 3), (0, 3)]))
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b are collinear and intersect at (0, 3)
    a = transform.transform_path(Path([(0, 1), (0, 3)]))
    b = transform.transform_path(Path([(0, 5), (0, 3)]))
    assert a.intersects_path(b) and b.intersects_path(a)

    # self-intersect
    assert a.intersects_path(a)

    # a contains b
    a = transform.transform_path(Path([(0, 0), (5, 5)]))
    b = transform.transform_path(Path([(1, 1), (3, 3)]))
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b are collinear but do not intersect
    a = transform.transform_path(Path([(0, 1), (0, 5)]))
    b = transform.transform_path(Path([(3, 0), (3, 3)]))
    assert not a.intersects_path(b) and not b.intersects_path(a)

    # a and b are on the same line but do not intersect
    a = transform.transform_path(Path([(0, 1), (0, 5)]))
    b = transform.transform_path(Path([(0, 6), (0, 7)]))
    assert not a.intersects_path(b) and not b.intersects_path(a)

    # Note: 1e-13 is the absolute tolerance error used for
    # `isclose` function from src/_path.h

    # a and b are parallel but do not touch
    for eps in eps_array:
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0 + eps, 1), (0 + eps, 5)]))
        assert not a.intersects_path(b) and not b.intersects_path(a)

    # a and b are on the same line but do not intersect (really close)
    for eps in eps_array:
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0, 5 + eps), (0, 7)]))
        assert not a.intersects_path(b) and not b.intersects_path(a)

    # a and b are on the same line and intersect (really close)
    for eps in eps_array:
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0, 5 - eps), (0, 7)]))
        assert a.intersects_path(b) and b.intersects_path(a)

    # b is the same as a but with an extra point
    a = transform.transform_path(Path([(0, 1), (0, 5)]))
    b = transform.transform_path(Path([(0, 1), (0, 2), (0, 5)]))
    assert a.intersects_path(b) and b.intersects_path(a)
Пример #22
0
for a in range(0,2):
    x_0 = randint(-9,9)
    y_0 = randint(-9,9)
    x_length = randint(1,10)
    y_length = randint(1,10)
    internal_rect = patches.Rectangle((x_0,y_0),x_length,y_length,linewidth=1,edgecolor='b', facecolor='none')
    boxes.append(internal_rect)
"""
f = patches.Rectangle((3,3),1,1,linewidth=1,edgecolor='b', fill = None)
s = patches.Rectangle((4,4),1,1,linewidth=1,edgecolor='y', fill = None)
boxes.append(f)
boxes.append(s)


path_f = Path(f.get_verts())
path_s = Path(s.get_verts())

pc = path_f.intersects_path(path_s, filled = True)
bbc = path_f.intersects_bbox(s.get_bbox(), filled = True)
print('path intersection', pc , 'bbox intersection',bbc)

"""
for (fi,f) in enumerate(boxes):
    for (si,s) in enumerate(boxes):
        pc = f.get_path().intersects_path(s.get_path(), filled = False)
        bbc = f.get_path().intersects_bbox(s.get_bbox(), filled = True)
        print(fi,si,'path intersection', pc , 'bbox intersection',bbc)
"""
for p in boxes:
    ax.add_patch(p)
plt.show()