Esempio n. 1
0
def test_footprints():
    import json
    import pytest
    from shapely.geometry import Polygon

    # download footprints and plot them
    gdf = ox.footprints_from_place(place='Emeryville, California, USA')
    gdf = ox.footprints_from_polygon(
        Polygon([(17.574, -4.145), (17.575, -4.144), (17.576, -4.145)]))
    gdf = ox.footprints_from_address(
        address='600 Montgomery St, San Francisco, California, USA',
        distance=300)
    fig, ax = ox.plot_footprints(gdf)

    # new_river_head.json contains a relation with 1 outer closed way and 2 inner closed ways
    # inner way 665593284 is directly tagged as a building and should create its own polygon
    with open("tests/input_data/new_river_head.json", "r") as read_file:
        new_river_head_responses = [json.load(read_file)]
    new_river_head_gdf = ox.create_footprints_gdf(
        responses=new_river_head_responses)
    assert 665593284 in new_river_head_gdf.index
    assert new_river_head_gdf.loc[9246394]['geometry'].type == 'Polygon'
    assert len(new_river_head_gdf.loc[9246394, 'geometry'].interiors) == 2

    # clapham_common.json contains a relation with 5 outer rings and 1 inner ring. One of the outer rings is a chain of open ways
    with open("tests/input_data/clapham_common.json", "r") as read_file:
        clapham_common_responses = [json.load(read_file)]
    clapham_common_gdf = ox.create_footprints_gdf(
        footprint_type='leisure', responses=clapham_common_responses)
    assert clapham_common_gdf.loc[1290065]['geometry'].type == 'MultiPolygon'

    # relation_no_outer.json contains a relation with 0 outer rings and 1 inner ring
    with open("tests/input_data/relation_no_outer.json", "r") as read_file:
        relation_no_outer_responses = [json.load(read_file)]
    ox.create_footprints_gdf(responses=relation_no_outer_responses)

    # inner_chain.json contains a relation with 1 outer rings and several inner rings one of which is a chain of open ways
    with open("tests/input_data/inner_chain.json", "r") as read_file:
        inner_chain_responses = [json.load(read_file)]
    ox.create_footprints_gdf(responses=inner_chain_responses)

    # mis_tagged_bus_route.json contains a relation with out 'inner' or 'inner' rings
    with open("tests/input_data/mis_tagged_bus_route.json", "r") as read_file:
        mis_tagged_bus_route_responses = [json.load(read_file)]
    ox.create_footprints_gdf(responses=mis_tagged_bus_route_responses)

    # test plotting multipolygon
    fig, ax = ox.plot_footprints(clapham_common_gdf)

    # should raise an exception
    # polygon or -north, south, east, west- should be provided
    with pytest.raises(ValueError):
        ox.create_footprints_gdf(polygon=None,
                                 north=None,
                                 south=None,
                                 east=None,
                                 west=None)

    gdf = ox.footprints_from_place(place='kusatsu, shiga, japan',
                                   which_result=2)
Esempio n. 2
0
def test_footprints():

    # download footprints and plot them
    cs = '[out:json][timeout:180][date:"2019-10-28T19:20:00Z"]'
    gdf = ox.footprints_from_place(place2, custom_settings=cs)
    gdf = ox.footprints_from_polygon(polygon)
    gdf = ox.footprints_from_address(address, dist=300)
    fig, ax = ox.plot_footprints(gdf)

    # new_river_head.json contains a relation with 1 outer closed way and 2
    # inner closed ways inner way 665593284 is directly tagged as a building
    # and should create its own polygon
    with open("tests/input_data/new_river_head.json", "r") as read_file:
        new_river_head_responses = [json.load(read_file)]
    new_river_head_gdf = ox.footprints._create_footprints_gdf(
        responses=new_river_head_responses)
    assert 665593284 in new_river_head_gdf.index
    assert new_river_head_gdf.loc[9246394]["geometry"].type == "Polygon"
    assert len(new_river_head_gdf.loc[9246394, "geometry"].interiors) == 2

    # clapham_common.json contains a relation with 5 outer rings and 1
    # inner ring. One of the outer rings is a chain of open ways
    with open("tests/input_data/clapham_common.json", "r") as read_file:
        clapham_common_responses = [json.load(read_file)]
    clapham_common_gdf = ox.footprints._create_footprints_gdf(
        footprint_type="leisure", responses=clapham_common_responses)
    assert clapham_common_gdf.loc[1290065]["geometry"].type == "MultiPolygon"

    # relation_no_outer.json contains a relation with 0 outer rings and 1
    # inner ring
    with open("tests/input_data/relation_no_outer.json", "r") as read_file:
        relation_no_outer_responses = [json.load(read_file)]
    ox.footprints._create_footprints_gdf(responses=relation_no_outer_responses)

    # inner_chain.json contains a relation with 1 outer rings and several
    # inner rings one of which is a chain of open ways
    with open("tests/input_data/inner_chain.json", "r") as read_file:
        inner_chain_responses = [json.load(read_file)]
    ox.footprints._create_footprints_gdf(responses=inner_chain_responses)

    # mis_tagged_bus_route.json contains a relation with out 'inner' or
    # 'inner' rings
    with open("tests/input_data/mis_tagged_bus_route.json", "r") as read_file:
        mis_tagged_bus_route_responses = [json.load(read_file)]
    ox.footprints._create_footprints_gdf(
        responses=mis_tagged_bus_route_responses)

    # test plotting multipolygon
    fig, ax = ox.plot_footprints(clapham_common_gdf)

    # should raise an exception
    # polygon or -north, south, east, west- should be provided
    with pytest.raises(ValueError):
        ox.footprints._create_footprints_gdf(polygon=None,
                                             north=None,
                                             south=None,
                                             east=None,
                                             west=None)
