• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python ops.unary_union函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中shapely.ops.unary_union函数的典型用法代码示例。如果您正苦于以下问题:Python unary_union函数的具体用法?Python unary_union怎么用?Python unary_union使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了unary_union函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: dissolve_df

def dissolve_df(in_df, dissolve_attribute=None):

    if dissolve_attribute is not None:
        print("dissolving DataFrame on {}".format(dissolve_attribute))
        # unique attributes on which to make the dissolve


        dissolved_items = list(np.unique(in_df[dissolve_attribute]))

        # go through unique attributes, combine the geometries, and populate new DataFrame
        df_out = pd.DataFrame()
        length = len(dissolved_items)
        knt = 0
        for item in dissolved_items:
            df_item = in_df[in_df[dissolve_attribute] == item]
            geometries = list(df_item.geometry)
            dissolved = unary_union(geometries)
            dict = {dissolve_attribute: item, 'geometry': dissolved}
            df_out = df_out.append(dict, ignore_index=True)
            knt +=1
            print('\r{:d}%'.format(100*knt/length))
    else:
        dissolved = unary_union(in_df.geometry.values)
        df_out = pd.DataFrame([{'geometry': dissolved}])
    return df_out
开发者ID:aleaf,项目名称:GIS_utils,代码行数:25,代码来源:GISops.py


示例2: createUnaryUnion

	def createUnaryUnion(self, allAreas):
		''' Given a set of areas, this method constructs a unary union for them '''
		try:
			# Construct a unary_union assume that there are no errors in
			# geometry.
			allDsgnPlygons = unary_union(allAreas)
		except Exception as e1:
			# If there are errors while consutrcuting the union, examine the
			# geometries further to seperate to just valid polygons. To avoid this error, 
			# ensure that the evaluation features are topologically correct, usually use a 
			# Geometry checker in GIS tools. 
			s1All = []
			try:
			    s1Polygons = MultiPolygon([x for x in allAreas if (
			        x.geom_type == 'Polygon' or x.geom_type == 'MultiPolygon') and x.is_valid])
			    if s1Polygons:
			        s1All.append(s1Polygons)
			except Exception as e:
			    print('Error in CreateUnaryUnion Polygon: %s' % e)
			else:
				if s1All:
					allDsgnPlygons = unary_union(s1All)
				else:
					allDsgnPlygons = ''

		return allDsgnPlygons
开发者ID:hrishiballal,项目名称:GDHLanduseAllocationModel,代码行数:26,代码来源:GDHAllocationModel.py


示例3: test_suite

def test_suite():
    try:
        patches = [Point((0, 0)).buffer(0.05)]
        unary_union(patches)
    except KeyError:
        return lambda x: None
    return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
开发者ID:31415us,项目名称:trajectory,代码行数:7,代码来源:test_unary_union.py


示例4: test_unary_union_multi

 def test_unary_union_multi(self):
     # Test of multipart input based on comment by @schwehr at
     # https://github.com/Toblerity/Shapely/issues/47#issuecomment-21809308
     patches = MultiPolygon([Point(xy).buffer(0.05) for xy in self.coords])
     self.assertAlmostEqual(unary_union(patches).area,
                            0.71857254056)
     self.assertAlmostEqual(unary_union([patches, patches]).area,
                            0.71857254056)
开发者ID:Toblerity,项目名称:Shapely,代码行数:8,代码来源:test_union.py


示例5: move

    def move(self, displacement):
        sweep = aa_get_sweep(self.agent, displacement)
        
        if self.attached is not None:
            poly = self.poly[:self.attached] + self.poly[self.attached+1:]
            config_obstacle = unary_union(self.config_poly[:self.attached] + self.config_poly[self.attached+1:])
        else:
            poly = self.poly
            config_obstacle = self.config_objects
        
        self.intersect = unary_union(poly).intersection(sweep)
        self.config_intersect = config_obstacle.intersection(LineString([self.agent.exterior.coords[0],
                                                                               np.array(self.agent.exterior.coords[0]) + np.array(displacement)]))
        
