<jupyter_start><jupyter_text>Point in Polygon & IntersectFinding out if a certain point is located inside or outside of an area,or finding out if a line intersects with another line or polygon arefundamental geospatial operations that are often used e.g. to selectdata based on location. Such spatial queries are one of the typicalfirst steps of the workflow when doing spatial analysis. Performing aspatial join (will be introduced later) between two spatial datasets isone of the most typical applications where Point in Polygon (PIP) queryis used. For further reading about PIP and other geometric operations, see Chapter 4.2 in Smith, Goodchild & Longley: [Geospatial Analysis - 6th edition](https://www.spatialanalysisonline.com/HTML/index.html). How to check if point is inside a polygon?Computationally, detecting if a point is inside a polygon is most commonly done using a specific formula called [Ray Casting algorithm](https://en.wikipedia.org/wiki/Point_in_polygonRay_casting_algorithm).Luckily, we do not need to create such a function ourselves forconducting the Point in Polygon (PIP) query. Instead, we can takeadvantage of [Shapely's binary predicates](https://shapely.readthedocs.io/en/stable/manual.htmlbinary-predicates)that can evaluate the topolocical relationships between geographicalobjects, such as the PIP as we're interested here.There are basically two ways of conducting PIP in Shapely:1. using a function called   [.within()](https://shapely.readthedocs.io/en/stable/manual.htmlobject.within)   that checks if a point is within a polygon2. using a function called   [.contains()](https://shapely.readthedocs.io/en/stable/manual.htmlobject.contains)   that checks if a polygon contains a pointNotice: even though we are talking here about **Point** in Polygonoperation, it is also possible to check if a LineString or Polygon isinside another Polygon.-  Let's import shapely functionalities and create some points:<jupyter_code>from shapely.geometry import Point, Polygon

# Create Point objects
p1 = Point(24.952242, 60.1696017)
p2 = Point(24.976567, 60.1612500)<jupyter_output><empty_output><jupyter_text>- Let's also create a polygon using a list of coordinate-tuples:<jupyter_code># Create a Polygon
coords = [(24.950899, 60.169158), (24.953492, 60.169158), (24.953510, 60.170104), (24.950958, 60.169990)]
poly = Polygon(coords)
# Let's check what we have
print(p1)
print(p2)
print(poly)<jupyter_output>POINT (24.952242 60.1696017)
POINT (24.976567 60.16125)
POLYGON ((24.950899 60.169158, 24.953492 60.169158, 24.95351 60.170104, 24.950958 60.16999, 24.950899 60.169158))<jupyter_text>- Let's check if those points are ``within`` the polygon:<jupyter_code># Check if p1 is within the polygon using the within function
p1.within(poly)
# Check if p2 is within the polygon
p2.within(poly)<jupyter_output><empty_output><jupyter_text>Okey, so we can see that the first point seems to be inside that polygonand the other one isn't.-  In fact, the first point is quite close to close to the center of the polygon as we   can see if we compare the point location to the polygon centroid:<jupyter_code># Our point
print(p1)

# The centroid
print(poly.centroid)<jupyter_output>POINT (24.952242 60.1696017)
POINT (24.95224242849236 60.16960179038188)<jupyter_text>-  It is also possible to do PIP other way around, i.e. to check if   polygon contains a point:<jupyter_code># Does polygon contain p1?
poly.contains(p1)
# Does polygon contain p2?
poly.contains(p2)<jupyter_output><empty_output><jupyter_text>Thus, both ways of checking the spatial relationship are identical; [contains()](https://shapely.readthedocs.io/en/stable/manual.htmlobject.contains) is inverse to [within()](https://shapely.readthedocs.io/en/stable/manual.htmlobject.within) and vice versa.Which one should you use then? Well, it depends:-  if you have **many points and just one polygon** and you try to find out   which one of them is inside the polygon: You might need to iterate over the points and check one at a time if it   is **within()** the polygon.-  if you have **many polygons and just one point** and you want to find out   which polygon contains the point: You might need to iterate over the polygons until you find a polygon that **contains()** the point specified (assuming there are no overlapping polygons)         IntersectAnother typical geospatial operation is to see if a geometry intersectsor touches another one. Again, there are binary operations in Shapely for checking these spatial relationships:- [intersects():](https://shapely.readthedocs.io/en/stable/manual.htmlobject.intersects) Two objects intersect if the boundary or interior of one object intersect in any way with the boundary or interior of the other object.- [touches():](https://shapely.readthedocs.io/en/stable/manual.htmlobject.touches) Two objects touch if the objects have at least one point in common and their interiors do not intersect with any part of the other object.   Let's try these out.-  Let's create two LineStrings<jupyter_code>from shapely.geometry import LineString, MultiLineString

# Create two lines
line_a = LineString([(0, 0), (1, 1)])
line_b = LineString([(1, 1), (0, 2)])<jupyter_output><empty_output><jupyter_text>-  Let's see if they intersect<jupyter_code>line_a.intersects(line_b)<jupyter_output><empty_output><jupyter_text>-  Do they also touch each other?<jupyter_code>line_a.touches(line_b)<jupyter_output><empty_output><jupyter_text>Indeed, they do and we can see this by plotting the features together<jupyter_code># Create a MultiLineString from line_a and line_b
multi_line = MultiLineString([line_a, line_b])
multi_line<jupyter_output><empty_output><jupyter_text>Thus, the ``line_b`` continues from the same node ( (1,1) ) where ``line_a`` ends.However, if the lines overlap fully, they don't touch due to the spatial relationship rule, as we can see:- Check if `line_a` touches itself:<jupyter_code># Does the line touch with itself?
line_a.touches(line_a)<jupyter_output><empty_output><jupyter_text>- It does not. However, it does intersect:<jupyter_code># Does the line intersect with itself?
line_a.intersects(line_a)<jupyter_output><empty_output><jupyter_text>Point in Polygon using GeopandasNext we will do a practical example where we check which of the addresses from [the geocoding tutorial](geocoding_in_geopandas.ipynb) are located in Southern district of Helsinki. Let's start by reading a KML-file ``PKS_suuralue.kml`` that has the Polygons for districts of Helsinki Region (data openly available from [Helsinki Region Infoshare](http://www.hri.fi/fi/dataset/paakaupunkiseudun-aluejakokartat).- Let's start by reading the addresses from the Shapefile that we saved earlier.<jupyter_code>import geopandas as gpd

fp = "data/addresses.shp"
data = gpd.read_file(fp)

data.head()<jupyter_output><empty_output><jupyter_text>Reading KML-files in GeopandasIt is possible to read the data from KML-files with GeoPandas in a similar manner as Shapefiles. However, we need to first, enable the KML-driver which is not enabled by default (because KML-files can contain unsupported data structures, nested folders etc., hence be careful when reading KML-files). Supported drivers are managed with [`fiona.supported_drivers`](https://github.com/Toblerity/Fiona/blob/master/fiona/drvsupport.py), which is integrated in geopandas. Let's first check which formats are currently supported:<jupyter_code>import geopandas as gpd
gpd.io.file.fiona.drvsupport.supported_drivers<jupyter_output><empty_output><jupyter_text>- Let's enable the read and write functionalities for KML-driver by passing ``'rw'`` to whitelist of fiona's supported drivers:<jupyter_code>gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = 'rw'<jupyter_output><empty_output><jupyter_text>Let's check again the supported drivers:<jupyter_code>gpd.io.file.fiona.drvsupport.supported_drivers<jupyter_output><empty_output><jupyter_text>Now we should be able to read a KML file using the geopandas [read_file()](http://geopandas.org/reference/geopandas.read_file.htmlgeopandas.read_file) function.- Let's read district polygons from a KML -file that is located in the data-folder:<jupyter_code># Filepath to KML file
fp = "data/PKS_suuralue.kml"
polys = gpd.read_file(fp, driver='KML')
#Check the data
print("Number of rows:",len(polys))
polys.head(11)<jupyter_output>Number of rows: 23<jupyter_text>Nice, now we can see that we have 23 districts in our area. - Let's quickly plot the geometries to see how the layer looks like:<jupyter_code>%matplotlib inline
polys.plot()<jupyter_output><empty_output><jupyter_text>We are interested in an area that is called ``Eteläinen`` (*'Southern'* in English).- Let's select the ``Eteläinen`` district and see where it is located on a map:<jupyter_code># Select data 
southern = polys.loc[polys['Name']=='Eteläinen']
# Reset index for the selection
southern.reset_index(drop=True, inplace=True)
# Check the selction
southern.head()<jupyter_output><empty_output><jupyter_text>- Let's create a map which shows the location of the selected district, and let's also plot the geocoded address points on top of the map:<jupyter_code>import matplotlib.pyplot as plt

# Create a figure with one subplot
fig, ax = plt.subplots()

# Plot polygons
polys.plot(ax=ax, facecolor='gray')
southern.plot(ax=ax, facecolor='red')

# Plot points
data.plot(ax=ax, color='blue', markersize=5)

plt.tight_layout()<jupyter_output><empty_output><jupyter_text>Okey, so we can see that, indeed, certain points are within the selected red Polygon.Let's find out which one of them are located within the Polygon. Hence, we are conducting a **Point in Polygon query**.- First, let's check that we have  `shapely.speedups` enabled. This module makes some of the spatial queries running faster (starting from Shapely version 1.6.0 Shapely speedups are enabled by default):<jupyter_code>#import shapely.speedups
from shapely import speedups
speedups.enabled

# If false, run this line:
#shapely.speedups.enable()<jupyter_output><empty_output><jupyter_text>- Let's check which Points are within the ``southern`` Polygon. Notice, that here we check if the Points are ``within`` the **geometry**  of the ``southern`` GeoDataFrame. - We use the ``.at[0, 'geometry']`` to parse the actual Polygon geometry object from the GeoDataFrame.<jupyter_code>pip_mask = data.within(southern.at[0, 'geometry'])
print(pip_mask)<jupyter_output>0      True
1      True
2      True
3     False
4      True
5     False
6     False
7     False
8     False
9     False
10     True
11    False
12    False
13    False
14    False
15    False
16    False
17    False
18    False
19    False
20    False
21    False
22    False
23    False
24    False
25    False
26    False
27    False
28    False
29    False
30     True
31     True
32     True
33     True
dtype: bool<jupyter_text>As we can see, we now have an array of boolean values for each row, where the result is ``True``if Point was inside the Polygon, and ``False`` if it was not.- We can now use this mask array to select the Points that are inside the Polygon. Selecting data with this kind of mask array (of boolean values) is  easy by passing the array inside the ``loc`` indexer:<jupyter_code>pip_data = data.loc[pip_mask]
pip_data<jupyter_output><empty_output><jupyter_text>Let's finally confirm that our Point in Polygon query worked as it should by plotting the points that are within the southern district:<jupyter_code># Create a figure with one subplot
fig, ax = plt.subplots()

# Plot polygons
polys.plot(ax=ax, facecolor='gray')
southern.plot(ax=ax, facecolor='red')

# Plot points
pip_data.plot(ax=ax, color='gold', markersize=2)

plt.tight_layout()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08695652173913043, 'fraction_numerical': 0.030349531116794545, 'mean_word_length': 5.389433551198257, 'pattern_counts': {'":': 0, '<': 89, '<?xml version=': 0, '>': 89, 'https://': 10, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '23', 'dir': 'jupyter-structured-clean-dedup', 'id': '36296', 'license': 'MIT', 'n_tokens_mistral': 3991, 'n_tokens_neox': 3607, 'n_words': 1349, 'path': 'source/notebooks/L3/point-in-polygon.ipynb', 'repo_name': 'AdrianKriger/Automating-GIS-Processess', 'size': '11730'}