Exemple #1
0
    def _get_level_geometries(level):
        buildings = level.buildings.all()
        buildings_geom = cascaded_union([building.geometry for building in buildings])
        spaces = {space.pk: space for space in level.spaces.all()}
        holes_geom = []
        for space in spaces.values():
            if space.outside:
                space.geometry = space.geometry.difference(buildings_geom)
            columns = [column.geometry for column in space.columns.all()]
            if columns:
                columns_geom = cascaded_union([column.geometry for column in space.columns.all()])
                space.geometry = space.geometry.difference(columns_geom)
            holes = [hole.geometry for hole in space.holes.all()]
            if holes:
                space_holes_geom = cascaded_union(holes)
                holes_geom.append(space_holes_geom.intersection(space.geometry))
                space.geometry = space.geometry.difference(space_holes_geom)

        for building in buildings:
            building.original_geometry = building.geometry

        if holes_geom:
            holes_geom = cascaded_union(holes_geom)
            holes_geom_prep = prepared.prep(holes_geom)
            for obj in buildings:
                if holes_geom_prep.intersects(obj.geometry):
                    obj.geometry = obj.geometry.difference(holes_geom)

        results = []
        results.extend(buildings)
        for door in level.doors.all():
            results.append(door)

        results.extend(spaces.values())
        return results
Exemple #2
0
    def parse_query(self, query):
        super(MapPlotter, self).parse_query(query)

        self.projection = query.get('projection')

        self.area = query.get('area')

        names = []
        centroids = []
        all_rings = []
        data = None
        for idx, a in enumerate(self.area):
            if isinstance(a, basestring):
                a = a.encode("utf-8")
                sp = a.split('/', 1)
                if data is None:
                    data = list_areas(sp[0], simplify=False)

                b = [x for x in data if x.get('key') == a]
                a = b[0]
                self.area[idx] = a
            else:
                p = np.array(a['polygons'])
                p[:, :, 1] = pyresample.utils.wrap_longitudes(p[:, :, 1])
                a['polygons'] = p.tolist()
                del p

            rings = [LinearRing(po) for po in a['polygons']]
            if len(rings) > 1:
                u = cascaded_union(rings)
            else:
                u = rings[0]

            all_rings.append(u)
            if a.get('name'):
                names.append(a.get('name'))
                centroids.append(u.centroid)

        nc = sorted(zip(names, centroids))
        self.names = [n for (n, c) in nc]
        self.centroids = [c for (n, c) in nc]
        data = None

        if len(all_rings) > 1:
            combined = cascaded_union(all_rings)
        else:
            combined = all_rings[0]

        self.combined_area = combined
        combined = combined.envelope

        self.centroid = list(combined.centroid.coords)[0]
        self.bounds = combined.bounds

        self.show_bathymetry = bool(query.get('bathymetry'))
        self.show_area = bool(query.get('showarea'))

        self.quiver = query.get('quiver')

        self.contour = query.get('contour')
def processpoly(polylist):
    print u"Полигоны"
    for p in polylist:
        pol = Polygon(p)
        print pol
    print u"Объединение"
    print cascaded_union([Polygon(p) for p in polylist])
    return 1
def fig_contains(fig1, fig2) -> float:
    pgz1 = polygonize_figure(fig1)
    pgz2 = polygonize_figure(fig2)
    if len(pgz1) > 0 and len(pgz2) > 0:
        plist1 = [Polygon(p) for p in pgz1]
        plist2 = [Polygon(p) for p in pgz2]
        u_polygon1 = cascaded_union(plist1)
        u_polygon2 = cascaded_union(plist2)
        if u_polygon1.contains(u_polygon2):
            return True
    return False
def fig_overlap_area(fig1, fig2) -> float:
    pgzfg1 = polygonize_figure(fig1)
    pgzfg2 = polygonize_figure(fig2)
    if len(pgzfg1) > 0 and len(pgzfg2) > 0:
        plist1 = [Polygon(p) for p in pgzfg1]
        plist2 = [Polygon(p) for p in pgzfg2]
        u_polygon1 = cascaded_union(plist1)
        u_polygon2 = cascaded_union(plist2)
        area = u_polygon1.intersection(u_polygon2).area
    else:
        area = 0.0
    return area
Exemple #6
0
def handle_special_countries(c):
    c['Iceland'].patch = ops.cascaded_union([c['Iceland'].patch, c['England'].patch,
                                             c['Ireland'].patch]).convex_hull
    c['Madagascar'].patch = ops.cascaded_union([c['Madagascar'].patch,
                                             c['Mozambique'].patch]).convex_hull
    c['Madagascar'].__class__ = c['Iceland'].__class__
    c['Malaysia'].patch = c['Malaysia'].patch.buffer(1)
    c['Indonesia'].patch = c['Indonesia'].patch.buffer(1)
    c['Indonesia'].__class__ = c['Iceland'].__class__
    c['Malaysia'].__class__ = c['Iceland'].__class__
    c['Hawaii'].continent = ''
    c['Falkland Is.'].continent = ''
def alpha_shape(points, alpha):
    """
    Compute the alpha shape (concave hull) of a set
    of points.
    @param points: Iterable container of points.
    @param alpha: alpha value to influence the
        gooeyness of the border. Smaller numbers
        don't fall inward as much as larger numbers.
        Too large, and you lose everything!
    """
    if len(points) < 4:
        # When you have a triangle, there is no sense
        # in computing an alpha shape.
        return geometry.MultiPoint(list(points)).convex_hull

    #coords = np.array([point.coords[0] for point in points])

    coords = np.array(points)

    print(coords)

    tri = Delaunay(coords)
    edges = set()
    edge_points = []
    # loop over triangles:
    # ia, ib, ic = indices of corner points of the
    # triangle
    for ia, ib, ic in tri.vertices:
        pa = coords[ia]
        pb = coords[ib]
        pc = coords[ic]
        # Lengths of sides of triangle
        a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
        b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
        c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
        # Semiperimeter of triangle
        s = (a + b + c)/2.0
        # Area of triangle by Heron's formula
        area = math.sqrt(s*(s-a)*(s-b)*(s-c))
        circum_r = a*b*c/(4.0*area)
        # Here's the radius filter.
        #print circum_r
        if circum_r < 1.0/alpha:
            add_edge(edges, edge_points, coords, ia, ib)
            add_edge(edges, edge_points, coords, ib, ic)
            add_edge(edges, edge_points, coords, ic, ia)
    m = geometry.MultiLineString(edge_points)
    triangles = list(polygonize(m))
    return (cascaded_union(triangles), edge_points)

    print (cascaded_union(triangles), edge_points)
Exemple #8
0
        def display(self, feature_name = None, *args):
            # allows function to be used by multiple processes, first option (when a feature_name is passed)
            # is for viewing data, second option is for viewing created geometries
            if feature_name:
                geom = self.datasets[self.current_dataset].features[feature_name][0]
                if geom.geom_type != ('Polygon' or 'MultiPolygon'):
                    self.dialog_text.set('This geometry is invalid. Please use a different dataset')
                    pass
                geom = cascaded_union(geom) #to dissolve multipolygons
                geom_bdry = geom.boundary
                minx, miny, maxx, maxy = self.bg.bounds
                w, h = maxx - minx, maxy - miny
                fig = plt.figure(1, figsize = (5, 5), dpi = 180, frameon = False)
                ax = fig.add_subplot(111)
                ax.set_xlim(minx,maxx)
                ax.set_ylim(miny,maxy)
                for poly in self.bg:
                    bg_patch = PolygonPatch(poly, fc = 'lightsage', ec = 'k', alpha = 1)
                    ax.add_patch(bg_patch)

                if geom.geom_type == 'MultiPolygon':
                    for poly in geom:
                        patch = PolygonPatch(poly, fc= 'teal', ec='navy', alpha = 0.5)
                        ax.add_patch(patch)
                else:
                    patch = PolygonPatch(geom, fc='teal', ec='navy', alpha = 0.5)
                    ax.add_patch(patch)
                plt.show()
            else:
                geom = args[0]
                name = args[1]
                geom = cascaded_union(geom) #to dissolve multipolygons
                minx, miny, maxx, maxy = self.bg.bounds
                w, h = maxx - minx, maxy - miny
                fig = plt.figure(1, figsize = (5, 5), dpi = 180, frameon = False)
                ax = fig.add_subplot(111)
                ax.set_xlim(minx,maxx)
                ax.set_ylim(miny,maxy)
                for poly in self.bg:
                    bg_patch = PolygonPatch(poly, fc = 'lightsage', ec = 'k', alpha = 1)
                    ax.add_patch(bg_patch)
                if geom.geom_type == 'MultiPolygon':
                    for poly in geom:
                        patch = PolygonPatch(poly, fc= 'teal', ec='navy', alpha = 0.5)
                        ax.add_patch(patch)
                else:
                    patch = PolygonPatch(geom, fc='teal', ec='navy', alpha = 0.5)
                    ax.add_patch(patch)
                plt.title(name)
                plt.show()
