How to use the shapely.ops.cascaded_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 rustychris / stompy / test / dev_waq_hydro_editor.py View on Github external
##

# Fabricate a really basic aggregation
from scipy.cluster import vq

pnts=model.grid.cells_centroid()

# make this deterministic
np.random.seed(37)

centroids,labels=vq.kmeans2(pnts,k=20,iter=5,minit='points')
permute=np.argsort(np.random.random(labels.max()+1))
# Make a shapefile out of that
polys=[]
for k,grp in utils.enumerate_groups(labels):
    grp_poly = ops.cascaded_union([model.grid.cell_polygon(i) for i in grp])
    assert grp_poly.type=='Polygon',"Hmm - add code to deal with multipolygons"
    polys.append(grp_poly)

agg_shp_fn="dwaq_aggregation.shp"
wkb2shp.wkb2shp(agg_shp_fn,polys,overwrite=True)
##

import matplotlib.pyplot as plt
plt.figure(1).clf()
ax=plt.gca()
model.grid.plot_cells(values=permute[labels],ax=ax)
ax.axis('equal')

for poly in polys:
    plot_wkb.plot_wkb(poly,ax=ax,fc='none',lw=3)
github Image-Py / imagepy / imagepy / core / roi / polygonroi.py View on Github external
def commit(self, buf, oper):     
        pgs = []
        if len(buf[0])==0:return False
        if buf[0][0]!=buf[0][-1]:
            buf[0].append(buf[0][0])
        if len(self.body)==0:
            self.body.append(buf)
            buf = [[],[]]
            self.update, self.infoupdate = True, True
            return True
        for i in self.body:
            pgs.extend(to_segment(i))
        unin = cascaded_union(pgs)
        cur = cascaded_union(list(to_segment(buf)))
        if oper=='+':rst = unin.union(cur)
        if oper=='-':rst = unin.difference(cur)
        self.body = parse_mpoly(rst)
        self.update, self.infoupdate = True, True
github Image-Py / imagepy / imagepy / core / roi / polygonroi.py View on Github external
def commit(self, buf, oper):     
        pgs = []
        if len(buf[0])==0:return False
        if buf[0][0]!=buf[0][-1]:
            buf[0].append(buf[0][0])
        if len(self.body)==0:
            self.body.append(buf)
            buf = [[],[]]
            self.update, self.infoupdate = True, True
            return True
        for i in self.body:
            pgs.extend(to_segment(i))
        unin = cascaded_union(pgs)
        cur = cascaded_union(list(to_segment(buf)))
        if oper=='+':rst = unin.union(cur)
        if oper=='-':rst = unin.difference(cur)
        self.body = parse_mpoly(rst)
        self.update, self.infoupdate = True, True
github zhoubear / open-paperless / mayan / apps / appearance / static / appearance / packages / gentelella-master / vendors / jqvmap / create / jqvmap.py View on Github external
def merge(self, config, data_source):
    new_geometries = []
    for rule in config['rules']:
      expression = data_source.parse_manager.parse( rule['where'] )
      geometries = filter(lambda g: expression(g.properties), data_source.geometries)
      geometries = map(lambda g: g.geom, geometries)
      new_geometries.append( Geometry(shapely.ops.cascaded_union( geometries ), rule['fields']) )
    data_source.fields = config['fields']
    data_source.geometries = new_geometries
github oemof / feedinlib / example / download_50Hz_data.py View on Github external
'Sachsen-Anhalt': 'DEE0',
        'Thüringen': 'DEG0',
        'Berlin': 'DE30'
    }
    file = '/home/birgit/rli-server/04_Projekte/163_Open_FRED/' \
           '03-Projektinhalte/AP7 Community/paper_data/' \
           'geometries/Landkreise/landkreise_dump.shp'

    landkreise_shape = gpd.read_file(file)
    districts_shape = landkreise_shape[
        landkreise_shape.nuts.str.contains(nuts_id[state])]

    for nut_id in districts_shape.nuts.unique():
        tmp_df = districts_shape[districts_shape.nuts == nut_id]
        if len(tmp_df) > 1:
            polyg = cascaded_union(
                districts_shape[districts_shape.nuts == nut_id].geometry)
            counter = 0
            for index, row in tmp_df.iterrows():
                if counter == 0:
                    districts_shape.loc[index, 'geometry'] = polyg
                else:
                    districts_shape.drop(index=[index], inplace=True)
                counter += 1

    if dump_shape:
        districts_shape.to_file('districts_{}.shp'.format(state))
    return districts_shape
github Denvi / FlatCAM / camlib.py View on Github external
def union(self):
        """
        Runs a cascaded union on the list of objects in
        solid_geometry.

        :return: None
        """
        self.solid_geometry = [cascaded_union(self.solid_geometry)]
github erdc / RAPIDpy / RAPIDpy / gis / taudem.py View on Github external
if len(feature_indices) == 1:
                # write feature to file
                feature = \
                    ogr_polygon_shapefile_lyr.GetFeature(feature_indices[0])
                new_feat.SetGeometry(feature.GetGeometryRef())
            else:
                # dissolve
                dissolve_poly_list = []
                for feature_index in feature_indices:
                    feature = \
                        ogr_polygon_shapefile_lyr.GetFeature(feature_index)
                    feat_geom = feature.GetGeometryRef()
                    dissolve_poly_list.append(
                        shapely_loads(feat_geom.ExportToWkb()))
                dissolve_polygon = cascaded_union(dissolve_poly_list)
                new_feat.SetGeometry(
                    ogr.CreateGeometryFromWkb(dissolve_polygon.wkb))
            dissolve_layer.CreateFeature(new_feat)
        # clean up
        shp_drv.DeleteDataSource(temp_polygon_file)
        log("Time to dissolve: {0}".format(datetime.utcnow() -
                                           time_start_dissolve))
        log("Total time to convert: {0}".format(datetime.utcnow() -
                                                time_start))
