Esempio n. 1
0
    def _clipBounds(self):
        """
        Clip input vector data to bounds of map.
        """
        # returns a list of GeoJSON-like mapping objects
        comp = self.container.getComponents('MMI')[0]
        imtdict = self.container.getIMTGrids('MMI', comp)
        geodict = imtdict['mean'].getGeoDict()
        xmin, xmax, ymin, ymax = (geodict.xmin, geodict.xmax,
                                  geodict.ymin, geodict.ymax)
        bbox = (xmin, ymin, xmax, ymax)
        bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax),
                             (xmax, ymin), (xmin, ymin), (xmin, ymax)])
        self.vectors = {}
        for key, value in self.layerdict.items():
            vshapes = []
            f = fiona.open(value, 'r')
            shapes = f.items(bbox=bbox)
            for shapeidx, shape in shapes:
                tshape = sShape(shape['geometry'])
                try:
                    intshape = tshape.intersection(bboxpoly)
#                except TopologicalError as te:
                except Exception as te:
                    self.logger.warn('Failure to grab %s segment: "%s"'
                                     % (key, str(te)))
                    continue
                vshapes.append(intshape)
            self.logger.debug('Filename is %s' % value)
            f.close()
            self.vectors[key] = vshapes
Esempio n. 2
0
def _clip_bounds(bbox, filename):
    """Clip input fiona-compatible vector file to input bounding box.

    :param bbox:
      Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds.
    :param filename:
      Input name of file containing vector data in a format compatible
      with fiona.
    :returns:
      Shapely Geometry object (Polygon or MultiPolygon).
    """
    f = fiona.open(filename, 'r')
    shapes = list(f.items(bbox=bbox))
    xmin, ymin, xmax, ymax = bbox
    newshapes = []
    bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax), (xmax, ymin),
                         (xmin, ymin), (xmin, ymax)])
    for tshape in shapes:
        myshape = sShape(tshape[1]['geometry'])
        intshape = myshape.intersection(bboxpoly)
        newshapes.append(intshape)
        newshapes.append(myshape)
    gc = GeometryCollection(newshapes)
    f.close()
    return gc
Esempio n. 3
0
    def _selectRoads(self, roads_folder, bbox):
        """Select road shapes from roads directory.

        Args:
            roads_folder (str): Path to folder containing global roads data.
            bbox (tuple): Tuple of map bounds (xmin,ymin,xmax,ymax).

        Returns:
            list: list of Shapely geometries.
        """
        vshapes = []
        xmin, ymin, xmax, ymax = bbox
        bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax),
                             (xmax, ymin), (xmin, ymin), (xmin, ymax)])
        for root, dirs, files in os.walk(roads_folder):
            for fname in files:
                if fname.endswith('.shp'):
                    filename = os.path.join(root, fname)
                    with fiona.open(filename, 'r') as f:
                        shapes = f.items(bbox=bbox)
                        for shapeidx, shape in shapes:
                            tshape = sShape(shape['geometry'])
                            intshape = tshape.intersection(bboxpoly)
                            vshapes.append(intshape)

        return vshapes
Esempio n. 4
0
 def nest(obj):
     if isinstance(obj, Collection):
         for d in obj.data:
             nest(d)
     elif isinstance(obj, Polygon):
         p = sPolygon(obj.points[:])
         polys.append(p)
         for arc in obj.arcs:
             nest(arc)
     elif isinstance(obj, Arc):
         nest(arc_to_poly(obj))
     else:
         raise Exception(("shape not supported", obj))
Esempio n. 5
0
def getProjectedPolygon(polygon,m):
    extlon,extlat = zip(*polygon.exterior.coords[:])
    extx,exty = m(extlon,extlat)
    extpts = list(zip(extx,exty))
    ints = []
    for interior in polygon.interiors:
        try:
            intlon,intlat = zip(*interior.coords[:])
        except:
            x = 1
        intx,inty = m(intlon,intlat)
        ints.append(list(zip(intx,inty)))
    ppolygon = sPolygon(extpts,ints)
    return ppolygon
Esempio n. 6
0
 def _clipBounds(self):
     #returns a list of GeoJSON-like mapping objects
     xmin,xmax,ymin,ymax = self.shakemap.getBounds()
     bbox = (xmin,ymin,xmax,ymax)
     bboxpoly = sPolygon([(xmin,ymax),(xmax,ymax),(xmax,ymin),(xmin,ymin),(xmin,ymax)])
     self.vectors = {}
     for key,value in self.layerdict.items():
         vshapes = []
         f = fiona.open(value,'r')
         shapes = f.items(bbox=bbox)
         for shapeidx,shape in shapes:
             tshape = sShape(shape['geometry'])
             intshape = tshape.intersection(bboxpoly)
             vshapes.append(intshape)
         print('Filename is %s' % value)
         f.close()
         self.vectors[key] = vshapes
Esempio n. 7
0
def get_nbhd_reps(city):
    city_state = {'New York': 'NY', 'Philadelphia': 'PA'}
    nbhd_map = shpf.Reader("ZillowNeighborhoods-{}.shp".format(
        city_state[city]))
    shapes = nbhd_map.shapes()
    records = nbhd_map.records()
    shape_points = [k.points for k in shapes]
    polygons = [sPolygon(k) for k in shape_points]
    out = []
    exceptout = []
    for poly, record in zip(polygons, records):
        try:
            if record[2] == city:
                out.append(((city, record[3]),
                            (poly.representative_point().xy[0][0],
                             poly.representative_point().xy[1][0])))
        except ValueError:
            out.append(((city, record[3]), None))
            exceptout.append(((city, record[3]), None))
            print(city, record[3])
    return dict(out), dict(exceptout)