#         print self.config_intersect
        
        if self.config_intersect.is_empty or self.config_intersect.geom_type == 'Point':
            self.intersect = None
            self.config_intersect = None
        else:
            if self.config_intersect.geom_type in ('GeometryCollection', 'MultiLineString'):
                points = np.vstack([ np.array(p.coords) for p in self.config_intersect if p.geom_type == 'LineString'])
            elif self.config_intersect.geom_type == 'LineString':
                points = np.array(self.config_intersect.coords)
            i = np.argmin(np.linalg.norm(points - np.array(self.agent.exterior.coords[0])[None,:], axis=1))
            point = points[i]
            displacement = point - np.array(self.agent.exterior.coords[0])
            
        if self.attached is not None:
            index = self.attached
            poly_intersect = unary_union(self.obs_config[index]).intersection(LineString([self.poly[index].exterior.coords[0],
                                                                               np.array(self.poly[index].exterior.coords[0]) + np.array(displacement)]))
        
#             print 'obs', poly_intersect
            if poly_intersect.is_empty or poly_intersect.geom_type == 'Point':
                pass
            else:
                if poly_intersect.geom_type in ('GeometryCollection', 'MultiLineString'):
                    points = np.vstack([ np.array(p.coords) for p in poly_intersect if p.geom_type == 'LineString'])
                elif poly_intersect.geom_type == 'LineString':
                    points = np.array(poly_intersect.coords)
                i = np.argmin(np.linalg.norm(points - np.array(self.poly[index].exterior.coords[0])[None,:], axis=1))
                point = points[i]
                obs_pos = point
                displacement = point - np.array(self.poly[index].exterior.coords[0])
            self.move_obs(index, displacement)
            
        self.agent = translate(self.agent, 
                       xoff = displacement[0], 
                       yoff = displacement[1])
        self.last_sweep = sweep
开发者ID:gehring,项目名称:rec-namo,代码行数:51,代码来源:recnamo.py


示例6: createPhotoFoursects

def createPhotoFoursects():
	"""Create foursects out of smaller section units for areas covered by
	the aerial flight define in the 'photo_qtr_sects' shapefile"""

	# the mapping must be reversed to be used as a tool to define groups
	reverse_mapping = {i:k for k,v in foursect_mapping.iteritems() for i in v}

	# union the photo quarter sections into a single geometry
	qtr_sect_geoms = []
	with fiona.open(photo_qtr_sects) as q_sects:
		for qs in q_sects: 
			qtr_sect_geoms.append(shape(qs['geometry']))

	unioned_qs = unary_union(qtr_sect_geoms)

	foursect_dict = {}
	with fiona.open(sections) as sects:
		meta_data = sects.meta.copy()

		for s in sects:
			geom = shape(s['geometry'])
			
			if geom.centroid.intersects(unioned_qs):
				# derive the foursect id of each section based it its section
				# id and the foursect mapping dictionary
				sect_id = s['properties']['SECTION']
				township = sect_id[:4]
				foursect = reverse_mapping[int(sect_id[4:])]

				foursect_id = '{0}-{1}'.format(township, foursect)
				if foursect_id not in foursect_dict:
					foursect_dict[foursect_id] = [geom]
				else:
					foursect_dict[foursect_id].append(geom)
				
	# modify properties such that only the field 'foursect' exists
	new_properties = [('foursect', 'str')]
	meta_data['schema']['properties'] = new_properties

	with fiona.open(foursects, 'w', **meta_data) as f_sects:
		for fid, geoms in foursect_dict.iteritems():
			# not totally clear on why 'mapping' needs to be used below, but it
			# seems that unary union only returns a representation and mapping
			# in turn produces a writeable object
			fs_feat = {
			 	'geometry': mapping(unary_union(geoms)),
			 	'properties': {'foursect': fid}}
			
			f_sects.write(fs_feat)