def ConvertPolygons2LatLong(PolygonDict, CRS):

    """
    Convert coordinates to latlong using pyproj
    https://gis.stackexchange.com/questions/127427/transforming-shapely-polygon-and-multipolygon-objects

    returns shapely Polygon/Multipolygon Dictionary

    MDH

    """

    # define the output coordinate system
    Output_CRS = Proj({'init': "epsg:4326"})

    NewPolygonDict = {}

    #loop through polygon dict and convert to latlong
    for Key, Poly in PolygonDict.iteritems():

        if Poly.geom_type == 'Polygon':
            # get x and y as arrays
            x,y = Poly.exterior.coords.xy
            lon,lat = transform(CRS, Output_CRS, x, y)
            Shape = Polygon(zip(lon,lat))

            #check for multipolygons
            if Key in NewPolygonDict:
                Polygons = [Shape, NewPolygonDict[Key]]
                Shape = cascaded_union(Polygons)

            #add converted polygon to new dictionary
            NewPolygonDict[Key] = Shape

        elif Poly.geom_type == 'MultiPolygon':
            for SinglePoly in Poly:
                # get x and y as arrays
                x,y = SinglePoly.exterior.coords.xy
                lon,lat = transform(CRS, Output_CRS, x, y)
                Shape = Polygon(zip(lon,lat))

                #check for multipolygons
                if Key in NewPolygonDict:
                    Polygons = [Shape, NewPolygonDict[Key]]
                    Shape = cascaded_union(Polygons)

                #add converted polygon to new dictionary
                NewPolygonDict[Key] = Shape

    return NewPolygonDict
Exemple #10
0
def test_split():
    print "Split donut by interior point"
    donut = sg.Point(0, 0).buffer(2.0).difference(sg.Point(0, 0).buffer(1.0))
    center = donut.centroid
    res = split_horiz_by_point(donut, center)
    print "Parts (should be 2): %s" % len(res)
    dif = cascaded_union(res).symmetric_difference(donut).area
    print "Difference: %s" % dif

    print "Split donut by exterior point"
    side = sg.Point(4,4)
    res = split_horiz_by_point(donut, side)
    print "Parts (should be 1): %s" % len(res)
    dif = cascaded_union(res).symmetric_difference(donut).area
    print "Difference: %s" % dif
Exemple #11
0
  def buffer(self, toBuffer, outFile, distance, dissolve):

    with fiona.open(toBuffer, 'r') as input:
      schema = input.schema
      crs = input.crs
      schema['geometry'] = 'Polygon'
      
      buf_features = []
      for f in input:   
        buf_features.append(( shape(f['geometry']).buffer(distance), f['properties'] ))
      
      if dissolve == True:
        buf_features = cascaded_union([geom for geom, prop in buf_features])
        schema = {'geometry':buf_features.geom_type, 'properties':{'fid':'int'}}
        buf_features = [(buf_features, {'fid':'1'})]
   

    #in windows compiled shapely library python crashes if str has 255 characters
    #works without this block in source compiled verions 
    #--------------------------------------------------
    for k, v in schema['properties'].items():
      if v[0:3] == 'str' and v[-3:] == '255':
        schema['properties'][k] = 'str:254'
    #--------------------------------------------------
   
    with fiona.open(outFile, 'w', 'ESRI Shapefile', crs=crs, schema=schema) as output:
      for geom, prop in buf_features: 
        output.write({'geometry': mapping(geom), 'properties':prop})
	def merge_polygon(self):
		if self.zone_segment:
			if len(self.lines) > 0:
				self.reduce_lines()
		merge = []
		for elmt in self.tmp_figs.elements:
			if elmt.active == 0:
				continue
			if elmt.element.is_empty:
				continue
			if elmt.element.geom_type == 'Polygon':
				merge.append(elmt.element)
			elif elmt.element.geom_type == 'MultiPolygon':
				for polygon in elmt.element:
					merge.append(polygon)
		tmp = cascaded_union(merge)
		if tmp.geom_type=='MultiPolygon':
			for poly in tmp:
				if poly.is_valid:
 					self.figs.add(self.Figs(poly))
				#else:
				#	print "Invalid"
				if poly.interiors:
					for inter in poly.interiors:
					 self.figs.add(self.Figs(Polygon(inter)))
		elif tmp.geom_type=='Polygon':
			self.figs.add(self.Figs(tmp))
			if tmp.interiors:
				for inter in tmp.interiors:
				 self.figs.add(self.Figs(Polygon(inter)))
Exemple #13
0
    def _proto_read(self, layer):
        """ Read features for the layer based on the self.request. """
        proto = self._get_protocol_for_layer(layer)
        if layer.public:
            return proto.read(self.request)
        user = self.request.user
        if user is None:
            raise HTTPForbidden()
        cls = proto.mapped_class
        geom_attr = proto.geom_attr
        ras = DBSession.query(RestrictionArea.area, RestrictionArea.area.ST_SRID())
        ras = ras.join(RestrictionArea.roles)
        ras = ras.join(RestrictionArea.layers)
        ras = ras.filter(Role.id == user.role.id)
        ras = ras.filter(Layer.id == layer.id)
        collect_ra = []
        use_srid = -1
        for ra, srid in ras.all():
            if ra is None:
                return proto.read(self.request)
            else:
                use_srid = srid
                collect_ra.append(to_shape(ra))
        if len(collect_ra) == 0:  # pragma: no cover
            raise HTTPForbidden()

        filter1_ = create_filter(self.request, cls, geom_attr)
        ra = cascaded_union(collect_ra)
        filter2_ = ga_func.ST_Contains(
            from_shape(ra, use_srid),
            getattr(cls, geom_attr)
        )
        filter_ = filter2_ if filter1_ is None else and_(filter1_, filter2_)

        return proto.read(self.request, filter=filter_)
Exemple #14
0
def isGalleryCovered(camerasState):
    circles_array=[]
    for (i, camera) in enumerate(camerasState):
        if(camerasState[i]):
            circles_array.append(Gallery.cameras[i].circle)
    circles_union=cascaded_union(circles_array)
    return (circles_union.intersection(Gallery.gallery_polygon)==Gallery.gallery_polygon)
Exemple #15
0
def do(star, stars, vertices):
	maxArea = 0	
	start_poly = onestar_to_poly(star, vertices)
	adjTupleSet = getStarAdj(star, stars)
	# Get all adjacent combination with polyno number of polygons
	for polyno in range(1,len(adjTupleSet)+1):
		print("combine with" + str(polyno) + "\n\n")
		combis = itertools.combinations(adjTupleSet,polyno)
		for combi in combis:
			print("new combination")
			poly = shapelyPolygon(start_poly)
			# vertices of this combination
			polyvert = star.copy()
			for p in combi:
				# pdb.set_trace()
				addPoly = shapelyPolygon(onestar_to_poly(p, vertices))
				poly = cascaded_union([poly, addPoly])
				for v in p:
					polyvert.append(v)
			# pdb.set_trace()
			polyvert = list(set(polyvert))
			polyvert.sort()
			print("Vertices", polyvert)
			polyvert = onestar_to_poly(polyvert, vertices)
			print("Area", poly.area)
			print("Star", starise.kernel(list(range(len(polyvert))), polyvert))

			print("\n")
Exemple #16
0
def alpha_shape(points, alpha):
    def add_edge(points, i, j):
        if (i, j) in edges or (j, i) in edges:
            return
        edges.add((i, j))
        edge_points.append((points[i], points[j]))
    tri = DelaunayTri(points)
    edges = set()
    edge_points = []
    for i1, i2, i3 in tri.vertices:
        x1, y1 = tri.points[i1]
        x2, y2 = tri.points[i2]
        x3, y3 = tri.points[i3]
        a = hypot(x1 - x2, y1 - y2)
        b = hypot(x2 - x3, y2 - y3)
        c = hypot(x3 - x1, y3 - y1)
        s = (a + b + c) / 2.0
        area = sqrt(s * (s - a) * (s - b) * (s - c))
        radius = a * b * c / (4 * area)
        if radius < 1.0 / alpha:
            add_edge(tri.points, i1, i2)
            add_edge(tri.points, i2, i3)
            add_edge(tri.points, i3, i1)
    shape = cascaded_union(list(polygonize(MultiLineString(edge_points))))
    return shape
 def dissolve (self, inFile, outFile):
     # create dictionary for storing the uniqueRefs
     uniqueRefs = {}
     with fiona.open(inFile, 'r', encoding='utf-8') as input:
         input_driver = input.driver
         input_crs = input.crs
         input_schema = {'geometry': 'MultiLineString','properties': {'ref'.encode("utf-8"): 'str:254'}}
         with fiona.open(outFile, 'w', driver=input_driver, crs=input_crs, schema=input_schema, encoding='utf-8') as output:
             for item in input:
                 # extract the key, if the 'ref' attribute is NOT called 'ref' 
                 # you can insert the different attribute name HERE (and only HERE).
                 key = item['properties']['ids_and_re']
                 geom = shape(item['geometry'])
                 # find all motorways within the New Zealand mainland
                 # and remove all letters per  
                 newZeaBox = [(17920614.01, -4033681.682),(20362002, -4054837.565),(20357771.35, -6073108.484),(17683668.157,-6068877.308)]
                 newZeaPoly = Polygon(newZeaBox)
                 if geom.within(newZeaPoly):
                     key = re.sub(r'\D',"", key)
                 if not geom.type.startswith('Multi'):
                     geom = [geom]
                 for g in geom:
                     if key in uniqueRefs:
                         uniqueRefs[key].append(g)
                     else:
                         uniqueRefs[key] = [g]
             for key in uniqueRefs:
                 # omit lines that have blank 'ref' tags
                 if key is not None and key != 'None':
                     dissolve_feat = cascaded_union(uniqueRefs[key])
                     output.write({'geometry':mapping(dissolve_feat), 'properties': {'ref': key}})
