9. Understanding Parallel Computing
A quick note about the practicals...
Remember that coding should be done in Spyder using the understandinggis virtual environment.
GitHub Desktop should be used for version control.
Don't forget to set your Working Directory to the current week in Spyder!
You do not have to run every bit of code in this document. Read through it, and have a go where you feel it would help your understanding. If I explicitly want you to do something, I will write an instruction that looks like this:
This is an instruction.
Shortcuts: Part 1 Part 2
In which we learn how to make the most out of the CPU by dividing tasks into processes, and revisit our viewshed algorithm to examine running analysis at scale
Part 1
Introduction to Parallel Computing
Parallel computing is about making use of the features of the Central Processing Unit (CPU) to run code more efficiently. Specifically, we run multiple processes on the CPU at the same time, thus reducing the overall runtime of our code (in comparison with a serial version, in which each task runs one after the other).
Preparing some serial code
There is no better way to understand parallel computing than to give it a go. We will demonstrate parallelisation with a simple example in which we will use our evaluate_distortion() function from week 5 to evaluate the quality of a set of global Equal Area map projections (those recommended by the Projection Wizard) for use in a map of Iceland. As we learned in week 5, Equal Area map projections (particularly global ones) are frequently not as equal area as you would want them to be (see Usery and Seong, 2001, for example) - so this is a worthwhile test!
You will hopefully remember that this is a stochastic algorithm, meaning that the randomness in the calculation will lead to small differences between different runs of the same values. As a rule of thumb, the more runs we do, the smaller the variations will be. Unlike last time, when we ran only 1,000 samples per map, this time we will use 10,000. This will give us a much more stable result, but at the cost of around 10x more computing time.
Copy and paste
week5.pyfrom theweek5directory into theweek10directory. If you don’t have access a working copy, you can copy and paste the reference version from the solutions page insteadRead the below script and make sure that you understand what it does.
Once you do, paste it into
week10.py
"""
* Script to evaluate which of the Equal Area projections recommended by
* projectionwizard.org is the best for use in Iceland
"""
from itertools import repeat
from pandas import DataFrame
from time import perf_counter
from geopandas import read_file
from week5 import evaluate_distortion
from pyproj import Geod, CRS, Transformer
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 PyProj Transformer to transform coordinates
results = DataFrame(projections)