开发者ID:grant-humphries,项目名称:aerials,代码行数:49,代码来源:create_photo_foursects.py


示例7: _compute_limits

    def _compute_limits(self, region_id=None):
        """WARNING: probably not yet completely implemented.

        Parameters
        ----------
        region_id: integer or None (default)
            the region id information.

        Returns
        -------
        limits: array_like
            the limits information.

        """
        if region_id is None:
            polygons = tesselation(self.regionlocs)
            whole = ops.unary_union(polygons)
            limits = np.array(whole.bounds).reshape((2, 2)).T
        else:
            polygons = tesselation(self.regionlocs)
            i_r = match_regions(polygons, self.regionlocs)
            regionsid = self.regions_id[i_r]
            p = polygons[np.where(regionsid == region_id)[0]]
            limits = np.array(p.bounds).reshape((2, 2)).T
        return limits
开发者ID:tgquintela,项目名称:pySpatialTools,代码行数:25,代码来源:bisectordiscretization.py


示例8: smooth_layer

def smooth_layer(record_ls, buf_val,
                 scale_km_to_degrees=0.009, delta_km=-0.5,     ### STATE
                 cfg=None):
    """Buffer out, dissolve and buffer back
    *Mutation*

    Args:
        record_ls: <list> A list of fiona records (from fiona collection)
        buf_val: <float> The value to buffer out each polygon, units of km
        scale_km_to_degrees <float>: Conversion based on *some* latitude
        delta_km <float>: Diference between buffer in and buffer out values,
            A -ve delta indicates the buffer_in is maller than the buffer_out

    Returns:
        <coll of shapely Polygons>
    """
    assert isinstance(buf_val, (float, int))
    b_out = buf_val * scale_km_to_degrees    ### STATE
    b_in = -(b_out + delta_km * scale_km_to_degrees)
    vert_ls = [ r['geometry']['coordinates'][0] for r in record_ls ]
    # Transform to shapely Polygons and guards empty polygons
    polygons = ( Polygon(v) for v in vert_ls if len(v) > 3 )
    dilated = ( p.buffer(b_out) for p in polygons if p.is_valid )
    dissolved = unary_union(list(dilated))
    eroded = dissolved.buffer(b_in)
    if isinstance(eroded, Polygon):
        eroded = MultiPolygon([eroded])
    logging.debug("Leaving func:smooth_layer")
    return eroded
开发者ID:gjcoombes,项目名称:torres,代码行数:29,代码来源:arc_smooth.py


示例9: add_polis

 def add_polis(self, additional_polis, union=True):
     if union:
         newpolis = unary_union(self.POLIS+additional_polis)
         newpolis = list(flattenMultipoly(newpolis))
     else: 
         newpolis = self.POLIS + additional_polis
     self.POLIS = newpolis#list(np.hstack(newpolis))
开发者ID:hambi-hemts,项目名称:ShapelyChipDesigns,代码行数:7,代码来源:brandnew_structure.py


示例10: get_extents_from_huc

def get_extents_from_huc(huc_data_shp=None,extents_output_shp=None,extents_huc_list=None):
    '''Extracts a user-specified HUC or list of HUCs from the national dataset and writes it
    to a shapefile. 'huc_data_shp'=shapefile that includes the huc polygons
    that will be extracted.'''
       
    extents_huc_scale = len(extents_huc_list[0])
    huc_field = 'HUC' + str(extents_huc_scale)
    
    with fiona.open(huc_data_shp) as vin:
        schema = vin.schema
        crs = vin.crs
        driver = vin.driver        
    
    # Reduce the extract schema to only the huc id field    
    schema['properties'] = {huc_field:'str'}
    
    # Now write the model domain shapefile     
    with fiona.open(huc_data_shp) as vect_in:
        polygon_list = []        
        for feature in vect_in:
            if (feature['properties'][huc_field] in extents_huc_list): 
                polygon_list.append(shape(feature['geometry']))
                merged = unary_union(polygon_list)

    with fiona.open(extents_output_shp,'w',driver=driver,crs=crs,schema=schema) as extract_out:
        extract_out.write({'geometry': mapping(merged),'properties':{huc_field:'Merged'}})
    
    return
