Find all intersecting polygons in a shape file - python

I am trying to find out all the polygons in a shapefile through QGIS Algorithm Extract By Location and it gives me perfect results but takes too much time, around 25 hours. Now, I want it to be done by other libraries like geopandas or other libraries if possible. Can anyone suggest me which library can help?
This is what am doing in geopandas:
import itertools
import geopandas as gpd
gi = gpd.GeoDataFrame.from_file("D:\Shape_file_uploader\qgis\laneGroup.shp")
geoms = gi['geometry'].tolist()
intersection_iter = gpd.GeoDataFrame(gpd.GeoSeries([poly[0].intersection(poly[1]) for poly in itertools.combinations(geoms, 2)

I did this some time ago and if I remember correctly I used the geopandas overlay method. So the 'pseudo' code to handle this ...
from geopandas import GeoDataFrame, overlay
first_shape_gdf = GeoDataFrame.from_file('D:\Shape_file_uploader\qgis\laneGroup.shp')
second_shape_gdf = GeoDataFrame.from_file('another.shp')
intersection_gdf = overlay(first_shape_gdf, second_shape_gdf, how='intersection')
Have a look at Set-Operations with Overlay

Related

Pandana OSM loader does not recognize bbox

I am trying to perform some analysis using Pandana on the city of Santiago de Chile.
import numpy as np
import pandas as pd
import pandana
from pandana.loaders import osm
bbox = [-70.80063634909742,
-33.65910544543891,
-70.46303984334773,
-33.29788325657151] # my SCL bounding box
network = osm.pdna_network_from_bbox(bbox[0],bbox[1],bbox[2],bbox[3])
but I get the error
Exception: Query resulted in no data. Check your query parameters: [out:json][timeout:180];(way["highway"]["highway"!~"motor|proposed|construction|abandoned|platform|raceway"]["foot"!~"no"]["pedestrians"!~"no"](-70.80063635,-33.65910545,-70.46303984,-33.29788326);>;);out;
I have no idea why this bbox does not work, it works with other libraries and this pandana (actually osm) function works with other bboxes.
Are you able to suggest me the cause of the error?
Otherwise, is it possible to convert a OSMNX graph, that I was easily able to build, into a Pandana graph?
Bounding box formatted as a 4 element tuple: (lng_max, lat_min, lng_min, lat_max)
network = osm.pdna_network_from_bbox(lat_min=bbox[0],lng_min=bbox[1], lat_max=bbox[2], lng_max=bbox[3])

PyQGIS changing basemap crs when importing a csv

I am using PyQGIS to import a csv file with a lat and long, when doing this I am using the appropriate crs of EPSG:4326.
I'm plotting this onto Google Maps.
I load my basemap, then import my CSV. The issue is that my basemap projection then changes to 4326 and I need it to remain on 3857.
I've tried importing the basemap after the CSV and moving it down in the layers, however this still changes the projections.
import requests
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from qgis.core import *
from qgis.utils import iface
from qgis import core
#Use Google Street Map as QGIS basemap.
service_url = "mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}"
service_uri = "type=xyz&zmin=0&zmax=21&url=https://"+requests.utils.quote(service_url)
tms_layer = iface.addRasterLayer(service_uri, "GoogleSat", "wms")
#Import CSV and plot.
uri = 'file:///home/user/fred.csv?type=csv&xField=%s&yField=%s&crs=%s' % ("Site Longitude", "Site Latitude", "EPSG:4326")
layer_csv = QgsVectorLayer(uri, 'fred', 'delimitedtext')
layer_csv.isValid()
QgsProject.instance().addMapLayer(layer_csv)
I'll be the first to admit I'm a novice with QGIS!
It seems this has something to do with the application not refreshing properly as mentioned in this answer on gis stack. You may want to look into it for details.
To answer your question in brief, you can add QApplication.instance().processEvents() after QgsProject.instance().addMapLayer(layer_csv) and then use setCrs() to set your basemap CRS to whatever value you need. It will hold.
proj = QgsProject.instance()
proj.addMapLayer(layer_csv)
# This line makes the difference
QApplication.instance().processEvents()
# This sets the project CRS back to 3857
proj.setCrs(QgsCoordinateReferenceSystem(3857))

Plotting polygons onto folium with a gdf frame error

I have an issue i made a fairly simple code I just create my file then create the map and the plot it but I get an error. I want to be plotting the polygons from the file onto the map.
import pandas as pd
import folium
import geopandas as gpd
input_map = "CLUSTERS.TAB"
gdf = gpd.read_file(input_map, driver="MapInfo File")
maploc = folium.Map(location=[42.377157,-71.236088],zoom_start=11,tiles="Stamen Toner")
folium.GeoJson(gdf).add_to(maploc)
The error I get is
builtins.RuntimeError: b'no arguments in initialization list'
I have no idea what this means or how to fix it. Any input helps, Thanks.

.plot() command does not display anything

I have this code based on this question, just a different point Extract constrained polygon using OSMnx
I am trying to plot the block in which the point is located but it does nothing, it just prints "Done" but I cannot see any image
import osmnx as ox
import geopandas as gpd
import shapely
point = (50.090464, 14.400070)
streets_graph = ox.graph_from_point(point, distance=500, network_type='drive')
streets_graph = ox.project_graph(streets_graph)
streets = ox.save_load.graph_to_gdfs(streets_graph, nodes=False, edges=True,
node_geometry=False, fill_edge_geometry=True)
point = streets.unary_union.centroid
polygons = shapely.ops.polygonize(streets.geometry)
polygons = gpd.GeoSeries(polygons)
target = polygons.loc[polygons.contains(point)]
target_streets = streets.loc[streets.intersection(target.iloc[0]).type == 'MultiLineString']
ax = target_streets.plot()
gpd.GeoSeries([point]).plot(ax=ax, color='r')
print("Done")
I do not think this may help but I am using Visual Studio Code
Thank you very much
Since my comment answered your question, I will summarize it here for other people:
When using plotting library dependent on matplotlib, like geopandas or seaborn, you will need to import matplotlib in order to show the plot. The way matplotlib is imported will depend on whether you are using Jupyter or simple scripting (.py) files.
For Jupyter you need to import it like this:
%matplotlib inline
For simple scripting (.py) file you need to import it like this:
import matplotlib.pyplot as plt
Then when you want to show your plot you simply do
plt.show()
Hope it helps!

Python mapping: plotting an electoral boundary over a street map?

I would have thought this would be so simple it would be almost example 1 in any mapping documentation. But it seems not... I want to map the boundary of an electorate over a street map, using cartopy. I can download the GIS data of the electorates in either MapInfo or ShapeFile form. When I tried to do this a year ago, the only way I could find to do it was to extract the lat/long coordinates of the MapInfo polygon, and plot them with matplotlib.
I'm trying to be a bit more elegant this year. With the MapInfo file, I can isolate my particular electorate with
import geopandas as gpd
v = gpd.read_file('VicMaps/vic-july-2018-mid-mif/E_VIC18.MIF')
cg = v.loc[7].geometry
My efforts to extract a particular single boundary from a shapefile are given below.
The other issue is that when I try to run this in jupyter, attempts at plotting a map causes the kernel (python 3.4) to crash.
There must be examples of this somewhere, but so far I haven't found an example which works with my data. This is what I have so far, cobbled together from various helpful answers to other people's questions:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.io.img_tiles import OSM
shp = Reader('VicMaps/E_AUGFN3_region.shp')
fig = plt.figure(figsize=(16,16))
tiler = OSM()
ax = plt.axes(projection=tiler.crs)
ax.set_extent([144.956158, 145.085398, -37.813662, -37.690999])
for r, g in zip(shp.records(), shp.geometries()):
if r.attributes['Elect_div'] == 'Cooper':
ax.add_geometries(g, ccrs.Geodetic())
plt.show()
But what happens is that the kernel just dies "unexpectedly".
If anybody could point me in the direction of a solution, I'd be delighted! Also: I'm not wedded to cartopy; if there's a better package I'll use it.
Thanks!

Categories