Exemple #18
0
def cascaded_union(shapes):
    o = []
    for shape in shapes:
        if not hasattr(shape,'__geo_interface__'): raise TypeError("%r does not appear to be a shape"%shape)
        o.append(geom.asShape(shape))
    res = shops.cascaded_union(o)
    return asShape(res)
Exemple #19
0
    def visit(self, ax, poly, poly_vor, c1, c2, x, y, splits):
        scatter(ax, x, y)
        polys = sum([h.polys for h in self._heap_visitors], [])
        candidates_union = cascaded_union(polys)
        points = {}
        for h in self._heap_visitors:
            for x, y in zip(h.x, h.y):
                points[(x, y)] = np.array((x, y))
        points = list(points.values()) # remove duplicates
        points.sort(key=lambda p: distance.euclidean(self._p, p))

        if self._mode == 'union':
            ax.plot(self._p[0], self._p[1], marker='x', zorder=99, c='red', ms=10, mew=5)
            draw_poly(ax, candidates_union, 'none', lw=2.0, hatch='x')
            
        elif self._mode == 'dist':
            ax.plot(self._p[0], self._p[1], marker='x', zorder=99, c='blue', ms=3, mew=1)
            for p in points:
                ax.plot([self._p[0], p[0]], [self._p[1], p[1]], 'r-')
            draw_poly(ax, candidates_union, 'none', lw=2.0)

        elif self._mode == 'top':
            ax.plot(self._p[0], self._p[1], marker='x', zorder=99, c='blue', ms=3, mew=1)
            for p in points[:self._nns]:
                ax.plot([self._p[0], p[0]], [self._p[1], p[1]], 'r-')

            c = plt.Circle(self._p, distance.euclidean(self._p, points[self._nns-1]), edgecolor='red', zorder=99, lw=1.0, fill=False, linestyle='dashed')
            ax.add_artist(c)
            draw_poly(ax, candidates_union, 'none', lw=2.0)
Exemple #20
0
def run_contour_paths(pseudo, epsilon, evals):
    # get paths
    paths = pseudo.contour_paths(epsilon)

    # check if pseudospectrum is correct by matching the parts of it
    import shapely.geometry as geom
    from shapely.ops import cascaded_union
    # create circles
    circles = [geom.Point(numpy.real(lamda), numpy.imag(lamda))
               .buffer(epsilon) for lamda in evals]
    exact_pseudo = cascaded_union(circles)
    exact_paths = pseudopy.utils.get_paths(exact_pseudo)

    N = len(paths)
    assert(N == len(exact_paths))

    # create polygons
    polys = [geom.Polygon([(numpy.real(z), numpy.imag(z))
                           for z in path.vertices])
             for path in paths]
    exact_polys = [geom.Polygon([(numpy.real(z), numpy.imag(z))
                                 for z in path.vertices])
                   for path in exact_paths]

    # match elements by measuring intersections
    M = numpy.zeros((N, N))
    for (i, j) in product(range(N), range(N)):
        M[i, j] = exact_polys[i].symmetric_difference(polys[j]).area
    for i in range(N):
        assert(numpy.min(M[i, :]) < 0.1*epsilon)
def Merger_Aggregate(path_in, path_out):
    from shapely.ops import cascaded_union
    from shapely.geometry import Point, MultiPolygon, shape, mapping
    from fiona import collection
    import sys
    import shutil
    from time import sleep
    
    with collection(path_in, "r") as input:
        schema = input.schema.copy()
        print "Check point Alpha"
        with collection(path_out, "w", "ESRI Shapefile", schema) as output:
            bl = []
            print "Check point Brovo"
            total = len(input)
            count = 0;
            for f in input:    
                bl.append(shape(f['geometry']))
                ml = cascaded_union(bl)                
                f['geometry'] = mapping(ml)
                f['properties']['Shape_area'] = ml.area
                output.write(f)
                count +=1
                sys.stdout.write("\r" + "[%-75s]" % ('='*((count*75)/total)))
                sys.stdout.write(str((count*100)/total) + "%")
                sys.stdout.flush()
                sleep(0.25)
    print "Done!!!"
Exemple #22
0
def polygon_union(polygons):
	"""Takes the union of shapely polygons attempting to avoid floating point issues"""
	if len(polygons) == 1:
		return polygons[0]
		
	U = cascaded_union([_scale_polygon(poly,'up') for poly in polygons])
	return _scale_polygon(U,'down')