At this point, results contains a simple DataFrame containing nothing more than the name and projection string for our six equal area projections:
name proj
0 Mollweide +proj=moll +lon_0=0 +datum=WGS84 +units=m +no_...
1 Hammer +proj=hammer +lon_0=0 +datum=WGS84 +units=m +n...
2 Equal Earth +proj=eqearth +lon_0=0 +datum=WGS84 +units=m +...
3 Eckert IV +proj=eck4 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84...
4 Wagner IV +proj=wag4 +lon_0=0 +datum=WGS84 +units=m +no_...
5 Wagner VII +proj=wag7 +lon_0=0 +datum=WGS84 +units=m +no_...
Next, we want to run each of these projections through our distortion_worker function (above) to evaluate its distortion, and then we want to store the results in the results DataFrame. Simple!
So far in the course, we would have done this using an approach something like this:
# loop through each row (one per projection)
for idx, p in results.iterrows():
# get proj string
proj_string = p['proj']
# calculate the distortion and load it into the dataframe
results.loc[idx, ['Ep', 'Es', 'Ea']] = distortion_worker(geo_string, proj_string, g, minx, miny, maxx, maxy)
**↑ Don’t copy and paste this! ↑ **
This week, however, we are going to use a different approach, and use map(), which is a built-in Python function that is used to call a function multiple times using different arguments. The way it works is to simply give it the function that you want to call as the first argument, then you give it a collection (e.g., a list) of values for each argument. It will run the function using the arguments in position 0 of each list, then position 1, then 2, and so on, until it reaches the end.
For example, this snippet:
def get_string_length(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'pineapple'))
print(list(x))
Returns:
[5, 6, 9]
**↑ Don’t copy and paste these either… ↑ **
Normally, some arguments will not change between calls, and so need to be repeated. Previously, we have dealt with this by making a list and then multiplying it to replicate it (e.g., ['x']*3 gives ['x', 'x', 'x']) . This time, we will use a convenience function called repeat() from the built-in itertools library, which provides an iterator that will keep providing copies of the same value or object for as long as it is needed. In our case, we have ten arguments, only one of which (proj_string) should actually change between the different function calls, so we will use repeat() to generate the arguments for the other nine.
Make sure that you understand
map()andrepeat(), then copy the below snippet into your code and complete it by replacing eachXXXwith the correct value (hint: only theproj_stringargument should be different each time, so you should know where to userepeat()…)
# call the distortion worker once for each projection
distortions = map(distortion_worker,
repeat(geo_string), # geo_string
results['proj'], # proj_string
repeat(g), # g
XXX, # minx (COMPLETE THIS LINE)
XXX, # miny (COMPLETE THIS LINE)
XXX, # maxx (COMPLETE THIS LINE)
XXX, # maxy (COMPLETE THIS LINE)
repeat(10000), # minr
repeat(1000000), # maxr
XXX, # n (COMPLETE THIS LINE)
)
Finally, we can
Paste the below snippet into your code and run it.
# 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"Completed in {perf_counter() - start:.2f} seconds.")
This last section simply drops the proj_string column from the DataFrame as you come to print it, as otherwise it takes up too much space and you can’t see the results!
If all has gone to plan, you should get a message like:
name Ep Es Ea
2 Equal Earth 0.128393 0.218999 0.000412
1 Hammer 0.068748 0.130614 0.002520
5 Wagner VII 0.102475 0.184303 0.002538
3 Eckert IV 0.135803 0.227863 0.002555
4 Wagner IV 0.104407 0.186736 0.002563
0 Mollweide 0.079410 0.148238 0.002564
Completed in 4.65 seconds.
You should see that the Ea value is much better for Equal Earth than for the others (but as expected, it does not perform very well in shape and distance as a result).
Note that the reported time will vary between different machines (and even different runs) - this is just one result from my laptop.

Parallelising your code
Whatever amount of time your code took to run, it is probably a fair assumption that it was longer than we would like. We also know that we are not making full use of our CPU, as the whole script is running in serial (i.e., where each projection is evaluated one after the other). This is, therefore, a great opportunity to parallelise our code, so that each projection can be evaluated at the same time. Allowing for some overhead of the parallelisation process (which for small jobs can be greater than the saving…), this should still make our code run much faster than the serial version.
Let’s find out if it does…
Add the following import statements to your code
from os import process_cpu_count
from concurrent.futures import ProcessPoolExecutor
As you can see, we will be using a class called ProcessPoolExecutor to help us parallelise our code. There are multiple ways to do this in Python, but ProcessPoolExecutor from the concurrent.futures is a modern and relatively high-level interface. For those who are interested, an older and lower-level example is available in the multiprocessing library (this is what I actually used in the original Green View Index calculation).
For our code to run in parallel, we want each of our processes to call this distortion_worker function at the same time, instead of one after the other like it did above. To allow this to happen, we first need to check how many processes we can use. This is simply the number available on the CPU, or the number of jobs we need doing (whichever is smaller):
# 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")
We can then set up all of the function calls and arguments for each process to use. To do this, we must first enter the context of our ProcessPoolManager using with statement:
# 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:
Add these two statements to your code at a sensible location. Note that
distortions = ...is the only line that should be inside thewithblock
This opens the ProcessPoolExecutor and loads it into a variable called executor. Inside the block of the with statement, we are then going to use the executor.map() function. Just like the normal map() function in Python that we used above, this is used to call the a given function (distortion_worker, in this case) multiple times with different arguments each time, using a collection of a values for each argument. The only difference with executor.map() is that each version of the will run in a different process.
Now update your
distortions = ...line (which should now be inside thewithblock) so that so that it usesexecutor.map()instead ofmap(). The result should look like the below:
# 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
)
Make sure you are happy that your script makes sense, then run it.
If it has worked, you should get something like:
Launched 6 processes...
name Ep Es Ea
2 Equal Earth 0.128801 0.218912 0.000420
1 Hammer 0.068586 0.130490 0.002513
5 Wagner VII 0.102261 0.184453 0.002541
3 Eckert IV 0.134689 0.227973 0.002549
4 Wagner IV 0.103757 0.187017 0.002559
0 Mollweide 0.079555 0.148210 0.002563
Completed in 2.94 seconds.
The actual number might vary between 1 (the minimum) and 6 (the number of tasks we gave it) depending on the capability of your CPU.