Esempio n. 3
0
    def _plot_buildings(self, ax):

        if (self.colors_dict['buildings'] is not None) & (self.buildings
                                                          is not None):
            ox.plot_footprints(
                self.buildings,
                ax=ax,
                color=self.colors_dict['buildings'],
                # edgecolor=self.edge_colors_dict['buildings'],
                # edgewidth=self.edge_width_dict['buildings'],
                show=False,
                close=False)
Esempio n. 4
0
    def _plot_water(self, ax):

        if (self.colors_dict['water'] is not None) & (self.water is not None):
            ox.plot_footprints(
                self.water,
                ax=ax,
                color=self.colors_dict['water'],
                # edgecolor = self.edge_colors_dict['water'],
                # edgewidth=self.edge_width_dict['water'],
                bgcolor='white',
                show=False,
                close=False)
Esempio n. 5
0
    def _plot_green(self, ax):

        if (self.colors_dict['green'] is not None) & (self.green is not None):
            ox.plot_footprints(
                self.green,
                ax=ax,
                color=self.colors_dict['green'],
                # edgecolor=self.edge_colors_dict['green'],
                # edgewidth=self.edge_width_dict['green'],
                bgcolor='white',
                show=False,
                close=False)
Esempio n. 6
0
def test_geometries():

    # geometries_from_bbox - bounding box query to return empty GeoDataFrame
    gdf = ox.geometries_from_bbox(0.009, -0.009, 0.009, -0.009, tags={"building": True})

    # geometries_from_bbox - successful
    north, south, east, west = ox.utils_geo.bbox_from_point(location_point, dist=500)
    tags = {"landuse": True, "building": True, "highway": True}
    gdf = ox.geometries_from_bbox(north, south, east, west, tags=tags)
    fig, ax = ox.plot_footprints(gdf)

    # geometries_from_point - tests multipolygon creation
    gdf = ox.geometries_from_point((48.15, 10.02), tags={"landuse": True}, dist=2000)

    # geometries_from_place - includes test of list of places
    tags = {"amenity": True, "landuse": ["retail", "commercial"], "highway": "bus_stop"}
    gdf = ox.geometries_from_place([place1], tags=tags)

    # geometries_from_address - includes testing overpass settings and snapshot from 2019
    ox.settings.overpass_settings = '[out:json][timeout:200][date:"2019-10-28T19:20:00Z"]'
    gdf = ox.geometries_from_address(address, tags=tags)

    # geometries_from_xml - tests error handling of clipped XMLs with incomplete geometry
    gdf = ox.geometries_from_xml("tests/input_data/planet_10.068,48.135_10.071,48.137.osm")

    # test loading a geodataframe from a local .osm xml file
    with bz2.BZ2File("tests/input_data/West-Oakland.osm.bz2") as f:
        handle, temp_filename = tempfile.mkstemp(suffix=".osm")
        os.write(handle, f.read())
        os.close(handle)
    for filename in ("tests/input_data/West-Oakland.osm.bz2", temp_filename):
        gdf = ox.geometries_from_xml(filename)
        assert "Willow Street" in gdf["name"].values
    os.remove(temp_filename)
Esempio n. 7
0
def test_footprints():

    # download footprints and plot them
    gdf = ox.footprints_from_place(place2)
    gdf = ox.footprints_from_polygon(polygon)
    gdf = ox.footprints_from_address(address, dist=300)
    fig, ax = ox.plot_footprints(gdf)