Exemple #23
0
def pack(items):
    shifted = [ ]
    for i, item in enumerate(items):
        shifted.append(
            affinity.translate(item, (i%6)*15, (i//6)*15)
            )
    return ops.cascaded_union(shifted)
def createInputShapefileMethodB(input_shapefile):
    
    input_shapefile_fullpath = os.path.join(sys.path[0], input_shapefile + ".shp")
    
    if os.path.exists(input_shapefile_fullpath):
        return input_shapefile_fullpath
    
    
    iso3 = 'UGA'
    countries = { 'TZA': { "name": 'tanzania', "srid": '32736' }, 'BGD': { "srid": '32645', "name": 'bangladesh' }, 'UGA': { "srid": '32635', "name": 'uganda' }, 'NGA': { "name": 'nigeria', "srid": '32632' }, 'KEN': { "name": 'kenya', "srid": '32636' } };
    
    points = executeSQL("SELECT ST_ASTEXT(ST_TRANSFORM(geom, "+countries[iso3]['srid']+")) FROM public."+countries[iso3]['name']+"_cicos", returnRows=True)    
    points = [r[0].replace("POINT(","").replace(")","").split(" ") for r in points]
    bufferDist = 5000
    polygons = [Point(float(p[0]), float(p[1])).buffer(bufferDist) for p in points]
    multi_polygon = cascaded_union(polygons)
    multi_polygon = ogr.CreateGeometryFromWkt(multi_polygon.wkt)
    sourceSR = osr.SpatialReference()
    sourceSR.ImportFromEPSG(int(countries[iso3]['srid']))
    targetSR = osr.SpatialReference()
    targetSR.ImportFromEPSG(4326)
    coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
    multi_polygon.Transform(coordTrans)
    shpDriver = ogr.GetDriverByName("ESRI Shapefile")
    outDataSource = shpDriver.CreateDataSource(input_shapefile_fullpath)  
    outLayer = outDataSource.CreateLayer(input_shapefile, geom_type=ogr.wkbMultiPolygon)
    featureDefn = outLayer.GetLayerDefn()
    outFeature = ogr.Feature(featureDefn)
    outFeature.SetGeometry(multi_polygon)
    outLayer.CreateFeature(outFeature)   
    del outDataSource
    
    return input_shapefile_fullpath
Exemple #25
0
 def c_union(self):
     if self.fovs is not None:
         polygons = [Polygon(mbr_to_path(fov.mbr())) for fov in self.fovs[0:self.fov_count]]
         u = cascaded_union(polygons)
         return u
     else:
         print None
Exemple #26
0
    def fetch(self, **kwargs):
        name = kwargs.pop("name", None)
        if not name:
            raise RuntimeError("Mandatory argument 'name' not given")

        q = self.build_query(name, **kwargs)
        response = requests.get(self.url, params=q)
        if response.status_code != 200:
            raise GisDataFetchError("Could not fetch land type data from gis server.")
        data = response.json()
        polygons = []
        print "Extracting {} {} features".format(len(data["features"]), name)
        error_count=0
        for feature in data["features"]:
            shell = feature["geometry"]["rings"][0]
            holes = feature["geometry"]["rings"][1:]
            holes = holes if holes else None
            polygon=Polygon(shell=shell, holes=holes)
            if polygon.is_valid:
                polygons.append(polygon)
            else:
                error_count +=1
        if error_count>0:
            print "gis polygon error count is",error_count
        return cascaded_union(polygons)
Exemple #27
0
def saveR(rectangles, A, cc, n):
    zona = takeZona(n)
    polis =[]
    for r in rectangles:
        polis.append(r[0])

    union = affinity.rotate(cascaded_union(polis), -A, origin=cc)
    dx = union.centroid.x-cc.x
    dy = union.centroid.y-cc.y
    print 'translate : ',dx, dy
    data2save=()
    for r in rectangles:
        rotated=affinity.rotate(r[0], -A, origin=cc)
        translated = affinity.translate(rotated, -dx, -dy)
        #verificar si interseca
        print zona.intersects(translated)
        if zona.intersects(translated):
            data = (n, A, r[1], r[2], "SRID=25831;"+str(translated))
            data2save += (data,)
        #print data
    conn = db.connect(rootData)
    c = conn.cursor()
    c.executemany('''insert into elementsdiv ( name, ang, x, y, geometry ) values ( ?, ?, ?,?, GeomFromEWKT( ? ) )''', data2save )
    conn.commit()
    conn.close()

    return
Exemple #28
0
def getNeighborhoodsByAreas(conn, areaids, user):
  print 'getting votes'
  (blocks, allVotes) = vote_utils.getVotes(conn, areaids, user)
  print 'got votes'

  blocks_by_hoodid = defaultdict(list)
  id_to_label = {}

  for block in blocks:
    votes = allVotes[block['geoid10']]
    #print block['geoid10']
    maxVotes = vote_utils.pickBestVotes(votes)
    for maxVote in maxVotes:
      blocks_by_hoodid[maxVote['id']].append(block)
      id_to_label[maxVote['id']] = maxVote['label']

  hoods = {}
  print 'doing unions'
  for (id, blocks) in blocks_by_hoodid.iteritems():
    geoms = [asShape(eval(block['geojson_geom'])) for block in blocks]
    blockids = [block['geoid10'] for block in blocks]
    pop10 = sum([block['pop10'] for block in blocks])
    housing10 = sum([block['housing10'] for block in blocks])

    geom = cascaded_union(geoms)
    hoods[id] = NeighborhoodArea(geom, blockids, pop10, housing10)
  return (hoods, id_to_label)
	def generate_paths(self, shapes, tool_d):
		tool_r = tool_d / 2.0
		toolpath = []
		for shp in shapes:
			toolpath.append( shp.buffer(tool_r) )

		result = cascaded_union(toolpath)
		
		if result.geom_type == 'Polygon':
			opt_obj = result.simplify(tolerance=0.01, preserve_topology=False)
			tmp = self.add_holders(opt_obj.exterior, self.holder_size + tool_d, self.min_len)
			if type(tmp) == list:
				return tmp
			else:
				return [tmp]
			
		elif result.geom_type == 'MultiPolygon':
			tmp = []
			for f in result:
				opt_obj = f.simplify(tolerance=0.01, preserve_topology=False)
				tmp2 = self.add_holders(opt_obj.exterior, self.holder_size + tool_d, self.min_len)
				if type(tmp2) == list:
					for item in tmp2:
						tmp.append(item)
				else:
					tmp.append( tmp2 )
			return tmp
Exemple #30
0
def build_aggregate(level, code, name, territories):
    print 'Building aggregate "{0}" (level={1}, code={2})'.format(name, level, code)
    polygons = []
    for tlevel, tcode in territories:
        try:
            territory = Territory.objects.get(level=tlevel, code=tcode)
        except Territory.DoesNotExist:
            print 'Territory {0}/{1} not found'.format(tlevel, tcode)
            continue
        if not shape(territory.geom).is_valid:
            print 'Skipping invalid polygon for {0}'.format(territory.name)
            continue
        if shape(territory.geom).is_empty:
            print 'Skipping empty polygon for {0}'.format(territory.name)
            continue
        polygons.append(territory.geom)

    geom = cascaded_union([shape(p) for p in polygons])
    if geom.geom_type == 'Polygon':
        geom = MultiPolygon([geom])
    try:
        territory = Territory.objects.get(level=level, code=code)
    except Territory.DoesNotExist:
        territory = Territory(level=level, code=code)
    territory.name = name
    territory.geom = geom.__geo_interface__
    territory.save()
Exemple #31
0
 def cascaded_union(self):
     """Deprecated: Return the unary_union of all geometries"""
     return cascaded_union(self.geometry.values)
def poly_iou(poly1, poly2):
    poly = cascaded_union([poly1, poly2])
    union = poly.area
    intersection = poly1.area + poly2.area - union
    return intersection / union
Exemple #33
0
def geohashes_to_polygon(geohashes):
    """
    :param geohashes: array-like. List of geohashes to form resulting polygon.
    :return: shapely geometry. Resulting Polygon after combining geohashes.
    """
    return cascaded_union([geohash_to_polygon(g) for g in geohashes])
Exemple #34
0
    def alpha_shape(points, alpha, centeraxis=None):
        """
        Alpha Shapes Code by KEVIN DWYER, see
        http://blog.thehumangeo.com/2014/05/12/drawing-boundaries-in-python/
            Compute the alpha shape (concave hull) of a set
            of points.
            @param points: Iterable container of points.
            @param alpha: alpha value to influence the
                gooeyness of the border. Smaller numbers
                don't fall inward as much as larger numbers.
                Too large, and you lose everything!

        with minor adaptions to Tag Maps clustering.

        Notes:
        see also floating point resolution issue:
        https://stackoverflow.com/questions/8071382/points-left-out-when-nearby-in-scipy-spatial-delaunay

        Consider replace with shapely.Delauney
        http://kuanbutts.com/2017/08/17/delaunay-triangulation/
        """
        if centeraxis is None:
            centeraxis = False
        if len(points) < 4:
            # When you have a triangle,
            # there is no sense
            # in computing an alpha shape.
            return geometry.MultiPoint(list(points)).convex_hull

        def add_edge(edges, edge_points, coords, i, j):
            """
            Add a line between the i-th and j-th points,
            if not in the list already
            """
            if (i, j) in edges or (j, i) in edges:
                # already added
                return
            edges.add((i, j))
            edge_points.append(coords[[i, j]])

        coords = np.array([point.coords[0] for point in points])

        # qhull_options = 'Qt'
        # #To avoid this error,
        # joggle the data by specifying the
        # 'QJ' option to the DELAUNAY function.see:
        # https://de.mathworks.com/matlabcentral/answers/94438-why-does-the-delaunay-function-in-matlab-7-0-r14-produce-an-error-when-passed-colinear-points?s_tid=gn_loc_drop

        if centeraxis:
            # Center axis for avoiding floating point precision issues
            norm_co = coords[0]
            coords = coords - norm_co
        tri = Delaunay(coords)
        # print problematic points:
        # print(tri.coplanar)
        # tri = Delaunay(coords,qhull_topions='QJ')
        # #Version 3.1 added triangulated output ('Qt').
        # It should be used for Delaunay triangulations
        # instead of using joggled input ('QJ').
        edges = set()
        edge_points = []
        # loop over triangles:
        # vert_ia, ib, ic = indices of corner points of the
        # triangle
        for vert_ia, vert_ib, vert_ic in tri.vertices:
            pa_v = coords[vert_ia]
            pb_v = coords[vert_ib]
            pc_v = coords[vert_ic]
            # Lengths of sides of triangle
            a_val = math.sqrt((pa_v[0] - pb_v[0])**2 + (pa_v[1] - pb_v[1])**2)
            b_val = math.sqrt((pb_v[0] - pc_v[0])**2 + (pb_v[1] - pc_v[1])**2)
            c_val = math.sqrt((pc_v[0] - pa_v[0])**2 + (pc_v[1] - pa_v[1])**2)
            # Semiperimeter of triangle
            s_res = (a_val + b_val + c_val) / 2.0
            # Area of triangle by Heron's formula
            try:
                area = math.sqrt(s_res * (s_res - a_val) * (s_res - b_val) *
                                 (s_res - c_val))
            except ValueError:
                return False
            if area == 0:
                return False
            circum_r = a_val * b_val * c_val / (4.0 * area)
            # Here's the radius filter.
            # print circum_r
            if circum_r < 1.0 / alpha:
                add_edge(edges, edge_points, coords, vert_ia, vert_ib)
                add_edge(edges, edge_points, coords, vert_ib, vert_ic)
                add_edge(edges, edge_points, coords, vert_ic, vert_ia)

        if centeraxis:
            # return to original axis center
            edge_points = [
                np.array([edgepoint[0] + norm_co, edgepoint[1] + norm_co])
                for edgepoint in edge_points
            ]

        mmulti_line_str = geometry.MultiLineString(edge_points)
        triangles = list(polygonize(mmulti_line_str))
        return cascaded_union(triangles)  # , edge_points
Exemple #35
0
 def stairs(self):
     return cascaded_union([
         stair.geometry for stair in self.query('stairs')
     ]).intersection(self.accessible)
Exemple #36
0
    def getTiles(data, bbox, lbl='1'):
        points = {}
        coord_list = []
        polyCoordPositions = {}
        voronoiTiles = {}

        # track the position of each vertex of each geometry in the coordinates list passsed to scypi.voronoi
        # this position is mapped to the id of the corresponding feature in polyCoordPositions
        vert_cnt = 0

        vor_data = VoronoiTiles.get_min_dists([d['geometry'] for d in data])
        toPlot = []

        for d_pos in range(len(vor_data)):
            pid = data[d_pos]['attributes']['ssm_id']
            polyCoordPositions[pid] = []

            if isinstance(data[d_pos]['geometry'], Polygon):
                coords = VoronoiTiles.sample_geometry(
                    vor_data[d_pos][0].exterior.coords[:], vor_data[d_pos][1])
                toPlot.append(Polygon(coords))
                coords = coords[:-1]
            if isinstance(data[d_pos]['geometry'], LineString):
                coords = VoronoiTiles.sample_geometry(
                    vor_data[d_pos][0].coords[:], vor_data[d_pos][1])
                toPlot.append(LineString(coords))
            if isinstance(data[d_pos]['geometry'], Point):
                coords = VoronoiTiles.sample_geometry(
                    vor_data[d_pos][0].coords[:], vor_data[d_pos][1])
                toPlot.append(Point(coords))

            for coord in coords:
                current_vert = vert_cnt
                try:
                    current_vert = points[coord]
                except:
                    points[coord] = current_vert
                    coord_list.append(coord)
                    vert_cnt += 1

                polyCoordPositions[pid].append(current_vert)

        lbl = 'map_data_' + lbl
        #        plot = plotGPD(toPlot, lbl)

        # prepare bbox: add the maximum of min-dists as buffer around bbox
        # - the rational here is that max of min-dists will include enough outer space and if
        #   sketch map distances are somewhat correlated to metric map distances this implies
        #   an increased chance of including objects on the periphery in the expected voronoi region
        # First get the maximum distance
        maxmin_dist = max([d[1] for d in vor_data])

        minx, miny, maxx, maxy = np.array(bbox.bounds)

        bbox = Polygon([(minx - maxmin_dist, miny - maxmin_dist),
                        (maxx + maxmin_dist, miny - maxmin_dist),
                        (maxx + maxmin_dist, maxy + maxmin_dist),
                        (minx - maxmin_dist, maxy + maxmin_dist)])

        vor = Voronoi(coord_list, qhull_options="QJ Pp")  # )#  #UNCOMMENT
        #        fig = voronoi_plot_2d(vor, show_vertices= False, line_width=0.5, point_size=0.5)
        #        fig.set_size_inches((10, 10), forward=True)
        #        plt.xlim(vor.min_bound[0] - 0.5, vor.max_bound[0] + 0.5)
        #        plt.ylim(vor.min_bound[1] - 0.5 , vor.max_bound[1] + 0.5000)
        #        fig.savefig("orig_"+lbl+".svg")
        #        plt.show()

        # plot
        regions, vertices = VoronoiTiles.voronoi_finite_polygons_2d(
            vor, bbox=bbox.bounds)  #UNCOMMENT

        plotTiles = []
        # merge regions corresponding to polygons
        unmerged_vor_regs = []
        for pid in polyCoordPositions:
            region_set = []
            for pt_pos in polyCoordPositions[pid]:
                pt_region = regions[vor.point_region[pt_pos]]
                region_set.append(Polygon(vertices[pt_region]))
                unmerged_vor_regs.append(Polygon(vertices[pt_region]))

            try:
                poly_vor_pg = cascaded_union(region_set)
            except ValueError:
                raise
            # get the combined polygon back as np.array for matplotlib
            # vor_pg = np.array(poly_vor_pg.exterior)

            voronoiTiles[pid] = poly_vor_pg
            plotRow = VoronoiTiles.attrByID(data, pid)
            plotRow['feat_type'] = plotRow['feat_type'] + '_vor_region'
            plotTiles.append({'attributes': plotRow, 'geometry': poly_vor_pg})
            # only need this for visualdebug in matplotlib
            #polyVoronoiMapping[pid] = vor_pg

        lbl = 'voronoi_' + lbl
        #        plot = plotGPD(unmerged_vor_regs, lbl+'_unmerged') # UNCOMMENT
        #        addToPlot(vert_points, plot, lbl+'_unmerged')
        #        plot = plotGPD(plotTiles, lbl) # UNCOMMENT
        #        addToPlot(plotTiles, plot, lbl) # UNCOMMENT

        return voronoiTiles
Exemple #37
0
def image_poly(imgar):
    """
    :param imgar:
    :return:
    """
    polys = []
    over_poly = []
    bar = Bar('Plotting Image Bounds', max=len(imgar))
    # print("BAR", bar)
    for cent in iter(imgar):
        lat = float(cent['coords'][1])
        lng = float(cent['coords'][0])
        print("**Drones Lng, Lats**", lng, lat)
        prps = cent['props']
        fimy = float(prps['FlightRollDegree'])
        fimx = float(prps['FlightPitchDegree'])
        fimz = float(prps['FlightYawDegree'])
        gimr = float(prps['GimbalRollDegree'])
        gimp = float(prps['GimbalPitchDegree'])
        gimy = float(prps['GimbalYawDegree'])
        print("**Gimbal Pitch**", gimp, "\n **Gimbal Roll**", gimr, "\n **Gimbal Yaw**", gimy)
        img_n = prps['File_Name']
        # print("file name", img_n)
        focal_lgth = prps['Focal_Length']
        alt = float(prps["Relative_Altitude"])
        cds1 = utm.from_latlon(lat, lng)
        poly = new_gross(cds1, alt, focal_lgth, gimp, gimr, gimy, fimx, fimy, fimz)
        project = partial(
            pyproj.transform,
            # pyproj.Proj(init=darepo),
            pyproj.Proj(init='epsg:4326'),  # source coordinate system
            pyproj.Proj(init='epsg:3857'))  # destination coordinate system
        g2 = transform(project, poly)
        over_poly.append(g2)

        # Create GeoJSON
        wow3 = geojson.dumps(poly)
        wow4 = json.loads(wow3)
        wow4 = rewind(wow4)

        gd_feat = dict(type="Feature", geometry=wow4, properties=prps)
        gs1 = json.dumps(gd_feat)
        print("gs1", gs1)
        polys.append(gd_feat)
        bar.next()
    union_buffered_poly = cascaded_union([l.buffer(.001) for l in over_poly])
    print("UNION", union_buffered_poly)
    polyz = union_buffered_poly.simplify(0.005, preserve_topology=False)
    print("polyz", polyz)
    projected = partial(
        pyproj.transform,
        pyproj.Proj(init='epsg:3857'),  # source coordinate system
        pyproj.Proj(init='epsg:4326'))  # destination coordinate system
    g3 = transform(projected, polyz)
    print("G3", g3)
    pop3 = geojson.dumps(g3)
    # print("POP3", pop3)
    pop4 = json.loads(pop3)
    pop4 = rewind(pop4)
    # print("pops4", pop4, "\npolys", polys)
    ssx = json.dumps(polys)
    # print("SSX", ssx)
    bar.finish()
    return polys, pop4
Exemple #38
0
    return len(to_subdivide)


while 1:
    n_new = subdivide()
    print("Subdivide made %d new nodes" % n_new)
    if n_new == 0:
        break
##

# Limit that to cdt cells for which the centroid is inside the domain

bounds = wkb2shp.shp2geom('region-bounds-v00.shp')

domain_poly = ops.cascaded_union(polys)

select_cells = [
    domain_poly.contains(geometry.Point(cxy)) for cxy in cdt.cells_centroid()
]
select_cells = np.array(select_cells)

##

# come up with scales:
vc = cdt.cells_center(refresh=True)
diams = np.zeros(cdt.Ncells(), np.float64)
diams[:] = 0

for c in cdt.valid_cell_iter():
    n = cdt.cells['nodes'][c, 0]
 def get_one_polygon(self):
     # f = self.polygons[0]
     # for p in self.polygons[1:]:
     #     f = f.union(p)
     return cascaded_union(self.polygons)
Exemple #40
0
	if countyName in counties:
		counties[countyName].append(precinctName);
	else:
		counties[countyName] = [precinctName]


#print(counties)
#print(polygons)
jsonData = {}
#boundaryCoordinates	cascaded_union(polygons)
for chunk in counties.keys():
	precincts = counties[chunk]
	countyCoordinates = []
	for temp in precincts:
		countyCoordinates.append(polygons[temp])
	boundary = cascaded_union(countyCoordinates)
	temp = {}
	temp["precincts"] = counties[chunk]

	temp["geometry"] = mapping(boundary)
	jsonData[chunk] = temp

#adjacencyMap
adjacencyMap = {}
for i in polygons.keys():
	polygonList = []
	for j in polygons.keys():
		if i == j: 
			continue
		if polygons[i].touches(polygons[j]):
			polygonList.append(j)
Exemple #41
0
 def get_levelconnectors(self, to_level=None):
     queryset = self.query('levelconnectors').prefetch_related('levels')
     if to_level is not None:
         queryset = queryset.filter(levels=to_level)
     return cascaded_union(
         [levelconnector.geometry for levelconnector in queryset])
def swath_selection(swaths_selected=None):
    ''' Selection of swath. Swath information taken from the file:
           Points+Lines_SW_24_stay.xlsx
        Manual inpput check if there exists at least one valid swath otherwise
        repeat the input

        retrieves the extent for each swath, transforms it to Easting,Northing and
        unions the swaths to one polynom

        Parameters: None
        Returns:
        :swaths: list of selelected swaths, empty list if no swath is selected
        :swaths_pnt_polygon: union of selected swaths polygon in points (RL, RP)
        :swaths_geo_polygon: union of selected swaths polygon in (easting, northing)

    '''
    swath_file = r'./Points+Lines_SW_24_stay.xlsx'
    swath_df = pd.read_excel(swath_file, skiprows=5)
    valid_swaths = swath_df['Swath'].tolist()

    swaths = []
    if swaths_selected is None:
        valid = False
        while not valid:
            _swaths = [
                int(num[0]) for num in re.finditer(
                    r'\d+', input('Swaths to be included: [0 for all]: '))
            ]
            if len(_swaths) == 1 and _swaths[0] == 0:
                valid = True
                break

            for swath in _swaths:
                if swath in valid_swaths:
                    swaths.append(swath)

            if swaths:
                valid = True
    else:
        if len(swaths_selected) == 1 and swaths_selected[0] == 0:
            pass
        else:
            for swath in swaths_selected:
                if swath in valid_swaths:
                    swaths.append(swath)

    swaths_pnt_polygon = []
    swaths_geo_polygon = []
    for swath in swaths:
        sd = swath_df[swath_df['Swath'] == swath].iloc[0]

        point1 = (sd['1st RL'], sd['1st GP'])
        point2 = (sd['1st RL'], sd['last GP'])
        point3 = (sd['last RL'], sd['last GP'])
        point4 = (sd['last RL'], sd['1st GP'])
        _polygon = Polygon([point1, point2, point3, point4])
        swaths_pnt_polygon.append(_polygon)

        point1_coord = transformation(point1)
        point2_coord = transformation(point2)
        point3_coord = transformation(point3)
        point4_coord = transformation(point4)
        _polygon = Polygon(
            [point1_coord, point2_coord, point3_coord, point4_coord])
        swaths_geo_polygon.append(_polygon)

    return swaths, cascaded_union(swaths_pnt_polygon), cascaded_union(
        swaths_geo_polygon)
Exemple #43
0
    def get_map_divided_by_region(self, regions_dict, strategy='siting'):

        all_xs = self.net.buses.x.values
        all_ys = self.net.buses.y.values

        minx = min(all_xs) - 5
        maxx = max(all_xs) + 5
        miny = min(all_ys) - 2
        maxy = max(all_ys) + 2

        fig = get_map_layout("", [minx, maxx, miny, maxy], False)

        from functools import reduce
        all_countries = sorted(
            reduce(lambda x, y: x + y, list(regions_dict.values())))
        offshore_shapes = get_shapes(all_countries, 'offshore')["geometry"]
        offshore_shapes.index = [
            'UK' if idx == "GB" else idx for idx in offshore_shapes.index
        ]

        if strategy == "bus":
            # Compute capacity potential per eez
            tech_regions_dict = {"wind_offshore": offshore_shapes.values}
            wind_capacity_potential_per_country = get_capacity_potential_for_regions(
                tech_regions_dict)['wind_offshore']
            wind_capacity_potential_per_country.index = offshore_shapes.index

            # Compute generation per offshore bus
            offshore_buses_index = self.net.buses[~self.net.buses.
                                                  onshore].index
            total_generation_per_bus = pd.Series(index=offshore_buses_index)
            total_max_capacity_per_bus = pd.Series(index=offshore_buses_index)
            for idx in offshore_buses_index:
                offshore_generators_index = self.net.generators[
                    self.net.generators.bus == idx].index
                total_generation_per_bus[idx] = self.net.generators_t.p[
                    offshore_generators_index].values.sum()
                total_max_capacity_per_bus[idx] = self.net.generators.loc[
                    offshore_generators_index, 'p_nom_max'].values.sum()

            offshore_bus_region_shapes = self.net.buses.loc[
                offshore_buses_index].offshore_region

        feature_collection = []
        all_caps_pd = pd.DataFrame(0.,
                                   index=list(regions_dict.keys()),
                                   columns=[
                                       "ccgt", "load", "nuclear", "pv_utility",
                                       "ror", "sto"
                                       "wind_onshore", "wind_offshore"
                                   ])
        for idx, regions in regions_dict.items():

            # Get buses in region
            buses_index = self.net.buses.loc[[
                idx for idx in self.net.buses.index if idx[2:4] in regions
            ]].index

            # Agglomerate regions together
            region_shape = \
                cascaded_union([shapely.wkt.loads(self.net.buses.loc[bus_id].onshore_region) for bus_id in buses_index])

            centroid = region_shape.centroid

            if isinstance(region_shape, sPolygon):
                feature_collection += [
                    Feature(geometry=Polygon(
                        [list(region_shape.exterior.coords)]),
                            id=idx)
                ]
            else:
                feature_collection += \
                    [Feature(geometry=MultiPolygon([(list(poly.exterior.coords), ) for poly in region_shape]), id=idx)]

            # Get all generators for those buses
            generators = self.net.generators[self.net.generators.bus.isin(
                buses_index)]
            all_cap = dict.fromkeys(sorted(set(generators.type)))
            for key in all_cap:
                generators_type_index = generators[generators.type ==
                                                   key].index
                all_cap[key] = np.sum(
                    self.net.generators_t.p[generators_type_index].values)

            # Add STO output
            storage_units = self.net.storage_units[
                self.net.storage_units.bus.isin(buses_index)]
            stos = storage_units[storage_units.type == "sto"]
            all_cap['sto'] = np.sum(
                self.net.storage_units_t.p[stos.index].values)

            # Add wind_offshore
            offshore_regions = [
                r for r in regions if r in offshore_shapes.index
            ]
            eez_region_shape = cascaded_union(
                offshore_shapes.loc[offshore_regions]["geometry"])
            offshore_generators = self.net.generators[self.net.generators.type
                                                      == 'wind_offshore']
            if strategy == 'siting':
                offshore_generators_in_region = \
                    offshore_generators[["x", "y"]].apply(lambda x: eez_region_shape.contains(Point(x[0], x[1])), axis=1)
                offshore_generators_in_region_index = offshore_generators[
                    offshore_generators_in_region].index
                if len(offshore_generators_in_region_index) != 0:
                    all_cap['wind_offshore'] = np.sum(
                        self.net.generators_t.
                        p[offshore_generators_in_region_index].values)

            elif strategy == 'bus':
                wind_capacity = wind_capacity_potential_per_country[
                    offshore_regions].sum()
                # Compute intersection with all offshore shapes
                all_cap['wind_offshore'] = 0
                for off_idx, off_region_shape in offshore_bus_region_shapes.items(
                ):
                    off_region_shape = shapely.wkt.loads(off_region_shape)
                    intersection = off_region_shape.intersection(
                        eez_region_shape)
                    prop_cap_received_by_bus = (
                        intersection.area /
                        eez_region_shape.area) * wind_capacity
                    all_cap['wind_offshore'] += (
                        prop_cap_received_by_bus /
                        total_max_capacity_per_bus[off_idx]
                    ) * total_generation_per_bus[off_idx]

            x = (centroid.x - minx) / (maxx - minx)
            y = (centroid.y - miny) / (maxy - miny)

            title = idx
            if ' ' in title:
                title = f"{title.split(' ')[0]}<br>{title.split(' ')[1]}"

            # Sort values
            sorted_keys = sorted(list(all_cap.keys()))
            sorted_values = [all_cap[key] for key in sorted_keys]

            for i, key in enumerate(sorted_keys):
                all_caps_pd.loc[idx, key] = sorted_values[i]
            all_caps_pd.to_csv("generation_siting.csv")

            fig.add_trace(
                go.Pie(
                    values=sorted_values,
                    labels=sorted_keys,
                    hole=0.4,
                    text=[""] * len(all_cap.keys()),
                    textposition="none",
                    scalegroup='one',
                    domain=dict(x=[max(x - 0.14, 0),
                                   min(x + 0.14, 1.0)],
                                y=[max(y - 0.14, 0),
                                   min(y + 0.14, 1.0)]),
                    marker=dict(
                        colors=[self.tech_colors[key] for key in sorted_keys]),
                    sort=False,
                    title=dict(text=f"{title}",
                               position='middle center',
                               font=dict(size=20))))

        feature_collection = FeatureCollection(feature_collection)

        fig.add_trace(
            go.Choropleth(
                locations=list(regions_dict.keys()),
                geojson=feature_collection,
                z=list(range(len(regions_dict.keys()))),
                text=list(regions_dict.keys()),
                marker=dict(opacity=0.3),
                colorscale='viridis',
                autocolorscale=False,
                reversescale=True,
                marker_line_color='black',
                marker_line_width=1.0,
            ))

        # Add offshore regions
        if 0:
            feature_collection = []
            for i, idx in enumerate(offshore_buses_index):

                region_shape = shapely.wkt.loads(
                    self.net.buses.loc[idx].region)

                if isinstance(region_shape, sPolygon):
                    feature_collection += [
                        Feature(geometry=Polygon(
                            [list(region_shape.exterior.coords)]),
                                id=idx)
                    ]
                else:
                    feature_collection += \
                        [Feature(geometry=MultiPolygon([(list(poly.exterior.coords), ) for poly in region_shape]), id=idx)]

            feature_collection = FeatureCollection(feature_collection)

            fig.add_trace(
                go.Choropleth(
                    locations=offshore_buses_index.values,
                    geojson=feature_collection,
                    z=list(range(len(offshore_buses_index))),
                    text=offshore_buses_index,
                    marker=dict(opacity=0.5),
                    colorscale='plotly3',
                    autocolorscale=False,
                    reversescale=True,
                    marker_line_color='black',
                    marker_line_width=0.5,
                ))

        return fig
Exemple #44
0
    def geometries(self, request, *args, **kwargs):
        if not can_access_editor(request):
            return PermissionDenied

        Level = request.changeset.wrap_model('Level')
        Space = request.changeset.wrap_model('Space')

        level = request.GET.get('level')
        space = request.GET.get('space')
        if level is not None:
            if space is not None:
                raise ValidationError('Only level or space can be specified.')
            level = get_object_or_404(Level.objects.filter(
                Level.q_for_request(request)),
                                      pk=level)

            levels, levels_on_top, levels_under = self._get_levels_pk(
                request, level)
            # don't prefetch groups for now as changesets do not yet work with m2m-prefetches
            levels = Level.objects.filter(pk__in=levels).filter(
                Level.q_for_request(request))
            # graphnodes_qs = request.changeset.wrap_model('GraphNode').objects.all()
            levels = levels.prefetch_related(
                Prefetch(
                    'spaces',
                    request.changeset.wrap_model('Space').objects.filter(
                        Space.q_for_request(request))),
                Prefetch(
                    'doors',
                    request.changeset.wrap_model('Door').objects.filter(
                        Door.q_for_request(request))),
                'buildings',
                'spaces__holes',
                'spaces__groups',
                'spaces__columns',
                'spaces__altitudemarkers',
                # Prefetch('spaces__graphnodes', graphnodes_qs)
            )

            levels = {s.pk: s for s in levels}

            level = levels[level.pk]
            levels_under = [levels[pk] for pk in levels_under]
            levels_on_top = [levels[pk] for pk in levels_on_top]

            # todo: permissions
            # graphnodes = tuple(chain(*(space.graphnodes.all()
            #                            for space in chain(*(level.spaces.all() for level in levels.values())))))
            # graphnodes_lookup = {node.pk: node for node in graphnodes}

            # graphedges = request.changeset.wrap_model('GraphEdge').objects.all()
            # graphedges = graphedges.filter(Q(from_node__in=graphnodes) | Q(to_node__in=graphnodes))
            # graphedges = graphedges.select_related('waytype')

            # this is faster because we only deserialize graphnode geometries once
            # missing_graphnodes = graphnodes_qs.filter(pk__in=set(chain(*((edge.from_node_id, edge.to_node_id)
            #                                                              for edge in graphedges))))
            # graphnodes_lookup.update({node.pk: node for node in missing_graphnodes})
            # for edge in graphedges:
            #     edge._from_node_cache = graphnodes_lookup[edge.from_node_id]
            #     edge._to_node_cache = graphnodes_lookup[edge.to_node_id]

            # graphedges = [edge for edge in graphedges if edge.from_node.space_id != edge.to_node.space_id]

            results = chain(
                *(self._get_level_geometries(l) for l in levels_under),
                self._get_level_geometries(level),
                *(self._get_level_geometries(l) for l in levels_on_top),
                *(space.altitudemarkers.all() for space in level.spaces.all()),
                # graphedges,
                # graphnodes,
            )

            return Response([obj.to_geojson(instance=obj) for obj in results])
        elif space is not None:
            space_q_for_request = Space.q_for_request(request)
            qs = Space.objects.filter(space_q_for_request)
            space = get_object_or_404(qs.select_related(
                'level', 'level__on_top_of'),
                                      pk=space)
            level = space.level

            doors = [
                door for door in level.doors.filter(Door.q_for_request(
                    request)).all() if door.geometry.intersects(space.geometry)
            ]
            doors_space_geom = cascaded_union(
                [door.geometry for door in doors] + [space.geometry])

            levels, levels_on_top, levels_under = self._get_levels_pk(
                request, level.primary_level)
            if level.on_top_of_id is not None:
                levels = chain([level.pk], levels_on_top)
            other_spaces = Space.objects.filter(
                space_q_for_request,
                level__pk__in=levels).prefetch_related('groups')

            space = next(s for s in other_spaces if s.pk == space.pk)
            other_spaces = [
                s for s in other_spaces
                if s.geometry.intersects(doors_space_geom) and s.pk != space.pk
            ]
            all_other_spaces = other_spaces

            if level.on_top_of_id is None:
                other_spaces_lower = [
                    s for s in other_spaces if s.level_id in levels_under
                ]
                other_spaces_upper = [
                    s for s in other_spaces if s.level_id in levels_on_top
                ]
            else:
                other_spaces_lower = [
                    s for s in other_spaces if s.level_id == level.on_top_of_id
                ]
                other_spaces_upper = []
            other_spaces = [s for s in other_spaces if s.level_id == level.pk]

            space.bounds = True

            buildings = level.buildings.all()
            buildings_geom = cascaded_union(
                [building.geometry for building in buildings])
            for other_space in other_spaces:
                if other_space.outside:
                    other_space.geometry = other_space.geometry.difference(
                        buildings_geom)
            for other_space in chain(other_spaces, other_spaces_lower,
                                     other_spaces_upper):
                other_space.opacity = 0.4
                other_space.color = '#ffffff'
            for building in buildings:
                building.opacity = 0.5

            # todo: permissions
            graphnodes = request.changeset.wrap_model(
                'GraphNode').objects.all()
            graphnodes = graphnodes.filter((Q(space__in=all_other_spaces))
                                           | Q(space__pk=space.pk))

            space_graphnodes = tuple(node for node in graphnodes
                                     if node.space_id == space.pk)

            graphedges = request.changeset.wrap_model(
                'GraphEdge').objects.all()
            graphedges = graphedges.filter(
                Q(from_node__in=space_graphnodes)
                | Q(to_node__in=space_graphnodes))
            graphedges = graphedges.select_related('from_node', 'to_node',
                                                   'waytype')

            areas = space.areas.filter(
                Area.q_for_request(request)).prefetch_related('groups')
            for area in areas:
                area.opacity = 0.5

            results = chain(
                buildings, other_spaces_lower, doors, other_spaces,
                [space], areas, space.holes.all(), space.stairs.all(),
                space.ramps.all(), space.obstacles.all(),
                space.lineobstacles.all(), space.columns.all(),
                space.altitudemarkers.all(), space.wifi_measurements.all(),
                space.pois.filter(
                    POI.q_for_request(request)).prefetch_related('groups'),
                other_spaces_upper, graphedges, graphnodes)
            return Response([obj.to_geojson(instance=obj) for obj in results])
        else:
            raise ValidationError('No level or space specified.')
Exemple #45
0
polygons_B = [
    sf["geometry"][1],  #24
    sf["geometry"][3],  #28
    sf["geometry"][4],  #32
    sf["geometry"][5],  #44
    sf["geometry"][6],  #52
    sf["geometry"][7],  #53
    sf["geometry"][11]
]  #93

polygons_C = [
    sf["geometry"][0],  #11
    sf["geometry"][9]
]  #76

u_A = cascaded_union(polygons_A)
u_B = cascaded_union(polygons_B)
u_C = cascaded_union(polygons_C)

sf_zone = sf[:3]
sf_zone = sf_zone.drop(['code'], axis=1)
sf_zone['nom'] = ["A", "B", "C"]
sf_zone['geometry'] = [u_A, u_B, u_C]

sf_zone['value'] = [
    df_zone["Zone_A_male_p"][2], df_zone["Zone_B_male_p"][2],
    df_zone["Zone_C_male_p"][2]
]

deps = gv.Polygons(sf_zone, vdims=['nom', 'value'])
#input for the first layout
Exemple #46
0
def alpha_shape_auto(xys, step=1, verbose=False):
    '''
    Computation of alpha-shape delineation with automated selection of alpha.
    ...

    This method uses the algorithm proposed by  Edelsbrunner, Kirkpatrick &
    Seidel (1983) to return the tightest polygon that contains all points in
    `xys`. The algorithm ranks every point based on its radious and iterates
    over each point, checking whether the maximum alpha that would keep the
    point and all the other ones in the set with smaller radii results in a
    single polygon. If that is the case, it moves to the next point;
    otherwise, it retains the previous alpha value and returns the polygon
    as `shapely` geometry.

    Arguments
    ---------
    xys     : ndarray
              Nx2 array with one point per row and coordinates structured as X
              and Y
    step    : int
              [Optional. Default=1]
              Number of points in `xys` to jump ahead after checking whether the
              largest possible alpha that includes the point and all the
              other ones with smaller radii
    verbose : Boolean
              [Optional. Default=False] If True, it prints alpha values being
              tried at every step.


    Returns
    -------
    poly    : shapely.Polygon
              Tightest alpha-shape polygon containing all points in `xys`

    Example
    -------

    >>> pts = np.array([[0, 1], [3, 5], [4, 1], [6, 7], [9, 3]])
    >>> poly = alpha_shape_auto(pts)
    >>> poly.bounds
    (0.0, 1.0, 9.0, 7.0)
    >>> poly.centroid.x, poly.centroid.y
    (4.690476190476191, 3.4523809523809526)

    References
    ----------

    Edelsbrunner, H., Kirkpatrick, D., & Seidel, R. (1983). On the shape of
        a set of points in the plane. IEEE Transactions on information theory, 
        29(4), 551-559.
    '''
    if not HAS_JIT:
        warn(
            "Numba not imported, so alpha shape construction may be slower than expected."
        )
    if xys.shape[0] < 4:
        from shapely import ops, geometry as geom
        return ops.cascaded_union([geom.Point(xy)
                                   for xy in xys])\
                  .convex_hull.buffer(0)
    triangulation = spat.Delaunay(xys)
    triangulation = spat.Delaunay(xys)
    triangles = xys[triangulation.simplices]
    a_pts = triangles[:, 0, :]
    b_pts = triangles[:, 1, :]
    c_pts = triangles[:, 2, :]
    radii = r_circumcircle_triangle(a_pts, b_pts, c_pts)
    radii[np.isnan(radii)] = 0  # "Line" triangles to be kept for sure
    del triangles, a_pts, b_pts, c_pts
    radii_sorted_i = radii.argsort()
    triangles = triangulation.simplices[radii_sorted_i][::-1]
    radii = radii[radii_sorted_i][::-1]
    geoms_prev = alpha_geoms((1 / radii.max()) - EPS, triangles, radii, xys)
    xys_bb = np.array([*xys.min(axis=0), *xys.max(axis=0)])
    if verbose:
        print('Step set to %i' % step)
    for i in range(0, len(radii), step):
        radi = radii[i]
        alpha = (1 / radi) - EPS
        if verbose:
            print('%.2f%% | Trying a = %f'\
    %((i+1)/radii.shape[0], alpha))
        geoms = alpha_geoms(alpha, triangles, radii, xys)
        if (geoms.shape[0] != 1) or not (np.all(xys_bb == geoms.total_bounds)):
            break
        else:
            geoms_prev = geoms
    return geoms_prev[0]  # Return a shapely polygon
Exemple #47
0
 def areas_and_doors(self):
     return cascaded_union([self.areas, self.raw_doors])
Exemple #48
0
for level in levels:
# level = levels[0]
    print "Processing level: {}".format(level)
    level_path = os.path.join(base_dir, "{}.geojson".format(level))
    feature_list = []
    for ix, row in metadata_df.iterrows():
    # for ix, row in metadata_df.loc[metadata_df["City Name"] == "Milan"].iterrows():
        city_name = row["City Name"].replace(" ", "_")
        fname = level + ".shp"
        if level == "studyArea":
            fname = "{}_{}".format(city_name, fname)
        shp_path = os.path.join(shps_dir, city_name, fname)
        shp = fiona.open(shp_path, "r")
        if len(shp) > 1:
            print "\tCombining {} features for {}".format(len(shp), city_name)
            geom_shape = cascaded_union([shape(i["geometry"]) for i in shp]).buffer(0)
        else:
            geom_shape = shape(shp[0]["geometry"]).buffer(0)
        # if "coordinates" in geom:
        #     geom = {
        #         "type": "Feature",
        #         "geometry": geom,
        #     }
        geom = mapping(geom_shape)
        if shp.crs["init"] != 'epsg:4326':
            geom = reproject(geom, shp.crs["init"])
        if geom["type"] == "Polygon":
            geom = mapping(MultiPolygon([shape(geom)]))
        props = convert_unicode(row.to_dict())
        for i in props:
            if isinstance(props[i], float) and math.isnan(props[i]):
Exemple #49
0
 def holes(self):
     return cascaded_union([
         holes.geometry for holes in self.query('holes').all()
     ]).intersection(self.areas)
Exemple #50
0
 def p2mp(da):  # polygon to multipolygon
     from shapely.ops import cascaded_union
     return cascaded_union(
         da)  # https://stackoverflow.com/questions/36774049/
Exemple #51
0
 def accessible(self):
     return self.areas.difference(
         cascaded_union([self.holes, self.obstacles]))
Exemple #52
0
 def elevatorlevels(self):
     return cascaded_union([
         elevatorlevel.geometry
         for elevatorlevel in self.query('elevatorlevels').all()
     ])
Exemple #53
0
 def areas(self):
     return cascaded_union([self.rooms, self.outsides, self.elevatorlevels])
Exemple #54
0
    def shapes(self, shape_type=1):
        """Computes cluster shapes.
        Parameters:
            shape_type (int): The methods to use for computing cluster
                shapes (allowed values: 1, 2 or 3; default: 1 - fastest).
        Returns:
            A GeoDataFrame containing the cluster shapes.
        """
        pois = self._pois_in_clusters.to_geopandas_df()
        eps_per_cluster = self._eps_per_cluster
        if shape_type == 2:
            cluster_borders = pois.groupby(
                ['cluster_id'], sort=False)['geometry'].agg([list, np.size])
            join_df = pd.merge(cluster_borders,
                               eps_per_cluster,
                               left_index=True,
                               right_index=True,
                               how='inner')
            cluster_list = []
            for index, row in join_df.iterrows():
                eps = row['eps']
                cluster_i = []
                for p in row['list']:
                    cluster_i.append(p.buffer(eps))

                cluster_list.append(cascaded_union(cluster_i))

            join_df['geometry'] = cluster_list
            join_df['cluster_id'] = join_df.index
            join_df.reset_index(drop=True, inplace=True)
            join_df.drop(['list', 'cluster_size'], axis=1, inplace=True)

            cluster_borders = gpd.GeoDataFrame(join_df,
                                               crs=pois.crs,
                                               geometry='geometry')
            cluster_borders = cluster_borders[[
                'cluster_id', 'size', 'geometry'
            ]]

        elif shape_type == 3:
            eps_dict = dict()
            for index, row in eps_per_cluster.iterrows():
                eps_dict[index] = row['eps']

            circles_from_pois = pois.copy()
            cid_size_dict = dict()
            circles = []
            for index, row in circles_from_pois.iterrows():
                cid = row['cluster_id']
                circles.append(row['geometry'].buffer(eps_dict[cid]))
                cid_size_dict[cid] = cid_size_dict.get(cid, 0) + 1

            circles_from_pois['geometry'] = circles

            s_index = pois.sindex

            pois_in_circles = gpd.sjoin(pois,
                                        circles_from_pois,
                                        how="inner",
                                        op='intersects')
            agged_pois_per_circle = pois_in_circles.groupby(
                ['cluster_id_left', 'index_right'],
                sort=False)['geometry'].agg([list])

            poly_list = []
            cluster_id_list = []
            for index, row in agged_pois_per_circle.iterrows():
                pois_in_circle = row['list']
                lsize = len(pois_in_circle)
                if lsize >= 3:
                    poly = MultiPoint(pois_in_circle).convex_hull
                    poly_list.append(poly)
                    cluster_id_list.append(index[0])

            temp_df = pd.DataFrame({
                'cluster_id': cluster_id_list,
                'geometry': poly_list
            })

            grouped_poly_per_cluster = temp_df.groupby(
                ['cluster_id'], sort=False)['geometry'].agg([list])

            cluster_size_list = []
            poly_list = []
            for index, row in grouped_poly_per_cluster.iterrows():
                poly_list.append(cascaded_union(row['list']))
                cluster_size_list.append(cid_size_dict[index])

            grouped_poly_per_cluster['geometry'] = poly_list
            grouped_poly_per_cluster.drop(['list'], axis=1, inplace=True)

            cluster_borders = gpd.GeoDataFrame(grouped_poly_per_cluster,
                                               crs=pois.crs,
                                               geometry='geometry')
            cluster_borders['cluster_id'] = cluster_borders.index
            cluster_borders['size'] = cluster_size_list

        elif shape_type == 1:
            cluster_borders = pois.groupby(
                ['cluster_id'], sort=False)['geometry'].agg([list, np.size])
            cluster_borders['list'] = [
                MultiPoint(l).convex_hull for l in cluster_borders['list']
            ]
            cluster_borders.rename(columns={"list": "geometry"}, inplace=True)
            cluster_borders.sort_index(inplace=True)
            cluster_borders = gpd.GeoDataFrame(cluster_borders,
                                               crs=pois.crs,
                                               geometry='geometry')
            cluster_borders.reset_index(inplace=True)

        else:
            raise Exception('Argument for shape_type could be 1, 2 or 3')

        self._cluster_borders = cluster_borders
        self._shape_type = shape_type
        return cluster_borders
Exemple #55
0
 def raw_escalators(self):
     return cascaded_union([
         escalator.geometry for escalator in self.query('escalators').all()
     ])
Exemple #56
0
 def oneways_raw(self):
     return cascaded_union(
         [oneway.geometry for oneway in self.query('oneways')])
Exemple #57
0
 def levelconnectors(self):
     return cascaded_union([
         levelconnector.geometry
         for levelconnector in self.query('levelconnectors')
     ])
Exemple #58
0
 def stuffedareas(self):
     return cascaded_union([
         stuffedarea.geometry for stuffedarea in self.query('stuffedareas')
     ])
Exemple #59
0
def line_buffer(lat, lon, delta=1.0):
    """Creates buffer around geographical line using from pole rotated cap 
    outlines. This is far from perfect, but it does "a" job. There isn't much
    more that one can and be spherically accurate. As long as the amount of 
    points in the line is fair this should have no problem to immitate a true 
    buffer.

    Parameters
    ----------
    lat : np.ndarray
        latitudes
    lon : np.ndarray
        longitudes
    delta : float, optional
        epicentral distance to line, by default 1.0

    Returns
    -------
    np.ndarray
        Nx2 matrix with coordinates of a polygon that forms a buffer around 
        the line


    Notes
    -----

    :Authors:
        Lucas Sawade ([email protected])

    :Last Modified:
        2021.04.21 20.00 (Lucas Sawade)

    """

    # Buffer circle around z axis
    r = 1
    phi = np.arange(0, 2 * np.pi, 2 * np.pi / 100)
    theta = delta * np.pi / 180

    # Circle around z axis in cartesian
    x = r * np.sin(theta) * np.cos(phi)
    y = r * np.sin(theta) * np.sin(phi)
    z = r * np.cos(theta) * np.ones_like(phi)
    points = np.vstack((x, y, z))

    # Get circlse around the local coordinates
    rcoordset = []

    for _lat, _lon in zip(lat, lon):

        # Convert line coordinates
        x1 = geo2cart(1, _lat, _lon)

        # Compute rotation matrix compute the new set of points
        rpoints = Ra2b((0, 0, 1), x1) @ points

        # Append x and y coordinates
        rcoordset.append(cart2geo(rpoints[0, :], rpoints[1, :], rpoints[2, :]))

    # Generate and combine polygons
    polygons = []
    circles = []

    for _i, coords in enumerate(rcoordset):
        circles.append((coords[2], coords[1]))
        polygon = Polygon([(_x, _y) for _x, _y in zip(coords[2], coords[1])])
        polygons.append(polygon)

    # Combine from converted points
    upoly = cascaded_union(polygons)

    if upoly.type == 'MultiPolygon':
        polyplot = [np.array(x.exterior.xy).T for x in upoly.geoms]
    else:
        polyplot = [np.array(upoly.exterior.xy).T]

    return polyplot, circles
Exemple #60
0
 def escalatorslopes(self):
     return cascaded_union([
         s.geometry for s in self.query('escalatorslopes')
     ]).intersection(self.accessible)