<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Pull political boundary data from OpenStreetMap as shapefile
This notebook pulls political boundary data from the OpenStreetMap database and creates a shapefile containing the query results.
Required packages
<a href="https
Step1:  Import statements
Step2:  Utility functions
function to see what results were returned from the Overpass API query
Step3:  Query OpenStreetMap using OverpassAPI via overpy python package
setup Overpass api
Step4:  define bounding box from a 1km-buffered envelope around the study area boundary
Step7:  define query
Step9:  execute query
Step10:  Write OpenStreetMap data to a shapefile
<ASSISTANT_TASK:>
Python Code:
bounding_box_file = ""
result_shapefile_filepath = ""
p1 = pyproj.Proj("+init=epsg:31254")
p2 = pyproj.Proj("+init=epsg:4326")
p3 = pyproj.Proj("+init=epsg:3857")
p4 = pyproj.Proj("+init=epsg:25832")
Explanation: Pull political boundary data from OpenStreetMap as shapefile
This notebook pulls political boundary data from the OpenStreetMap database and creates a shapefile containing the query results.
Required packages
<a href="https://github.com/DinoTools/python-overpy">overpy</a> <br />
<a href="https://github.com/Toblerity/Fiona">Fiona</a>
Variable settings
bounding_box_filepath — path to shapefile to can define the desired bounding box to query the OpenStreetMap database <br />
result_shapefile_filepath — path to export shapefile containing the query results
End of explanation
import overpy
import fiona
import numpy
import geopandas
from shapely.ops import polygonize
from shapely.geometry import LineString
from database.models import Site
import pyproj
from matplotlib import pyplot
%matplotlib inline
Explanation: Import statements
End of explanation
def print_results(results):
    for way in result.ways:
        print("Name: %s" % way.tags.get("name", "n/a"))
        print("  Highway: %s" % way.tags.get("highway", "n/a"))
        print("  Nodes:")
        for node in way.nodes:
            print("    Lat: %f, Lon: %f" % (node.lat, node.lon))
Explanation: Utility functions
function to see what results were returned from the Overpass API query
End of explanation
api = overpy.Overpass()
Explanation: Query OpenStreetMap using OverpassAPI via overpy python package
setup Overpass api
End of explanation
with fiona.open(bounding_box_file, mode='r') as bounding_box:
    bounds = bounding_box.bounds
    bounding_box.close()
print(bounds)
Explanation: define bounding box from a 1km-buffered envelope around the study area boundary
End of explanation
query = way({bottom},{left},{top},{right}) ["highway"]; (._;>;); out body;.format(bottom=bounds[1],
                                                                                        left=bounds[0],
                                                                                        top=bounds[3],
                                                                                        right=bounds[2])
query = 
            [out:json];
            relation
            ["boundary"="administrative"]
            ["admin_level"="2"]
            ["name:en"="Austria"];
            (._;>;);
            out;
        .replace("\n", "").replace(" ", "")
query
Explanation: define query
End of explanation
result = api.query(query)
ways = numpy.empty(len(result.ways), dtype=numpy.object)
for i, way in enumerate(result.ways):
    ways[i] = LineString([ (node.lon, node.lat) for node in way.nodes ])
boundaries = list(polygonize(ways))
boundaries = geopandas.GeoDataFrame(geometry=boundaries, crs="+init=epsg:4326")
boundaries
boundaries.plot(facecolor='white', edgecolor='red')
bbox = boundaries.bounds.iloc[0]
bbox
query = 
            relation({s}, {w}, {n}, {e})
            ["boundary"="administrative"]
            ["admin_level"="2"];
            (._;>;);
            out;
        .format(s=bbox['miny'], w=bbox['minx'], n=bbox['maxy'], e=bbox['maxx']).replace("\n", "").replace(" ", "")
query
result = api.query(query)
ways = numpy.empty(len(result.ways), dtype=numpy.object)
for i, way in enumerate(result.ways):
    ways[i] = LineString([ (node.lon, node.lat) for node in way.nodes ]).simplify(0.01, preserve_topology=False)
boundaries = list(polygonize(ways))
boundaries = geopandas.GeoDataFrame(geometry=boundaries, crs="+init=epsg:4326")
boundaries = boundaries.to_crs(crs="+init=epsg:25832")
center = Site.objects.get(name='Hofgarten')
x, y = center.geometry.coords
x, y = pyproj.transform(p1, p4, x, y)
x
y
geopandas.datasets.available
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
area = world[world.name.isin(['Austria', 'Germany', 'Switzerland', 'Italy'])]
plt = area.plot(facecolor='white', edgecolor='black')
plt.set_frame_on(False)
Explanation: execute query
End of explanation
from fiona.crs import from_epsg
schema = {'geometry': 'LineString', 'properties': {'Name':'str:80', 'Type':'str:80'}}
with fiona.open(result_shapefile_filepath, 'w', crs=from_epsg(4326), driver='ESRI Shapefile', schema=schema) as output:
    for way in result.ways:
        # the shapefile geometry use (lon,lat) 
        line = {'type': 'LineString', 'coordinates':[(node.lon, node.lat) for node in way.nodes]}
        prop = {'Name': way.tags.get("name", "n/a"), 'Type': way.tags.get("highway", "n/a")}
        output.write({'geometry': line, 'properties':prop})
    output.close()
Explanation: Write OpenStreetMap data to a shapefile
End of explanation
<END_TASK>