Esempio n. 8
0
def test_footprints():

    # download footprints and plot them
    gdf = ox.footprints_from_place(place='Emeryville, California, USA')
    gdf = ox.footprints_from_address(
        address='600 Montgomery St, San Francisco, California, USA',
        distance=300)
    fig, ax = ox.plot_footprints(gdf)
Esempio n. 9
0
def test_footprints():

    # download footprints and plot them
    gdf = ox.footprints_from_place(place='Emeryville, California, USA')
    gdf = ox.footprints_from_address(address='600 Montgomery St, San Francisco, California, USA', distance=300)
    fig, ax = ox.plot_footprints(gdf)

    # test multipolygon footprint
    # point is the location of known multipolygon building, relation id 1767022
    point = (51.5276, -0.11)
    gdf = ox.footprints_from_point(point=point, distance=20, footprint_type='building')
    assert 1767022 in gdf.index, "relation 1767022 was not returned in the geodataframe"
    assert gdf.loc[1767022]['geometry'].type=='MultiPolygon', "relation 1767022 is not a multipolygon"
Esempio n. 10
0
def test_footprints():

    # download footprints and plot them
    gdf = ox.footprints_from_place(place='Emeryville, California, USA')
    gdf = ox.footprints_from_address(
        address='600 Montgomery St, San Francisco, California, USA',
        distance=300)
    fig, ax = ox.plot_footprints(gdf)

    # test multipolygon footprint
    # point is the location of known multipolygon building, relation id 1767022
    point = (51.5276, -0.11)
    gdf = ox.footprints_from_point(point=point,
                                   distance=20,
                                   footprint_type='building')
    assert 1767022 in gdf.index, "relation 1767022 was not returned in the geodataframe"
    assert gdf.loc[1767022][
        'geometry'].type == 'MultiPolygon', "relation 1767022 is not a multipolygon"
Esempio n. 11
0
###########################################################################
(fig, ax) = ox.plot_graph(G,
                          node_size=0,
                          figsize=(40, 40),
                          dpi=DPI,
                          bgcolor=bgColor,
                          save=False,
                          edge_color=roadColors,
                          edge_alpha=rdAlpha,
                          edge_linewidth=roadWidths,
                          show=False)
if bldg:
    (fig, ax) = ox.plot_footprints(gdf,
                                   ax=ax,
                                   color=bdColor,
                                   dpi=DPI,
                                   save=False,
                                   show=False,
                                   close=False)
ax.scatter(
    point[1],
    point[0],
    marker="x",
    zorder=10,
    color='#100F0FCC',
    # facecolors='#000000AA', edgecolors='#000000AA',
    s=7500,
    linewidth=5)
