Practical 9 Code Solution

GA Result

Part 2: Parallel GVI

Part 1: Parallel Distortion

Part 2: Parallel GVI

"""
Understanding GIS: Practical 9
@author jonnyhuck

Calculate multiple GVI for a set of schools in parallel

References:
    https://rasterio.readthedocs.io/en/latest/api/rasterio.plot.html
    https://rasterio.readthedocs.io/en/stable/topics/plotting.html
    https://rasterio.readthedocs.io/en/stable/topics/windowed-rw.html
    https://matplotlib.org/3.1.1/gallery/color/colormap_reference.html
    https://matplotlib.org/stable/gallery/text_labels_and_annotations/custom_legends.html
    http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=How%20Visibility%20works
    https://www.zoran-cuckovic.from.hr/QGIS-visibility-analysis/help_qgis2.html#algorithm-options
    https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map
    https://docs.python.org/3/library/itertools.html#itertools.repeat

New Topics:
    Windowed raster reading
    ProcessPoolExecutor
    executor.map()
    itertools.repeat()
"""

from math import hypot
from itertools import repeat
from os import process_cpu_count
from time import perf_counter
from geopandas import read_file
from rasterio import open as rio_open
from rasterio.transform import rowcol
from multiprocessing import get_context
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
from rasterio.plot import show as rio_show
from rasterio.windows import Window, from_bounds
from matplotlib.pyplot import subplots, savefig
from skimage.draw import line, circle_perimeter
from matplotlib_scalebar.scalebar import ScaleBar
from concurrent.futures import ProcessPoolExecutor
from numpy import column_stack, array, nan, intp, sum as np_sum

# paths to the raster datasets (each worker opens these for itself)
DSM_PATH = "./data/bolton/1m_data/bolton_dsm.tif"
TREES_PATH = "./data/bolton/1m_data/bolton_trees_resample.tif"


def coord_2_img(transform, x, y):
    """
    * Convert from coordinate space to image space
    """
    r, c = rowcol(transform, x, y)
    return int(r), int(c)


def line_of_sight_coords(r0, c0, z0, r1, c1, radius, dsm_data):
    """
    * Use Bresenham's Line algorithm to calculate a line of sight from one point to another point,
    *	returning a list of visible cells
    """

    # init variable for biggest dydx so far (starts at -infinity)
    max_dydx = -float('inf')

    # iterate along integer raster cells on line from observer to target
    visible_coords = []
    for r, c in column_stack(line(r0, c0, r1, c1))[1:]: # skip the observer cell itself

        # distance in pixels from observer (Euclidean)
        dx = hypot(c0 - c, r0 - r)

        # if we go too far, or go off the edge of the data, stop looping
        if dx > radius or not (0 <= r < dsm_data.shape[0]) or not (0 <= c < dsm_data.shape[1]):
            break

        # slope from observer to the *top* of this cell
        cur_dydx =  (dsm_data[r, c] - z0) / dx

        # if this slope is greater than any previous slope, this cell is visible
        if cur_dydx > max_dydx:

            # store the index location of the visible cell (instead of setting it to =1)
            visible_coords.append((int(r), int(c)))

            # update max_slope to block further lower-angle points
            max_dydx = cur_dydx

    # return the list of index locations of the visible cells
    return visible_coords


