How to use the shapely.ops.unary_union function in shapely

To help you get started, we’ve selected a few shapely examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github opendatacube / datacube-core / utils / USGS_precollection_oldscripts / usgs_ls_ard_prepare.py View on Github external
# ensure formats match
        with rasterio.open(str(fname), 'r') as ds:
            transform = ds.transform
            img = ds.read(1)

            if mask_value is not None:
                new_mask = img & mask_value == mask_value
            else:
                new_mask = img != ds.nodata
            if mask is None:
                mask = new_mask
            else:
                mask |= new_mask

    shapes = rasterio.features.shapes(mask.astype('uint8'), mask=mask)
    shape = shapely.ops.unary_union([shapely.geometry.shape(shape) for shape, val in shapes if val == 1])

    # convex hull
    geom = shape.convex_hull

    # buffer by 1 pixel
    geom = geom.buffer(1, join_style=3, cap_style=3)

    # simplify with 1 pixel radius
    geom = geom.simplify(1)

    # intersect with image bounding box
    geom = geom.intersection(shapely.geometry.box(0, 0, mask.shape[1], mask.shape[0]))

    # transform from pixel space into CRS space
    geom = shapely.affinity.affine_transform(geom, (transform.a, transform.b, transform.d,
                                                    transform.e, transform.xoff, transform.yoff))
github c3nav / c3nav / src / c3nav / mapdata / render / data.py View on Github external
# keep track which areas are affected by access restrictions
        access_restriction_affected = {}

        # keep track wich spaces to hide
        restricted_spaces_indoors = {}
        restricted_spaces_outdoors = {}

        # go through spaces and their areas for access control, ground colors, height areas and obstacles
        colors = {}
        obstacles = {}
        heightareas = {}
        for space in level.spaces.all():
            access_restriction = space.access_restriction_id
            if access_restriction is not None:
                access_restriction_affected.setdefault(access_restriction, []).append(space.geometry)
                buffered = space.geometry.buffer(0.01).union(unary_union(
                    tuple(door.geometry for door in level.doors.all() if door.geometry.intersects(space.geometry))
                ).difference(walkable_spaces_geom))

                intersects = buildings_geom_prep.intersects(buffered)
                if intersects:
                    restricted_spaces_indoors.setdefault(access_restriction, []).append(
                        buffered.intersection(buildings_geom)
                    )
                if not intersects or not buildings_geom_prep.contains(buffered):
                    restricted_spaces_outdoors.setdefault(access_restriction, []).append(
                        buffered.difference(buildings_geom)
                    )

            colors.setdefault(space.get_color(), {}).setdefault(access_restriction, []).append(space.geometry)

            for area in space.areas.all():
github microsoft / qmt / qmt / geometry / geo_2d_data.py View on Github external
def compute_bb(self) -> List[float]:
        """Compute the bounding box of all of the parts in the geometry.

        Returns
        -------
        List of [min_x, max_x, min_y, max_y].

        """
        all_shapes = list(self.parts.values())
        bbox_vertices = unary_union(all_shapes).envelope.exterior.coords.xy
        min_x = min(bbox_vertices[0])
        max_x = max(bbox_vertices[0])
        min_y = min(bbox_vertices[1])
        max_y = max(bbox_vertices[1])
        return [min_x, max_x, min_y, max_y]
github opendatacube / datacube-dataset-config / agdcv2-ingest / prepare_scripts / landsat_collection / usgs_ls_ard_prepare.py View on Github external
# ensure formats match
        with rasterio.open(str(fname), 'r') as ds:
            transform = ds.transform
            img = ds.read(1)

            if mask_value is not None:
                new_mask = img & mask_value == mask_value
            else:
                new_mask = img != ds.nodata
            if mask is None:
                mask = new_mask
            else:
                mask |= new_mask

    shapes = rasterio.features.shapes(mask.astype('uint8'), mask=mask)
    shape = shapely.ops.unary_union([shapely.geometry.shape(shape) for shape, val in shapes if val == 1])

    # convex hull
    geom = shape.convex_hull

    # buffer by 1 pixel
    geom = geom.buffer(1, join_style=3, cap_style=3)

    # simplify with 1 pixel radius
    geom = geom.simplify(1)

    # intersect with image bounding box
    geom = geom.intersection(shapely.geometry.box(0, 0, mask.shape[1], mask.shape[0]))

    # transform from pixel space into CRS space
    geom = shapely.affinity.affine_transform(geom, (transform.a, transform.b, transform.d, transform.e, transform.xoff,
                                                    transform.yoff))
github gboeing / osmnx / osmnx / core.py View on Github external
west, south, east, north = geometry.bounds
    x_num = math.ceil((east-west) / quadrat_width) + 1
    y_num = math.ceil((north-south) / quadrat_width) + 1
    x_points = np.linspace(west, east, num=max(x_num, min_num))
    y_points = np.linspace(south, north, num=max(y_num, min_num))

    # create a quadrat grid of lines at each of the evenly spaced points
    vertical_lines = [LineString([(x, y_points[0]), (x, y_points[-1])]) for x in x_points]
    horizont_lines = [LineString([(x_points[0], y), (x_points[-1], y)]) for y in y_points]
    lines = vertical_lines + horizont_lines

    # buffer each line to distance of the quadrat width divided by 1 billion,
    # take their union, then cut geometry into pieces by these quadrats
    buffer_size = quadrat_width * buffer_amount
    lines_buffered = [line.buffer(buffer_size) for line in lines]
    quadrats = unary_union(lines_buffered)
    multipoly = geometry.difference(quadrats)

    return multipoly