Esempio n. 8
0
def _clip_bounds(bbox, filename):
    """Clip input fiona-compatible vector file to input bounding box.

    :param bbox:
      Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds.
    :param filename:
      Input name of file containing vector data in a format compatible with fiona.
    :returns:
      Shapely Geometry object (Polygon or MultiPolygon).
    """
    #returns a clipped shapely object
    xmin, ymin, xmax, ymax = bbox
    bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax), (xmax, ymin),
                         (xmin, ymin), (xmin, ymax)])
    vshapes = []
    f = fiona.open(filename, 'r')
    shapes = f.items(bbox=bbox)
    for shapeidx, shape in shapes:
        tshape = sShape(shape['geometry'])
        intshape = tshape.intersection(bboxpoly)
        vshapes.append(intshape)
    f.close()
    return vshapes
Esempio n. 9
0
def getProjectedPolygon(polygon, m):
    """
    Project a lat/lon polygon into the projection defined by Basemap instance.

    Args:
        polygon (Polygon): Shapely polygon.
        m (Basemap): Basemap instance.

    Returns:
        Polygon: Shapely polygon, with vertices projected.
    """
    extlon, extlat = zip(*polygon.exterior.coords[:])
    extx, exty = m(extlon, extlat)
    extpts = list(zip(extx, exty))
    ints = []
    for interior in polygon.interiors:
        try:
            intlon, intlat = zip(*interior.coords[:])
        except:
            x = 1
        intx, inty = m(intlon, intlat)
        ints.append(list(zip(intx, inty)))
    ppolygon = sPolygon(extpts, ints)
    return ppolygon
Esempio n. 10
0
                             upper_limit) == 1):
                print(1, end='')
                io_points.append(1)
            else:
                print(1, end='')
                io_points.append(1)
        print()
        if (sum(io_points) == len(io_points)):
            print("в допуске")
        else:
            print("не в допуске")
        #circ_patch = Circle((y_centers_straight[axs_count], z_centers_straight[axs_count]), 0.5, color='tab:blue', alpha = 0.5)
        #axs1[i][j].add_patch(circ_patch)

        try:
            coords_xy_1 = sPolygon(verts1)
            coords_xy_2 = sPolygon(verts2)
            ##the intersect will be outlined in black
            intersect = coords_xy_1.intersection(coords_xy_2)

            #print("intersect", intersect, intersect == "POLYGON EMPTY", intersect.length)
            if (intersect.length == 0.0):
                print(axs_count, "нет пересечений")
                axs_count += 1
                continue
            else:
                pass

            verts3 = np.array(intersect.exterior.coords.xy)
            patch3 = mPolygon(verts3.T, facecolor='none', edgecolor='black')
            axs1[i][j].add_patch(patch3)
Esempio n. 11
0
    def subset(self, raster_data, **kwargs):
        # It is possible our user has drawn a polygon where part of the
        # shape is outside the dataset,  intersect with the rasterdata
        # shape to make sure we don't try to select/mask data that is
        # outside the bounds of our dataset.

        # Convert the image corner coordinates to WGS84
        trgt_srs = CRS.from_string("EPSG:4326")
        src_srs = raster_data.crs
        transformed = [transform_coordinates(src_srs, trgt_srs, [i[0]], [i[1]])
                       for i in raster_data.shape.exterior.coords]
        reprojected_data_extent = sPolygon(transformed)
        clipped = self.intersection(reprojected_data_extent)

        # Polygon is completely outside the dataset, return whatever
        # would have been returned by get_data()
        if not bool(clipped):
            ul = raster_data.index(self.bounds[0], self.bounds[1])
            lr = raster_data.index(self.bounds[2], self.bounds[3])
            window = self.get_data_window(ul[0], ul[1], lr[0], lr[1])

            return raster_data.get_data(window=window, **kwargs)

        ul = raster_data.index(clipped.bounds[0], clipped.bounds[1])
        lr = raster_data.index(clipped.bounds[2], clipped.bounds[3])
        window = self.get_data_window(ul[0], ul[1], lr[0], lr[1])

        data = raster_data.get_data(window=window, **kwargs)

        # out_shape must be determined from data's shape,  get_data
        # may have returned a bounding box of data that is smaller than
        # the implicit shape of the window we passed.  e.g. if the window
        # is partially outside the extent of the raster data. Note that
        # we index with negative numbers here because we may or may not
        # have a time dimension.
        num_bands = len(raster_data.band_indexes)

        if num_bands > 1:
            out_shape = data.shape[-3], data.shape[-2]
        else:
            out_shape = data.shape[-2], data.shape[-1]

        coordinates = []
        for lat, lon in clipped.exterior.coords:
            x, y = raster_data.index(lat, lon)
            coordinates.append((y - window[0][1], x - window[0][0]))

        # Mask the final polygon
        mask = rasterize(
            [({'type': 'Polygon',
               'coordinates': [coordinates]}, 0)],
            out_shape=out_shape, fill=1, all_touched=True, dtype=np.uint8)

        # If we have more than one band,  expand the mask so it includes
        # A "channel" dimension (e.g.  shape is now (lat, lon, channel))
        if num_bands > 1:
            mask = mask[..., np.newaxis] * np.ones(num_bands)

        # Finally broadcast mask to data because data may be from a
        # Raster data collection and include a time component
        # (e.g.  shape could be (time, lat, lon),  or even
        #  (time, lat, lon, channels))
        _, mask = np.broadcast_arrays(data, mask)
        data[mask.astype(bool)] = raster_data.nodata

        return np.ma.masked_equal(data, raster_data.nodata)