def gvi_worker(x0, y0, radius_m, observer_height, dsm_path, trees_path):
    """
    * Calculate Green Visibility Index based on Labib et al. (2021)
    *   Note that there is no target height in this case, as we are using
    *   the DSM (so it is 0).
    """
    # use try-except so that if one school fails, it doesn't stop the others
    try:

        # open the raster datasets
        with rio_open(dsm_path) as dsm, rio_open(trees_path) as trees:

            # catch if the point is outside the dataset
            if not (dsm.bounds.left <= x0 <= dsm.bounds.right and dsm.bounds.bottom <= y0 <= dsm.bounds.top):
                print(f"ERROR: data point {x0},{y0} outside of dataset")
                return nan

            # calculate the radius around the observer in coordinate space (plus a couple of cells to be safe)
            r = radius_m + 2 * abs(dsm.transform[0])

            # use the radius to define a rasterio window object
            window = from_bounds(x0 - r, y0 - r, x0 + r, y0 + r, dsm.transform).round()

            # clip the window to the edge of the dataset (in case the school is near the edge)
            window = window.intersection(Window(0, 0, dsm.width, dsm.height))

            # read the data inside the window (rather than the whole raster)
            dsm_data = dsm.read(1, window=window)
            trees_data = trees.read(1, window=window)

            # get the affine transform for the window (rather than the whole raster)
            transform = dsm.window_transform(window)

        # convert observer location to raster row/col
        r0, c0 = coord_2_img(transform, x0, y0)

        # radius in pixels (use absolute of pixel x-scale; assumes square pixels)
        radius_px = int(radius_m / abs(transform[0]))

        # observer absolute elevation: DSM value at observer plus observer height
        observer_abs_elev = dsm_data[r0, c0] + observer_height

        # collect visible coords in a set (to avoid duplicates)
        visible = set()

        # add the observer location
        visible.add((int(r0), int(c0)))

        # iterate perimeter points to cast rays
        for rr, cc in column_stack(circle_perimeter(r0, c0, radius_px)):

            # for each line, get visible coords and add to set
            for rc in line_of_sight_coords(r0, c0, observer_abs_elev, int(rr), int(cc), radius_px, dsm_data):
                visible.add(rc)

        # convert to numpy arrays for fast indexing and ensure indices are valid
        rows, cols = zip(*visible)
        rows = array(rows, dtype=intp)  # intp means just use the default integer type used by the system
        cols = array(cols, dtype=intp)

        # count visible tree pixels
        visible_trees = np_sum(trees_data[rows, cols] == 1)

        # count total visible pixels (convert to float to avoid rounding in final result)
        visible_cells = float(len(rows))

        # return GVI value (proportion of visible cells that are tree pixels)
        return visible_trees / visible_cells

    except Exception as e:
        print(f"ERROR: GVI failed for point {x0},{y0}: {e}")
        return nan


# main block
if __name__ == "__main__":

    # read schools data
    schools = read_file("./data/bolton/primary_schools.shp")

    # start timer
    start = perf_counter()

    # one process per CPU core (but no more processes than we have schools)
    n_processes = min(process_cpu_count(), len(schools.index))
    print(f"Launching {n_processes} processes...\n")

    # create an Executor to run GVI calculations in parallel - force spawn context
    with ProcessPoolExecutor(max_workers=n_processes, mp_context=get_context("spawn")) as executor:

        # map the function onto every school, each in a separate process
        results = executor.map(gvi_worker,
            schools.geometry.x,             # x0
            schools.geometry.y,             # y0
            repeat(800),                    # radius_m
            repeat(1.7),                    # observer_height
            repeat(DSM_PATH),               # dsm_path
            repeat(TREES_PATH),             # trees_path
        )

        # load the results into the schools GeoDataFrame
        schools["gvi"] = list(results)

    # report performance counter results
    print(f"{len(schools.index)} Schools analysed in {perf_counter() - start:.2f} seconds.")

    # open the trees dataset for plotting
    with rio_open(TREES_PATH) as trees:

        # Plot DEM + GVI points
        fig, my_ax = subplots(1, 1, figsize=(16, 10))
        my_ax.set_title("Green Visibility Index (GVI) per school")

        # show trees raster as context (transparent)
        rio_show(
            trees,
            ax=my_ax,
            transform = trees.transform,
            cmap = 'Greens',
            alpha=0.4,
        )

    # Plot schools coloured by computed GVI
    schools.plot(
        ax = my_ax,
        column='gvi',
        cmap = 'Greens',
        markersize = 120,
        edgecolor = 'black',
    )

    # add a colour bar for GVI
    if schools["gvi"].notna().any():
        fig.colorbar(
            ScalarMappable(norm=Normalize(vmin=schools["gvi"].min(), vmax=schools["gvi"].max()), cmap='Greens'),
            ax=my_ax,
            pad=0.01,
            label="GVI"
        )

    # add north arrow
    x, y, arrow_length = 0.97, 0.99, 0.1
    my_ax.annotate('N', xy=(x, y), xytext=(x, y-arrow_length),
        arrowprops=dict(facecolor='black', width=5, headwidth=15),
        ha='center', va='center', fontsize=20, xycoords=my_ax.transAxes)

    # add scalebar
    my_ax.add_artist(ScaleBar(dx=1, units="m", location="lower right"))

    # output
    savefig('./out/9-simple.png', bbox_inches='tight')

    print("done!")