github CNES / swot-hydrology-toolbox / processing / src / cnes / common / lib / my_hull.py View on Github external
# 2 - Select triangles following it's shape
        # 2.1 - Compute CircumRatio for each triangle
        circum_r = [get_circum_ratio(in_coords[ia], in_coords[ib], in_coords[ic]) for ia, ib, ic in tri.vertices]
    
        # 2.2 - Compute mean alpha parameter for each triangle
        mean_alpha = [1.0 / np.mean([in_alpha[ia], in_alpha[ib], in_alpha[ic]]) for ia, ib, ic in tri.vertices]
    
        # 2.3 - Select triangles
        triangles_selected = np.where(np.array(circum_r) < mean_alpha)
    
        # 2.4 - Compute a list of shapely polygon correpsonding to selected triangles
        list_triangle = [geometry.Polygon([(in_coords[ia][0], in_coords[ia][1]), (in_coords[ib][0], in_coords[ib][1]), (in_coords[ic][0], in_coords[ic][1])]) for ia, ib, ic in tri.vertices[triangles_selected]]
    
        # 3 - Union of selected triangles
        triangle_union = cascaded_union(list_triangle)

        retour = triangle_union
        
    return retour
github mmccoo / kicad_mmccoo / utils / via_fill.py View on Github external
if (zone.GetLayerName() == "B.Cu"):
                bzonepolygons.append(polygon)
            else:
                tzonepolygons.append(polygon)

        netclass = net.GetNetClass()
        viadiameter = netclass.GetViaDiameter()

        obstacles = cascaded_union(mods + tracks).buffer(viadiameter/2,
                                                         cap_style=CAP_STYLE.flat,
                                                         join_style=JOIN_STYLE.mitre)
        #draw_poly(board, obstacles, layertable['Eco1.User'])


        # cascaded_union takes a list of polys and merges/unions them together
        overlaps = cascaded_union(bzonepolygons).intersection(cascaded_union(tzonepolygons)).buffer(-viadiameter/2)

        # unlike the other polys in this function, the boundary can have holes.
        boundspoly = MultiPolygon(LinesToPolyHoles(bounds)).buffer(-viadiameter/2)

        overlapsinbound = overlaps.intersection(cascaded_union(boundspoly))

        viaspots = list(overlapsinbound.difference(obstacles))
        #draw_poly(board, viaspots, layertable['Eco1.User'])


        # this gives list of polygons where vias can be placed.
        # I got some unexpected behavior from shrinking. there's a self intersecting poly
        # in there I think.
        # viaspots above used to be called diff
        #viaspots = diff.buffer(-viadiameter/2, join_style=JOIN_STYLE.mitre)
        #draw_poly(board, viaspots, layertable['Eco1.User'])
github oscarpilote / Ortho4XP / src / O4_Airport_Utils.py View on Github external
#seeds.append(numpy.array(pol.representative_point()))
        total+=1
    helipad_area=ops.cascaded_union(multipol)
    # helipads that are only encoded as nodes, they will be grown into hexagons
    for nodeid in (x for x in airport_layer.dicosmn if x in airport_layer.dicosmtags['n'] and 'aeroway' in airport_layer.dicosmtags['n'][x] and airport_layer.dicosmtags['n'][x]['aeroway']=='helipad'):
        center=numpy.round(numpy.array(airport_layer.dicosmn[nodeid])-numpy.array([tile.lon,tile.lat]),7)
        if geometry.Point(center).intersects(helipad_area) or geometry.Point(center).intersects(treated_area): 
            continue
        way=numpy.round(center+numpy.array([[cos(k*pi/3)*9*GEO.m_to_lon(tile.lat),sin(k*pi/3)*9*GEO.m_to_lat] for k in range(7)]),7)
        pol=geometry.Polygon(way)
        multipol.append(pol)
        #alti_way=numpy.ones((len(way),1))*numpy.mean(tile.dem.alt_vec(way))
        #vector_map.insert_way(numpy.hstack([way,alti_way]),'INTERP_ALT',check=True) 
        #seeds.append(center)
        total+=1
    helipad_area=VECT.ensure_MultiPolygon(VECT.cut_to_tile(ops.cascaded_union(multipol)))
    for pol in helipad_area:
        if (pol.is_empty) or (not pol.is_valid) or (not pol.area):
            continue
        way=numpy.array(pol.exterior.coords)
        alti_way=numpy.ones((len(way),1))*numpy.mean(tile.dem.alt_vec(way))
        vector_map.insert_way(numpy.hstack([way,alti_way]),'INTERP_ALT',check=True) 
        seeds.append(numpy.array(pol.representative_point()))
    if seeds:
        if 'INTERP_ALT' in vector_map.seeds:
            vector_map.seeds['INTERP_ALT']+=seeds
        else:
            vector_map.seeds['INTERP_ALT']=seeds  
    if total:
        UI.vprint(1,"   Flattened", total,"helipads.")
####################################################################################################