github nismod / digital_comms / scripts / fixed_cluster_input_files.py View on Github external
'type': "Feature",
            'geometry': mapping(exchange_multipolygon),
            'properties': {
                'id': exchange
            }
        })

    if merge:
        print('generate_exchange_area - Merge multipolygons into singlepolygons')
        # Merge MultiPolygons into single Polygon
        removed_islands = []
        for area in exchange_areas:

            # Avoid intersections
            geom = shape(area['geometry']).buffer(0)
            cascaded_geom = unary_union(geom)

            # Remove islands
            # Keep polygon with largest area
            # Add removed islands to a list so that they
            # can be merged in later
            if (isinstance(cascaded_geom, MultiPolygon)):
                for idx, p in enumerate(cascaded_geom):
                    if idx == 0:
                        geom = p
                    elif p.area > geom.area:
                        removed_islands.append(geom)
                        geom = p
                    else:
                        removed_islands.append(p)
            else:
                geom = cascaded_geom
github wez / clacker / tools / circuitlib / shape.py View on Github external
trrs_type = shape_config.get('trrs', None) if shape_config else None
    if trrs_type == 'basic':
        trrs_box = box(0, 0, 10, 11)
    elif trrs_type == 'left+right':
        trrs_box = box(0, 0, 15, 12)
    elif trrs_type is None:
        trrs = None
    else:
        raise Exception('handle trrs type %s' % trrs_type)

    if trrs_type is not None:
        trrs = find_space(overall_hull,
                                    unary_union([switch_holes, mcu]),
                                    trrs_box, padding=0)
        trrs_hull = trrs
        overall_hull = unary_union([overall_hull,
                                    trrs_hull.buffer(1,
                                                cap_style=CAP_STYLE.square,
                                                join_style=JOIN_STYLE.mitre)]).convex_hull


    rj45_type = shape_config.get('rj45', None) if shape_config else None
    if rj45_type == 'magjack':
        rj45_box = box(0, 0, 33, 23)
    elif rj45_type == 'basic':
        rj45_box = box(0, 0, 18, 18)
    elif rj45_type == 'left+right':
        rj45_box = box(0, 0, 18, 18)
    elif rj45_type is None:
        rj45 = None
    else:
        raise Exception('handle rj45 type %s' % rj45_type)
github opendatacube / datacube-dataset-config / ls_usgs_sr_l2.py View on Github external
# ensure formats match
        with rasterio.open(str(fname), 'r') as ds:
            transform = ds.transform
            img = ds.read(1)

            if mask_value is not None:
                new_mask = img & mask_value == mask_value
            else:
                new_mask = img != ds.nodata
            if mask is None:
                mask = new_mask
            else:
                mask |= new_mask

    shapes = rasterio.features.shapes(mask.astype('uint8'), mask=mask)
    shape = shapely.ops.unary_union([shapely.geometry.shape(shape) for shape, val in shapes if val == 1])

    # convex hull
    geom = shape.convex_hull

    # buffer by 1 pixel
    geom = geom.buffer(1, join_style=3, cap_style=3)

    # simplify with 1 pixel radius
    geom = geom.simplify(1)

    # intersect with image bounding box
    geom = geom.intersection(shapely.geometry.box(0, 0, mask.shape[1], mask.shape[0]))

    # transform from pixel space into CRS space
    geom = shapely.affinity.affine_transform(geom, (transform.a, transform.b, transform.d,
                                                    transform.e, transform.xoff, transform.yoff))
github sambler / myblendercontrib / blendercam / utils.py View on Github external
#	m.polygons[923].select
						id+=1
				if use_modifiers:
					bpy.data.meshes.remove(m)	
			#print(polys
			if totfaces<20000:
				p=sops.unary_union(polys)
			else:	
				print('computing in parts')
				bigshapes=[]
				i=1
				part=20000
				while i*part
github RobertBaruch / polychip / polychip / layers.py View on Github external
print("Merging overlapping sections. Before merge:")
        print("{:d} contacts".format(len(self.contact_paths)))
        print("{:d} diffs".format(len(diff_paths)))
        print("{:d} polys".format(len(poly_paths)))
        print("{:d} metals".format(len(metal_paths)))
        print("After merging:")
        # print(diff_paths['p_rect10018'])

        self.multicontact = coerce_multipoly(shapely.ops.unary_union(
            [p for p in self.contact_paths.values() if p is not None]))
        self.contact_array = list(self.multicontact.geoms)
        list.sort(self.contact_array, key = functools.cmp_to_key(InkscapeFile.poly_cmp))
        print("{:d} contacts".format(len(self.contact_array)))

        self.multidiff = coerce_multipoly(shapely.ops.unary_union(
            [p for p in diff_paths.values() if p is not None]))
        self.diff_array = list(self.multidiff.geoms)
        list.sort(self.diff_array, key = functools.cmp_to_key(InkscapeFile.poly_cmp))
        print("{:d} diffs".format(len(self.diff_array)))

        self.multipoly = coerce_multipoly(shapely.ops.unary_union(
            [p for p in poly_paths.values() if p is not None]))
        self.poly_array = list(self.multipoly.geoms)
        list.sort(self.poly_array, key = functools.cmp_to_key(InkscapeFile.poly_cmp))
        print("{:d} polys".format(len(self.poly_array)))

        self.multimetal = coerce_multipoly(shapely.ops.unary_union(
            [p for p in metal_paths.values() if p is not None]))
        self.metal_array = list(self.multimetal.geoms)
        list.sort(self.metal_array, key = functools.cmp_to_key(InkscapeFile.poly_cmp))
        print("{:d} metals".format(len(self.metal_array)))