开发者ID:giltis,项目名称:PyModflow,代码行数:28,代码来源:gis_tools.py


示例11: create_t6_deserts

def create_t6_deserts(desert_geom, b_box, mask_metadata):
    """"""

    geom_list = list()
    with fiona.open(t6_block_groups) as block_groups:
        t6_metadata = block_groups.meta.copy()

        with fiona.open(t6_desert_feats, 'w', **t6_metadata) as t6_deserts:
            for bg in block_groups:
                geom = shape(bg['geometry'])
                props = bg['properties']

                # 'neither' is misspelled in dataset so (sic)
                if props['min_pov'] != 'niether' and \
                        geom.intersects(desert_geom):
                    geom_list.append(geom)

                    new_geom = geom.intersection(desert_geom)
                    bg['geometry'] = mapping(new_geom)
                    t6_deserts.write(bg)

    t6_geom = unary_union(geom_list)
    t6_desert_geom = t6_geom.intersection(desert_geom)
    t6_mask_geom = b_box.difference(t6_desert_geom)

    with fiona.open(t6_desert_mask, 'w', **mask_metadata) as t6_mask:
        feat = {
            'geometry': mapping(t6_mask_geom),
            'properties': {
                'id': 1
            }
        }
        t6_mask.write(feat)
开发者ID:grant-humphries,项目名称:gis-scripts,代码行数:33,代码来源:create_vendor_desert_layer.py


示例12: test_1

 def test_1(self):
     # Instead of random points, use deterministic, pseudo-random Halton
     # sequences for repeatability sake.
     patches = [Point(xy).buffer(0.05) for xy in self.coords]
     u = unary_union(patches)
     self.failUnlessEqual(u.geom_type, 'MultiPolygon')
     self.failUnlessAlmostEqual(u.area, 0.71857254056)
开发者ID:antoinepairet,项目名称:Shapely,代码行数:7,代码来源:test_unary_union.py


示例13: test_unary_union

    def test_unary_union(self):
        p1 = self.t1
        p2 = Polygon([(2, 0), (3, 0), (3, 1)])
        expected = unary_union([p1, p2])
        g = GeoSeries([p1, p2])

        self._test_unary_topological('unary_union', expected, g)
开发者ID:sjsrey,项目名称:geopandas,代码行数:7,代码来源:test_geom_methods.py


示例14: createCenterline

	def createCenterline(self):
		"""
		Calculates the centerline of a polygon.

		Densifies the border of a polygon which is then represented by a Numpy
		array of points necessary for creating the Voronoi diagram. Once the
		diagram is created, the ridges located within the polygon are
		joined and returned.

		Returns:
			a union of lines that are located within the polygon.
		"""

		minx = int(min(self.inputGEOM.envelope.exterior.xy[0]))
		miny = int(min(self.inputGEOM.envelope.exterior.xy[1]))

		border = np.array(self.densifyBorder(self.inputGEOM, minx, miny))

		vor = Voronoi(border)
		vertex = vor.vertices

		lst_lines = []
		for j, ridge in enumerate(vor.ridge_vertices):
			if -1 not in ridge:
				line = LineString([\
					(vertex[ridge[0]][0] + minx, vertex[ridge[0]][1] + miny), \
					(vertex[ridge[1]][0] + minx, vertex[ridge[1]][1] + miny)])

				if line.within(self.inputGEOM) and len(line.coords[0]) > 1:
					lst_lines.append(line)

		return unary_union(lst_lines)
开发者ID:mmiler,项目名称:polygon-centerline,代码行数:32,代码来源:centerline.py


示例15: get_intersections