Part 2
Now we understand the basics of parallel processing, we will apply that knowledge to a more complex situation: calculating the green view index (GVI) (Labib et al., 2021) for 50 schools in a local town called Bolton. I developed GVI with SM Labib (a former PhD student of mine, now a Lecturer at Utrecht) and Sarah Lindley. This method is now the ‘gold standard’ method for the calculation of visibility exposure. GVI is simply calculated as the proportion of the visible area that is ‘green’, which for practical purposes is:
\[GVI = \frac{visible_cells_{green}}{visible_cells_{total}}\]Because calculating many viewsheds over high-resolution data such as we have here (5m resolution) is computationally intensive, this is a perfect opportunity for parallalisation. When we developed the method, I used parallel code on the University’s High Performance Computing (HPC) facility to calculate GVI for the entirety of Greater Manchester at 5m resolution (~87 million viewsheds), as part of Labib’s PhD studies relating to health and greenspace exposure:

Labib et al. (2021)
In our case, we need to do 50 viewsheds to calculate the GVI score for each school, each of which we will calculate using a separate process. It is unlikely that these will all be able to run at the same time on most machines, and the number that can run at the same time will be dependent on the CPU that you are using, but we should certainly see a big improvement in processing time!
On my machine, this approach uses 10 processes, and processes the 50 schools about twice as fast as the serial version (~25 vs ~50 seconds). This might not seem like quite as good an improvement as you would have expected, but I will explain why this is later in this session.
Because the GVI analysis is based on a viewshed (as per week 7), so we already have much of the code that we need ready to go:
Read over the below snippet and make sure you understand it - this simply handles imports and functions that we have already understood in previous week 7, so hopefully should be relatively clear.
Note in particular how the line_of_sight_coords() is slightly different from the line_of_sight() function we used in week 7, simply because it returns a list of the indexes (row, col) of the visible cells (rather than updating them directly).
When you understand the snippet below, paste it into your
week10/gvi.pyfile
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/bolton_dsm.tif"
TREES_PATH = "./data/bolton/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
Now that we have our coord_2_img() and line_of_sight_coords() functions in place, it is time to put them together in a function called gvi_worker(), this is the function that we will call from executor.map() to run in parallel.
Create a function called
gvi_worker()with the following arguments:x0, y0, radius_m, observer_height, dsm_path, trees_path
Reading raster data using a Window
In Understanding Surfaces I & II, we used a context manager (with statement) to open our raster datasets. We then used a separate call to .read() to actually load the data into RAM. So far, we have just loaded entire bands of data into RAM at once, but this is often not desirable, as it can be quite ineffcient. It is therefore common to use a rasterio Window, which specifies the spatial extent of the raster that you would like to read into RAM.
This is especially useful where you have very large rasters (and hence might not be able to read it all at once), and also in situations like this, where each process has its own copy of the data. For example, our DSM is >300MB in size. If we make 50 processes, then we will need to 50 copies, which would amount to 15GB just for that one dataset. Alternatively, each process could only read the part of the DSM required for its individual viewshed, which keeps the RAM requirement much lower, resulting in code that will run more quickly (due to reduced data transfer) and is less likely to crash.
Let’s give that a go then…
Read and understand the below snippet, then paste it into your
gvi_worker()function (taking care to note the indentation)
The key elements are:
- We use a
try-exceptblock to catch any errors gracefully and return anan(not a number) value if the GVI calculation cannot complete. This means that if one school fails, the rest of the analysis won’t be lost. - We do some simple checking to make sure that the point is actually located within the dataset (and return
nanif not) - We then calculate the radius (
r) of the viewshed in image space: radius (in metres) divided by the resolution (giving radius in pixels), plus2(just for a safety buffer to make sure we don’t fall off the edge durine to a rounding error). - We then define a
rasterio.Windowobject using thefrom_bounds()function, to which we give the min and max row and column (location ± radius). - We then clip that to the bounds of the actual dataset using the built-in
.intersection()function (to make sure we don’t fall off the edge of the data). - We pass the resulting
windowto the.read()function ofdsmandtreesto extract only the relevant part of the dataset into RAM, and also get the affine transform object for the window (which of course is different to that of the full dataset).
# 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 image space (plus a couple of cells to be safe)
r = (radius_m / abs(dsm.transform[0])) + 2
# 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)
except Exception as e:
print(f"ERROR: GVI failed for point {x0},{y0}: {e}")
return nan