Part 1: Parallel Distortion Analysis

from itertools import repeat
from pandas import DataFrame
from time import perf_counter
from geopandas import read_file
from os import process_cpu_count
from week5 import evaluate_distortion
from multiprocessing import get_context
from pyproj import Geod, CRS, Transformer
from concurrent.futures import ProcessPoolExecutor


def distortion_worker(geo_string, proj_string, g, minx, miny, maxx, maxy, minr, maxr, n):
    """ construct a transformer and evaluate distortion """

    # construct transformer
    transformer = Transformer.from_crs(CRS.from_proj4(geo_string), CRS.from_proj4(proj_string), always_xy=True)

    # calculate the distortion with 10,000 samples and return
    return evaluate_distortion(g, transformer, minx, miny, maxx, maxy, minr, maxr, n)


# main code block
if __name__ == "__main__":

    # set the projected CRSs to evaluate for distortion (All Equal Areas from projectionwizard.org)
    projections = [
        {'name':'Mollweide', 'proj':'+proj=moll +lon_0=0 +datum=WGS84 +units=m +no_defs'},
        {'name':'Hammer', 'proj':"+proj=hammer +lon_0=0 +datum=WGS84 +units=m +no_defs"},
        {'name':'Equal Earth', 'proj':"+proj=eqearth +lon_0=0 +datum=WGS84 +units=m +no_defs"},
        {'name':'Eckert IV', 'proj':"+proj=eck4 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"},
        {'name':'Wagner IV', 'proj':"+proj=wag4 +lon_0=0 +datum=WGS84 +units=m +no_defs"},
        {'name':'Wagner VII', 'proj':"+proj=wag7 +lon_0=0 +datum=WGS84 +units=m +no_defs"}]

    # set the geographical proj string and ellipsoid (should be the same)
    geo_string = "+proj=longlat +datum=WGS84 +no_defs"
    g = Geod(ellps='WGS84')

    # load the shapefile of countries and extract country of interest
    world = read_file("./data/natural-earth/ne_10m_admin_0_countries.shp")

    # set country using country code
    country = world.loc[world.ISO_A3 == "ISL"]

    # get the bounds of the country
    minx, miny, maxx, maxy = country.total_bounds

    # start timer
    start = perf_counter()

    # initialise a dataframe to hold the results
    results = DataFrame(projections)

    # one process per CPU core (but no more processes than we have projections)
    n_processes = min(process_cpu_count(), len(results.index))
    print(f"Launching {n_processes} processes...\n")

    # create an Executor to run distortion calculations in parallel - force spawn context
    with ProcessPoolExecutor(max_workers=n_processes, mp_context=get_context("spawn")) as executor:

        # map the function onto every projection, each will run in a different process
        distortions = executor.map(distortion_worker,
            repeat(geo_string),     # geo_string
            results['proj'],        # proj_string
            repeat(g),              # g
            repeat(minx),           # minx
            repeat(miny),           # miny
            repeat(maxx),           # maxx
            repeat(maxy),           # maxy
            repeat(10000),          # minr
            repeat(1000000),        # maxr
            repeat(10000),          # n
        )

    # load the results (one (Ep, Es, Ea) tuple per projection) into the dataframe
    results[['Ep', 'Es', 'Ea']] = list(distortions)

    # print the results, sorted by area distortion
    print(results.drop('proj', axis=1).sort_values('Ea'))
    print(f"\nCompleted in {perf_counter() - start:.2f} seconds.")