def get_intersections(roads):
    """Calculates the intersection points of all roads
    :param roads: List of shapely geometries representing road segments
    """
    intersections = []
    for road1, road2 in itertools.combinations(roads, 2):
        if road1.intersects(road2):
            intersection = road1.intersection(road2)
            if 'Point' == intersection.type:
                intersections.append(intersection)
            elif 'MultiPoint' == intersection.type:
                intersections.extend([pt for pt in intersection])
            elif 'MultiLineString' == intersection.type:
                multiLine = [line for line in intersection]
                first_coords = multiLine[0].coords[0]
                last_coords = multiLine[len(multiLine)-1].coords[1]
                intersections.append(Point(first_coords[0], first_coords[1]))
                intersections.append(Point(last_coords[0], last_coords[1]))
            elif 'GeometryCollection' == intersection.type:
                intersections.extend(get_intersections(intersection))

    # The unary_union removes duplicate points
    unioned = unary_union(intersections)

    # Ensure the result is a MultiPoint, since calling functions expect an iterable
    if 'Point' == unioned.type:
        unioned = MultiPoint([unioned])

    return unioned
开发者ID:kshepard,项目名称:high-risk-traffic,代码行数:29,代码来源:generate_training_input.py


示例16: generate_deserts_feature

def generate_deserts_feature(stops, desert_dist, t6=None):
    """"""

    b_box = get_pg_table_b_box('load.county')

    stops_buffs = []
    with fiona.open(stops) as dist_stops:
        metadata = dist_stops.meta.copy()

        for feat in dist_stops:
            geom = shape(feat['geometry'])
            fields = feat['properties']
            dist = fields['vend_dist']

            if dist > desert_dist:
                buff = geom.buffer(desert_dist)
                stops_buffs.append(buff)

    desert_area = unary_union(stops_buffs)

    vendor_buffs = []
    with fiona.open(rc_vendors) as vendors:
        for feat in vendors:
            geom = shape(feat['geometry'])
            buff = geom.buffer(desert_dist)
            vendor_buffs.append(buff)

    vendor_area = unary_union(vendor_buffs)
    desert_trim = desert_area.difference(vendor_area)
    desert_mask = b_box.difference(desert_trim)

    schema = metadata['schema']
    schema['geometry'] = desert_mask.geom_type
    schema['properties'] = {'id': 'int'}

    if t6:
        create_t6_deserts(desert_trim, b_box, metadata)
        return

    with fiona.open(desert_gaps, 'w', **metadata) as gaps_shp:
        feat = {
            'geometry': mapping(desert_mask),
            'properties': {
                'id': 1
            }
        }
        gaps_shp.write(feat)
开发者ID:grant-humphries,项目名称:gis-scripts,代码行数:47,代码来源:create_vendor_desert_layer.py


示例17: __init__

    def __init__(self, 
                 rectangles, 
                 state_range, 
                 agent_start = None,
                 agent_size = None):
        poly = []
        for rect in rectangles:
            poly.append(Polygon(rect))
            
        self.config_range = state_range
        limits = LinearRing([state_range[0], 
                            (state_range[1][0], state_range[0][1]),
                            state_range[1],
                            (state_range[0][0], state_range[1][1])])
        
        if agent_start is None:
            agent_start = np.array(self.DEFAULT_AGENT_START)
        else:
            agent_start = np.array(agent_start)
            
        if agent_size is None:
            self.agent_size = np.array(self.DEFAULT_AGENT_SIZE)   
        else:
            self.agent_size = np.array(agent_size)
        
        end_point = np.zeros(2) + self.agent_size
        self.agent = Polygon([agent_start,
                         (end_point[0], agent_start[1]),
                         end_point,
                         (agent_start[0], end_point[1])])
        
        self.poly = poly
        self.config_poly = compute_config_all_obst(self.agent, poly)
        self.config_objects = unary_union(self.config_poly)
        
        self.obs_config = { i : compute_config_all_obst(self.poly[i], self.poly[:i] + self.poly[i+1:]) for i in range(len(self.poly))}