Now, we need to add the code to do the GVI calculation… Much of this is just a matter of calculating the viewshed as we did in Surfaces II, so we will not work through it in detail a second time:
Add the below snippet into your
gvi_worker()function. It should be located inside thetry-exceptblock, but outside thewithstatements for the raster datasets.Complete the return statement to calculate GVI (equation at the top of Part 2 if needed…):
# 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
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 (rows, cols) tree (==1) 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
The only difference between the above and the version we used in Surfaces II is that (just like line_of_sight_coords) we are keeping a list of the index (row, col) of each of the visible cells, instead of setting them in an output surface. I explain more about the key differences below:
First, we extract the rows and cols from the visible list of tuples using the built-in Python function zip() and the unpacking operator (*).
- First, the unpacking operator (
*) removes the individual tuples from theset, so each pixel location is passed as a separate argument tozip()(rather than the set being passed as a single argument) zip()then transposes those pixels from a set of coordinate pairs (e.g.,(10, 12), (10, 13), (11, 14)) to a separate list of rows and columns ((10, 10, 11), (12, 13, 14))- we then use variable expansion to store those two lists into two variables (
rows, cols =) and convert them intonumpyarrayswith the data type set to integer (intp)
# 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)
- We then use those lists of pixel locations to count how many visible cells there are and how many of the visible cells also also contain trees (by getting the
1or0values fromtrees_data) - these values are then all you need to calculate GVI!
# count total visible pixels (convert to float to avoid rounding in final result)
visible_cells = float(len(rows))
# count visible (rows, cols) tree (==1) pixels
visible_trees = np_sum(trees_data[rows, cols] == 1)
(again, make sure you didn’t copy and paste any of the above…)
Launching your processes
At this point, we have all of the functionality we need in place, we just need to load our datasets and set up the ProcessPoolExecutor:
Open a main block (essential when working in parallel)
Read the
../../data/bolton/primary_schools.shpinto aGeoDataFramevariable calledschoolsUnderstand and add the below snippet to report how many processes you are launching (the smaller of the available number on your CPU or the number of schools):
# 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")
Now, open a context manager for a
ProcessPoolExecutorand call itexecutor(just like in Part 1…)Add the below
executor.map()statement forgvi_workerand complete the missing arguments identified withXXX(think about where to userepeat())
# map the function onto every school, each in a separate process
results = executor.map(gvi_worker,
schools.geometry.x, # x0
XXX, # y0
repeat(800), # radius_m
repeat(1.7), # observer_height
repeat(DSM_PATH), # dsm_path
XXX, # trees_path
)
# load the results into the schools GeoDataFrame
schools["gvi"] = list(results)
Finally, add the following (outside the loop!) to report completion:
# report performance counter results
print(f"{len(schools.index)} Schools analysed in {perf_counter() - start:.2f} seconds.")
You can now run your code!!
You might have a few bugs to work through (likely mostly indentation bugs), but after some tweaks you should get the above success message!

Making a Map
Finally…
Add the below to the bottom of your main block to plot your results to a map:
# 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!")
If all has gone to plan, you should now have something like this:

Here, the darker green schools have a view of more trees (with the maximum being ~50% of their total view taken up by trees). Does that meet with your expectations based on the map?
If so then hooray! - you can now do computing in parallel!