ax.text(0.5,
        0.8,
        '{}'.format(label),
# load buildings from about 1.5km² around UCL
point = (51.524498, -0.133874)
dist = 612
gdf = osmnx.footprints_from_point(point=point, dist=dist)

# preview image
gdf_proj = osmnx.projection.project_gdf(gdf, to_crs={'init': 'epsg:3857'})
gdf_proj = gdf_proj[gdf_proj.geometry.apply(
    lambda g: g.geom_type != 'MultiPolygon')]

fig, ax = osmnx.plot_footprints(gdf_proj,
                                bgcolor='#333333',
                                color='w',
                                figsize=(4, 4),
                                save=True,
                                show=False,
                                close=True,
                                filename='test_buildings_preview',
                                dpi=600)

# save
test_dir = os.path.dirname(__file__)
test_data_geojson = str(os.path.join(test_dir, 'test_buildings.geojson'))
subprocess.run(["rm", test_data_geojson])

gdf_to_save = gdf_proj.reset_index()[['index', 'geometry']]

gdf_to_save.rename(columns={
    'index': 'fid'
}).to_file(test_data_geojson, driver='GeoJSON')
Esempio n. 13
0
def create_map_from_osm(outfile: str, c_osm: int, north: float, south: float,
                        west: float, east: float):
    dpi = 200
    default_width = 6
    network_type = 'drive'

    fp = f'./images/{outfile}-osm-{c_osm}.png'

    tag_building = TagTypes.building
    tag_nature = TagTypes.nature
    tag_water = TagTypes.water

    ax = None

    G = ox.graph_from_bbox(north,
                           south,
                           east,
                           west,
                           network_type=network_type,
                           truncate_by_edge=True,
                           retain_all=True,
                           clean_periphery=False)

    gdf_building = ox.geometries_from_bbox(north,
                                           south,
                                           east,
                                           west,
                                           tags=tag_building)
    gdf_nature = ox.geometries_from_bbox(north,
                                         south,
                                         east,
                                         west,
                                         tags=tag_nature)
    gdf_water = ox.geometries_from_bbox(north,
                                        south,
                                        east,
                                        west,
                                        tags=tag_water)

    fig, ax = ox.plot_figure_ground(G,
                                    default_width=default_width,
                                    dpi=dpi,
                                    filepath=fp,
                                    show=False)
    if not gdf_nature.empty:
        fig, ax = ox.plot_footprints(gdf_nature,
                                     ax=ax,
                                     color='green',
                                     filepath=fp,
                                     dpi=dpi,
                                     save=True)
    if not gdf_water.empty:
        fig, ax = ox.plot_footprints(gdf_water,
                                     ax=ax,
                                     color='blue',
                                     filepath=fp,
                                     dpi=dpi,
                                     save=True)
    if not gdf_building.empty:
        fig, ax = ox.plot_footprints(gdf_building,
                                     ax=ax,
                                     filepath=fp,
                                     dpi=dpi,
                                     save=True)
Esempio n. 14
0
def create_square_from_osm(crop_size: float,
                           crop_status: bool,
                           outfile: str,
                           c_osm: int,
                           point,
                           dpi=100,
                           dist=2000,
                           default_width=6):
    """

    :param crop_size: Crop size of the output
    :param crop_status: Determine whether the output will be cropped or not
    :param outfile: Outfile name
    :param c_osm: count of osm image
    :param point: (lat, long)
    :param dpi: dpi for the output image
    :param dist: distance from the given point
    :param default_width: default width for the roads
    :return:
    """
    network_type = 'drive'

    fp = f'./images/{outfile}-osm-{c_osm}.png'

    tag_building = TagTypes.building
    tag_nature = TagTypes.nature
    tag_water = TagTypes.water

    bbox = ox.utils_geo.bbox_from_point(point, dist=dist)

    try:
        G = ox.graph_from_point(point,
                                network_type=network_type,
                                dist=dist,
                                truncate_by_edge=True,
                                retain_all=True,
                                clean_periphery=True)
        gdf_building = ox.geometries_from_point(point, tag_building, dist=dist)
        gdf_nature = ox.geometries_from_point(point, tag_nature, dist=dist)
        gdf_water = ox.geometries_from_point(point, tag_water, dist=dist)

        fig, ax = ox.plot_figure_ground(G,
                                        default_width=default_width,
                                        show=False,
                                        close=True)

        if not gdf_nature.empty:
            # print('nature')
            fig, ax = ox.plot_footprints(gdf_nature,
                                         ax=ax,
                                         bbox=bbox,
                                         color='green',
                                         filepath=fp,
                                         dpi=dpi,
                                         show=False,
                                         save=True,
                                         close=True)
        if not gdf_water.empty:
            # print('water')
            fig, ax = ox.plot_footprints(gdf_water,
                                         ax=ax,
                                         bbox=bbox,
                                         color='blue',
                                         filepath=fp,
                                         dpi=dpi,
                                         show=False,
                                         save=True,
                                         close=True)
        if not gdf_building.empty:
            # print('building')
            fig, ax = ox.plot_footprints(gdf_building,
                                         ax=ax,
                                         bbox=bbox,
                                         filepath=fp,
                                         dpi=dpi,
                                         save=True,
                                         show=False,
                                         close=True)

        if crop_status:
            image = Image.open(fp)
            image = crop_image(image=image, size=crop_size)
            image.save(f"./images/{outfile}-osm-{c_osm}.png")
        return True

    except:
        return False
Esempio n. 15
0
point = (-17.0188, -149.5884)
(placeName, dist) = ('Onetahi', 1000)
(COLORS, DPI) = (plo.COLORS, 500)
###############################################################################
# Image config
###############################################################################
(img_folder, extension, size) = ('images', 'png', 240)
tags = {'building': True}
###############################################################################
# Get footprints
###############################################################################
gdf = ox.geometries_from_point(point, tags, dist=dist)
gdf_proj = ox.project_gdf(gdf)
fp = f'{PTH}/{placeName}.{extension}'
fig, ax = ox.plot_footprints(
    gdf_proj, filepath=fp, 
    dpi=DPI, save=False, show=False, close=True
)
###############################################################################
# Centroids
###############################################################################
bounds = list(gdf['geometry'])
centroids = [[list(i)[0] for i in j.centroid.xy] for j in bounds]
(lons, lats) = list(zip(*centroids))
df = pd.DataFrame({'lons': lons, 'lats': lats})
df.to_csv(f'{PTH}/{placeName}.csv', index=False)
###############################################################################
# Shapefile
###############################################################################
gdf_save = gdf.applymap(lambda x: str(x) if isinstance(x, list) else x)
gdf_save.drop(labels='nodes', axis=1).to_file(f'{PTH}/{placeName}.shp', driver='ESRI Shapefile')