#         self.union_obs_config = { k : unary_union(v) for k, v in self.obs_config.iteritems()}
        
        
        self.objects = unary_union(poly)
        self.last_sweep = None
        self.intersect = None
        self.config_intersect = None
        self.agent = translate(self.agent, 
                                   xoff = agent_start[0], 
                                   yoff = agent_start[1])
        self.attached = None
开发者ID:gehring,项目名称:rec-namo,代码行数:47,代码来源:recnamo.py


示例18: move_obs

 def move_obs(self, index, displacement):
     for i in range(0,index):
         self.obs_config[i][index-1] = translate(self.obs_config[i][index-1], 
                                                    xoff = displacement[0], 
                                                    yoff = displacement[1])
     for i in range(index+1, len(self.poly)):
         self.obs_config[i][index] = translate(self.obs_config[i][index], 
                                                xoff = displacement[0], 
                                                yoff = displacement[1])
     self.config_poly[index] = translate(self.config_poly[index], 
                                        xoff = displacement[0], 
                                        yoff = displacement[1])
     self.config_objects = unary_union(self.config_poly)
     self.poly[index] = translate(self.poly[index], 
                                    xoff = displacement[0], 
                                    yoff = displacement[1])
     self.objects = unary_union(self.poly)
开发者ID:gehring,项目名称:rec-namo,代码行数:17,代码来源:recnamo.py


示例19: test_1

 def test_1(self):
     # Instead of random points, use deterministic, pseudo-random Halton
     # sequences for repeatability sake.
     coords = zip(list(islice(halton(5), 20, 120)), list(islice(halton(7), 20, 120)))
     patches = [Point(xy).buffer(0.05) for xy in coords]
     u = unary_union(patches)
     self.failUnlessEqual(u.geom_type, "MultiPolygon")
     self.failUnlessAlmostEqual(u.area, 0.71857254056)
开发者ID:fredj,项目名称:shapely,代码行数:8,代码来源:test_unary_union.py


示例20: from_system

    def from_system(cls, system):
        """Convert a `System` instance to a `Polygons` instance.

        Parameters
        ----------
        system : System

        Returns
        -------
        Polygons
        """
        obj = cls()
        for e in system:
            if not hasattr(e, "paths"):
                continue
            # assert isinstance(e, PolygonPixelElectrode), (e, e.name)
            exts, ints = [], []
            for pi in e.paths:
                # shapely ignores f-contiguous arrays so copy
                # https://github.com/sgillies/shapely/issues/26
                ei = area_centroid(pi)[0]
                pi = geometry.LinearRing(pi.copy("C"))
                if ei < 0:
                    ints.append((abs(ei), pi))
                elif ei > 0:
                    exts.append((abs(ei), pi))
            if not exts:
                continue
            ints.sort(key=operator.itemgetter(0))
            exts.sort(key=operator.itemgetter(0))
            # the following needs to be complicated to cover
            # onion-like "ext in int in ext" cases.
            groups = []
            done = set()
            for exta, exterior in exts:
                ep = geometry.Polygon(exterior)
                gint = []
                for i, (inta, interior) in enumerate(ints):
                    if i in done:
                        continue
                    if inta >= exta:
                        break
                    if ep.contains(interior):
                        gint.append(interior)
                        done.add(i)
                pi = geometry.Polygon(exterior, gint)
                if pi.is_valid and pi.area > 0:
                    groups.append(pi)
                else:
                    logger.warn("polygon %s failed %s/%s", e.name, pi.is_valid,
                                pi.area)
            # remaining interiors must be top level or "free"
            #assert not ints, ints
            #mp = geometry.MultiPolygon(groups)
            #mp = mp.union(geometry.Point())
            mp = ops.unary_union(groups)
            obj.append((e.name, mp))
        return obj
开发者ID:cntnly,项目名称:electrode,代码行数:58,代码来源:polygons.py



注:本文中的shapely.ops.unary_union函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python prepared.prep函数代码示例发布时间:2022-05-27
下一篇:
Python ops.transform函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap