<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Simon Wrigley on Medium]]></title>
        <description><![CDATA[Stories by Simon Wrigley on Medium]]></description>
        <link>https://medium.com/@simonwrigley?source=rss-514380d23687------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lttStm67xDS2bn9RCXgsIQ@2x.jpeg</url>
            <title>Stories by Simon Wrigley on Medium</title>
            <link>https://medium.com/@simonwrigley?source=rss-514380d23687------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:53:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simonwrigley/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Finding which cities share the same Latitude & Longitude]]></title>
            <link>https://simonwrigley.medium.com/finding-which-cities-share-the-same-latitude-longitude-f56a2e332950?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/f56a2e332950</guid>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[cartography]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[qgis]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 08:49:23 GMT</pubDate>
            <atom:updated>2024-10-15T08:49:23.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myx-Zn7vH1e5PGlmXGxEZA.png" /><figcaption>Edinburgh is West of Bristol and in line with Madrid.</figcaption></figure><h4>Using QGIS Geometry Generators</h4><p>It’s always interesting to see which places around the world line up, sharing the same Latitude and Longitude. After seeing a web-app somone had created on LinkedIn, it inspired me to test some functionality in QGIS that I had not explored before: Geometry Generators. These let you style a layer by creating new geometries on-the-fly based on custom expressions.</p><p>To replicate the functionality of the web app, when a user clicks on the map, we want to draw a line of latitude and a line of longitude across the whole map so you can see which cities line up. We can achieve this in QGIS through the use of the Geometry Generator styling option. The basic workflow is as follows:</p><ul><li>The user clicks to add a point on the map</li><li>A point marker is created</li><li>The latitude and longitude of that point are then automatically projected as a line across the entire map</li></ul><h3>Step 1: Add a new temporary scratch layer</h3><p>Go to <strong>Layer &gt; Create Layer &gt; New Temporary Scratch Layer…</strong> and give the new layer a name. Choose geometry type = points and the CRS as EPSG:4326 WGS 84. Press OK to add the layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPMp6t3HbxRPi_yv4Lq3eA.png" /></figure><h3>Step 2: Add symbology</h3><p>Double click the newly created point layer to open the Symbology Settings, then press the + icon to add two more symbology layers as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QESQb69ERUge7rMGg-A3bA.png" /></figure><p>We’re going to keep the first one as a Simple Marker to add a point on the map where the user clicks, then use the second two to add Geometry Generators to give the lines of latitude and longitude.</p><h3>Step 3: Add Geometry Generators</h3><p>Click on the second Simple Marker and change the Symbol Layer Type to Geometry Generator and the Geometry Type to Linestring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE5mMau_jmaNjpB9zFdvYw.png" /></figure><p>Next we enter the expression to generate the new styling — this is where the magic happens! To generate a Latitude line across the whole map where the user clicks we can use the following expression:</p><pre>make_line(<br>make_point(-180, y($geometry)),<br>make_point(180, y($geometry))<br>)</pre><p>Here we create a line between two points at +-180 deg Longitude with the latitude (or Y value) specified within the $geometry variable. The $geometry variable receives the geometry of the point that the user adds to the map.</p><p>We can now also change the third Simple Marker layer that we added to the symbology to become a Geometry Generator and enter the following expression to generate a Longitude line from the point location:</p><pre>make_line(<br>make_point(x($geometry),-80),<br>make_point(x($geometry),80)<br>)</pre><p>Style the Simple Marker and two Geometry Generator lines as you see fit.</p><h3>Step 4: Testing the map</h3><p>Back in the main QGIS window, turn the new layer to <strong>edit mode</strong>, then enable <strong>Add Point Feature.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*4YXHaLbaGzxtI_jFUAcReA.png" /><figcaption>QGIS Edit Toolbar</figcaption></figure><p>Click on the map to add a point in your desired location. Now thanks to the Geometry generators, even though we have only added a point to the map, it is rendered as a point with its latitude and longitude extending across the map to enable you to see how the location lines up with other landmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QfbeexgsiHk0z-wf4wE0yg.png" /><figcaption>The final result</figcaption></figure><p>This is a really simple example, but Geometry Generators can be really powerful. For more examples and information see Alasdair Rae’s excellent tutorial <a href="https://www.statsmapsnpix.com/2023/03/geometry-generators-in-qgis.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f56a2e332950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flattening Multiple Arrays in Google BigQuery]]></title>
            <link>https://simonwrigley.medium.com/flattening-multiple-arrays-in-google-bigquery-e1f9e4af71e2?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f9e4af71e2</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[gis]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 09:36:35 GMT</pubDate>
            <atom:updated>2024-07-16T09:36:35.569Z</atom:updated>
            <content:encoded><![CDATA[<h4>The easy way…</h4><p>When working with geospatial data you frequently encounter data (especially attributes) in nested arrays which you may want to flatten, or expand for further analysis such as those shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*YuF_vSDh5vczU8yyu-X-gQ.png" /><figcaption>BigQuery Arrays</figcaption></figure><p>For unnesting a single array, a lot of documentation points towards using a CROSS JOIN with the UNNEST statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d3ac2a5be4930857bd3b16efce71ffd/href">https://medium.com/media/6d3ac2a5be4930857bd3b16efce71ffd/href</a></iframe><p>When it comes to unnesting multiple array columns however, BigQuery offers comma cross join syntax which is much simpler and easier to read where you simply follow the initial SELECT statement with a comma separated list of UNNEST statements for each column that you wish to flatten:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/598e3d23392823c550f36a3b1e76539f/href">https://medium.com/media/598e3d23392823c550f36a3b1e76539f/href</a></iframe><p>To give the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*ENIdeSLQ_--ac2La1VHHlg.png" /><figcaption>Flattned Array Result</figcaption></figure><p>Happy unnesting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f9e4af71e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Electoral Geography]]></title>
            <link>https://simonwrigley.medium.com/electoral-geography-eae07bfffaec?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae07bfffaec</guid>
            <category><![CDATA[geography]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[elections]]></category>
            <category><![CDATA[spatial-statistics]]></category>
            <category><![CDATA[geospatial]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 15:49:03 GMT</pubDate>
            <atom:updated>2024-07-04T15:56:28.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wv7CWIXXsZLEbAGU7owcg.png" /><figcaption>UK Parliamentary Constituencies</figcaption></figure><h4>Maps and Spatial Statistics</h4><p>It’s election day — today the UK will head to the polls to vote in the General Election, much as it has in any other apart from one one fundamental difference: the geography of Parliamentary Constituencies.</p><p>Following the 2023 Boundary Review, of the 650 constituencies, only 77 remain unchanged. Not only have names changed, but the geographical boundaries have also been altered which could render historical knowledge of voting patterns irrelevant. Why is this?</p><p>The size and shape of electoral divisions matters. In Spatial Statistics this has the catchy name of the <strong>M</strong>odifiable <strong>A</strong>real <strong>U</strong>nit <strong>P</strong>roblem (or MAUP for short). In summary, if you try to aggregate data (e.g. counting votes) within set of boundaries, the size and shape of those boundaries can introduce statistical bias, having a significant affect on the resultant aggregation (especially if the boundaries are irregular in size or shape).</p><p>The Modifiable Areal Unit Problem has two components:</p><ul><li><strong>The Boundary Problem</strong>: Identical spatial data can appear either clustered or dispersed depending on the boundary placed around the data.</li><li><strong>The Scale problem</strong>: The size of the aggregation unit also affects the end result.</li></ul><p>The most effective way to negate the effect of the MAUP is to aggregate geographical data to a regular grid of an appropriate resolution.</p><p>The 2023 Boundary review in the UK has instead been designed in an effort to try and better balance the UK’s 650 Parliamentary Constituencies in terms of their total population. The new criteria for setting boundaries is that:</p><blockquote>The number of registered voters in each constituency must now be within 5% of the “electoral quota” of 73,393, except for five protected island seats.</blockquote><p>As a result of balancing the electoral boundaries by population, their geographical boundaries have had to change. 76 seats have been extended beyond their current boundaries to meet the minimum threshold whilst 73 have been reduced in size and some seats have disappeared completely.</p><blockquote>As the geographical boundaries have changed, if the same electorate were to cast identical votes today, the end result would be different, all down to the Modifiable Areal Unit Problem.</blockquote><h3>Visual Distortion</h3><p>In cartography, visual heirachy and prominence have a significant impact on how people interpret maps. As the UK Consituencies are balanced by population thresholds they can vary considerably in size. This means that it’s easy for your eye to be drawn to larger shapes. <a href="https://www.theguardian.com/politics/ng-interactive/2024/jul/04/uk-general-election-results-2024-live-in-full">The Guardian</a> have a nice graphic on their electoral tracker which allows you to swap from a geographical to a proportional map, reducing the dominance of larger, more sparsely populated Constituencies in the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuX9gN6_BPlyqRhq1V1grQ.png" /><figcaption>A geographical election tracker</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3M3jP5_AWnyA9B0SCIwPg.png" /><figcaption>A proportional area election tracker</figcaption></figure><h3>Spatial Statistics for Political Gain</h3><p>Whilst the UK boundary review has been completed to minimise the total population differences between constituencies, political geography can also be used for more nefarious political purposes.</p><p>In politics, the term Gerrymandering refers to the use of the Modifiable Areal Unit Problem for political gain. The graphic below made by my colleague <a href="https://medium.com/u/1701772dbb74">Helen McKenzie</a> illustrates the concept nicely. The same total number of votes can lead to very different outcomes, purely dependent on how geographical boundaries are used to split or group the electorate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BN8pJtdD__YMUg5m6OL7Ow.png" /><figcaption>Gerrymandering: Using the Modifiable Areal Unit Problem for political gain.</figcaption></figure><p>With some creative boundary manipulation, the vote can be “packed” and “cracked” to either concentrate or split support leading to some highly unusual boundary shapes such as those shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-Ul1t0v7if0d45dcjUhiw.png" /><figcaption>US Congressional Districts (SRC: <a href="https://www.washingtonpost.com/news/wonk/wp/2014/05/15/americas-most-gerrymandered-congressional-districts/">Washington Post</a>)</figcaption></figure><h3>How can the Modifiable Areal Unit Problem be measured?</h3><p>As discussed previously, MAUP has two components:</p><ul><li>The area problem</li><li>The boundary problem</li></ul><p>The area of different geographical boundaries is simple to calculate and compare, whilst Compactness can be used as a measure of how irregularly shaped a boundary is. Geographical compactness can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*C9IT3vu0AMClD5eFHLafhw.gif" /></figure><p>Or in other words, the compactness can be defined as the ratio of the area of the boundary to the area of a circle with the same perimeter. This gives a measure of how irregular a shape is.</p><h3>Broader applications</h3><p>Here we’ve seen how the MAUP can affect the ways in which votes are counted but it is applicable across any form of Spatial Analysis where aggregate statistics are being calculated across a geographical unit. It is a very good reason why you should consider using a regular grid system such as <a href="https://h3geo.org/">H3</a> for geographical aggregations rather than irregular administrative geographies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae07bfffaec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lat Lon or Lon Lat]]></title>
            <link>https://simonwrigley.medium.com/lat-lon-or-lon-lat-8adaf6441ccd?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/8adaf6441ccd</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[spatialdatascience]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[geospatial]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 15:59:54 GMT</pubDate>
            <atom:updated>2024-02-02T15:59:54.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOaxXwx88bgI9Z2PsYM24w.png" /><figcaption>Image SRC: <a href="https://commons.wikimedia.org/wiki/File:Latitude_and_Longitude_of_the_Earth.svg">https://commons.wikimedia.org/wiki/File:Latitude_and_Longitude_of_the_Earth.svg</a></figcaption></figure><h4>Which coordinate order is correct?!</h4><p>If you are a data scientist or developer new to dealing with geospatial data, this can be both confusing and an easy source of error.</p><p>Geographic coordinates are commonly presented as Latitude, Longitude e.g. in the <a href="https://en.wikipedia.org/wiki/World_Geodetic_System#Definition">World Geodetic System WGS 84 Standard</a> as well as in popular culture, for example at the top of every wikipedia.org page about a geographic location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLnYC2O5DKmpaqiqcdrImg.png" /><figcaption>A Wikipedia article with Latitude Longitude coordinates.</figcaption></figure><p>In Mathematics however, the conventional order for Cartesian coordinates is horizontal or X coordinate, followed by the vertical axis or Y coordinate which would correspond to Longitude (X) followed by Latitude (Y).</p><blockquote>One thing that quickly becomes clear when dealing with geospatial data is that <strong>there is no fixed standard on coordinate order</strong>.</blockquote><p>In many web mapping APIs such as <a href="https://developers.google.com/maps/documentation/geocoding/requests-geocoding?_gl=1*3tepaj*_up*MQ..*_ga*NjY3MTA1MDAzLjE3MDY4ODMwNDM.*_ga_NRWSTWS78N*MTcwNjg4MzA0Mi4xLjAuMTcwNjg4MzA0Mi4wLjAuMA..#GeocodingResponses">Google Maps</a>, spatial coordinates are often returned in order of latitude then longitude. In spatial databases like PostGIS or modern data warehouses such as BigQuery, Snowflake or Redshift, spatial coordinates are in longitude followed by latitude.</p><p>There are even conflicting International Standards on the subject. <a href="https://www.iso.org/standard/40114.html"><em>ISO 19125</em></a><em>: Geographic Information Simple Feature Access</em> specifies Lon / Lat whereas <a href="https://www.iso.org/standard/75147.html"><em>ISO 6709</em></a><em>: Standard representation of geographic point location by coordinates </em>specifies the opposite — Lat / Lon.</p><p>The most common theory as to why latitude has traditionally been quoted first is that it was the first to be calculated. To calculate latitude you only need the sun or the North Star (Polaris). It wasn’t until much later in the 17th Century that clocks became accurate enough to calculate longitude. As the earth spins 360 degrees every day or 15 degrees every hour, if you set a clock in London, then set sail, by comparing the time on the clock, to noon (when the sun is highest wherever you are), you can calculate how many degrees east or west you have travelled.</p><p>Many computer applications using geospatial data however utilise lon, lat to conform with the traditional order of X, Y cartesian coordinates.</p><p>Ultimately it is down to the developer to check documentation very carefully as to the correct coordinate order for each application, otherwise you may find your coordinates plotting a long way away from where you expected…!</p><p>Tom Macwright has compiled a useful list of different technologies and which coordinate order they use: <a href="https://macwright.com/lonlat/">https://macwright.com/lonlat/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8adaf6441ccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spatial SQL 101: Should you ever GROUP BY geometry/geography?]]></title>
            <link>https://simonwrigley.medium.com/spatial-sql-101-should-you-ever-group-by-geometry-geography-711402514844?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/711402514844</guid>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgis]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 10:15:26 GMT</pubDate>
            <atom:updated>2024-02-02T10:15:26.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*XPjhV5CX9ghv7Qb8" /><figcaption>Image SRC: <a href="https://postgis.net/workshops/postgis-intro/equality.html">https://postgis.net/workshops/postgis-intro/equality.html</a></figcaption></figure><h4>TLDR: Probably not, unless you are sure of what you are doing!</h4><p>In spatial analysis, it is common to use aggregate functions (COUNT(), SUM(), AVG(), MIN(), MAX() etc) to generate statistics related to a particular geography. All aggregate functions have to be followed by a GROUP BY … clause to instruct the query how to gather your data.</p><p>For example, to answer the question “How many populated places are there in each US State?” you might tempted to use a simple query like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pTAJ9EQYwpPmkZ3u" /></figure><p>The problem with grouping by geometry/geography is that the GROUP BY clause depends on the equality operator. Whilst it is easy to test equality between numeric data types, testing equality between geometry/geographies is a little more complex… Consider the polygons below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*XPjhV5CX9ghv7Qb8" /><figcaption>Image SRC: https://postgis.net/workshops/postgis-intro/equality.html</figcaption></figure><ul><li>Polygon 2 is geometrically equal to polygon 1 however the node order is reversed</li><li>Polygon 3 is geometrically equal to polygon 1 however the start node and node order are different</li><li>Polygon 4 is geometrically equal to polygon 1 however it has double the number of nodes</li><li>Polygon 5 is a different shape to polygon 1 however it has an identical bounding box to all other polygons.</li></ul><p>You can see how this introduces complexity — should two geometries only be considered equal if they are geometrically identical, have the same number of nodes in the same order? Or is it only the size/shape that we are worried about? The answer of course depends on your use case.</p><p>This nuance is why Google BigQuery currently does not support grouping by geography, as there is still debate around what the expected behaviour should be. If you are using PostGIS you can group by geometry/geography and it will consider geometries to be equal when they have the same number of nodes, in the same order with the same start point i.e. exactly equal.</p><p>To further highlight the danger of grouping by geometry, PostGIS used to use a bounding box comparison for GROUP BY for the first 16 years of its existence (up to v2.4) meaning the same query grouping by geometry could give different results depending on the version of PostGIS that you are running!</p><p>Best practice therefore is to group by id, or another appropriate field to avoid the problems highlighted above (which is also cheaper computationally). As you have to include all items in a SELECT statement within the GROUP BY clause, you can use the handy ANY_VALUE() function to return geometry/geography as part of your result set to plot the results on a map. ANY_VALUE is an aggregate function and you are presuming that you are grouping by identical geometries so it doesn’t matter which is ultimately returned! See below for an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*laXIOPHY2lvAFJTK" /></figure><p>Find this useful? Follow me for more Geospatial content: <a href="https://medium.com/@simonwrigley">https://medium.com/@simonwrigley</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=711402514844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doppelgänger Geography]]></title>
            <link>https://simonwrigley.medium.com/doppelg%C3%A4nger-geography-955bf69f6411?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/955bf69f6411</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[geospatial-data]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[carto]]></category>
            <category><![CDATA[place-names]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 12:48:18 GMT</pubDate>
            <atom:updated>2023-06-13T08:22:43.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLePZxRj_ZeKNUlX2QXc0Q.png" /><figcaption>Duplicate place names in Great Britain (<a href="https://clausa.app.carto.com/map/4cda13ea-d90b-4a24-8744-2768167f8a0b">interactive version</a>)</figcaption></figure><h4>Finding duplicate place names across Great Britain using BigQuery &amp; CARTO.</h4><p>I’ve always been fascinated with the etymology of place names and whilst on a long car journey at the weekend, I was struck by how many of the place names scrolling by on the SatNav were duplicates of other places in Great Britain and decided to investigate.</p><p>It turns out that there are 7044 distinct places sharing 2381 duplicated names! Read on for the methodology:</p><h3>Data</h3><p>The Ordnance Survey provide an open source dataset “<a href="https://osdatahub.os.uk/downloads/open/OpenNames">OS Open Names</a>” described as “<em>A comprehensive dataset of place names, roads numbers and postcodes for Great Britain</em>”. When downloaded, this contains a Data directory with 819 CSV files, and a Doc folder which contains another CSV with the column headers. For ease of import, we can concatenate the files into a single CSV with the headers attached using the following terminal command from within the root directory:</p><pre>cat ./Doc/OS_Open_Names_Header.csv ./Data/*.csv &gt; os_opennames_all.csv</pre><h3>Methodology</h3><p>Once uploaded to Google BigQuery, we can do some simple investigation to look into duplicated place names. To start off with we can simply find the duplicates using:</p><pre>SELECT<br>  NAME1,<br>  COUNT(*) AS name_count<br>FROM<br>  `os_open_names_dataset`<br>GROUP BY<br>  1<br>ORDER BY<br>  2 DESC</pre><p>However this returns a lot of results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*OLSLzNtiG5JfNggO9Dg9kQ.png" /></figure><p>If we add in the field LOCAL_TYPE, we can see that many of these are suburban areas, rather than distinct places so we can update our query with a WHERE clause: WHERE LOCAL_TYPE != ‘Suburban Area’ to leave:</p><ul><li>City</li><li>Town</li><li>Village</li><li>Hamlet</li><li>Other Settlement</li></ul><p>Which results in the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*9_Ahd7SlG-Y2G0pOfQbWJw.png" /></figure><p>By wrapping this in a CTE to perform a total count, we can see that there are are 2381 distinct place names in Great Britain which are duplicated one or more times!</p><pre>WITH<br>  duplicates AS (<br>  SELECT<br>    NAME1,<br>    COUNT(*) AS name_count<br>  FROM<br>    `os_open_names_dataset`<br>  WHERE<br>    LOCAL_TYPE != &#39;Suburban Area&#39;<br>  GROUP BY<br>    1)<br><br>SELECT<br>  COUNT(NAME1)<br>FROM<br>  duplicates<br>WHERE<br>  name_count &gt; 1</pre><p>To visualise the geographical distribution of these duplicated placenames, we can re-construct our count to use a window function to add the place name count to every row in the dataset. This means that when we come to visualise the dataset on a map, we can style each place by the number of occurences of it’s name.</p><p>We can use the SQL editor in <a href="http://www.carto.com/">CARTO</a> to visualise the results of the following query directly: (<em>If you don’t have a CARTO account, you can sign up for a free trial </em><a href="https://app.carto.com/signup/"><em>here</em></a>)</p><pre>SELECT<br>  ID,<br>  NAME1,<br>  LOCAL_TYPE,<br>  COUNT(*) OVER (PARTITION BY NAME1) AS name_count,<br>  geom<br>FROM<br>  `os_open_names_dataset`<br>WHERE<br>  LOCAL_TYPE != &#39;Suburban Area&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB25CRS2Q0d4_w9ugf4N4A.png" /></figure><p>We can then style the data and add some Widgets to allow the user to filter the dataset in different ways. We’re going to use:</p><ul><li>A range widget to filter by the number of times a name is repeated (<em>with a custom minimum of 2, so we only display duplicated place names</em>)</li><li>A histogram widget to show the distribution of the place name count</li><li>A category widget with the place names and the count of the number of occurrences</li><li>A category widget to show the settlement type</li></ul><p>Below you can see the completed dashboard where you can explore all of the 7044 places in Great Britain which share their name with somewhere else!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2Abf74uxpXrZckLPP4_cg.png" /><figcaption>View the interactive version of the dashboard <a href="https://clausa.app.carto.com/map/4cda13ea-d90b-4a24-8744-2768167f8a0b">here</a>.</figcaption></figure><p>If you’re interested in the connection between language and place, Robert McFarlane’s book <a href="https://www.penguin.co.uk/books/213416/landmarks-by-macfarlane-robert/9780241967874">Landmarks</a> provides a fascinating read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955bf69f6411" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Street Map Footprints]]></title>
            <link>https://simonwrigley.medium.com/open-street-map-footprints-a4bf89ba421e?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4bf89ba421e</guid>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[carto]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 08:59:06 GMT</pubDate>
            <atom:updated>2023-06-12T08:59:06.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*3OYakbMqpdGLJcPzjfZZaQ.png" /><figcaption>Global corporate editing footprints on Open Street Map</figcaption></figure><p>Following on from my previous post on the OSM edit history of the United Kingdom, I was inspired by <a href="https://www.linkedin.com/in/bathers?miniProfileUrn=urn%3Ali%3Afs_miniProfile%3AACoAAABmnLYBZGXfa9o51B0EocHjZsMVRuelaek">Gareth Bathers</a> comment to look into the edit “footprint” of some of the larger corporations that utilise OpenStreetMap.</p><p>You may not realise it but the majority of consumer mapping applications rely on Open Street Map data in one way or another, including major platforms like Apple Maps and Microsoft Bing. A byproduct of this is that these corporations have large teams of editors updating features on Open Street Map to improve their own maps which are (at least partially) derived from OSM data.</p><p>A great aspect of OSM is that it is fairly well documented, including a whole section on the Wiki regarding <a href="https://wiki.openstreetmap.org/wiki/Category:Organised_Editing_Teams">organised editing teams</a>. From here you can find links to some of the major corporate mapping projects, from which I’ve chosen a sample:</p><ul><li>Apple Maps: <a href="https://github.com/osmlab/appledata">https://github.com/osmlab/appledata</a></li><li>Microsoft: <a href="https://github.com/microsoft/Open-Maps">https://github.com/microsoft/Open-Maps</a></li><li>Amazon Logistics: <a href="https://wiki.openstreetmap.org/wiki/Organised_Editing/Activities/Amazon#Editing_team">https://wiki.openstreetmap.org/wiki/Organised_Editing/Activities/Amazon#Editing_team</a></li></ul><p>Each of these repositories lists the OSM usernames of their edit teams which we can use to interrogate the OSM History Nodes public dataset on Google BigQuery. From this we can discover that these 3 organisations alone have contributed an impressive 181,688,885 edits to the 11,214,272,205 edits in the OSM history dataset (~1.6% of total edits) between 2005 and 2021.</p><p>Using a simple SQL query in <a href="https://www.linkedin.com/company/carto/">CARTO</a>, we can spatially aggregate these 181 million edits into a H3 Spatial Index for visualisation purposes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgaBM0WzNY9Vlkqcf2SoJw.png" /></figure><p>It becomes immediately obvious that the three corporations have very different objectives with their mapping. Amazon Logistics are presumably utilising OSM for vehicle routing in their prime markets (USA &amp; Europe), whilst Apple has a distinctly global footprint, improving Apple Maps coverage and detail. Microsofts footprint is more unusual, focussed predominantly on South America, Australia and Serbia. Check out a fully interactive version of the map by clicking the image below. This map takes advantage of <a href="https://www.linkedin.com/company/carto/">CARTO</a>’s native support for Spatial Indexes alongside Dynamic Tiling to render a 4.4 million row dataset performantly in browser!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9G25hP4ykBa8empG9yCZQ.png" /><figcaption><a href="https://clausa.app.carto.com/map/685d89e1-49a2-4848-b046-2d8378ab0159">https://clausa.app.carto.com/map/685d89e1-49a2-4848-b046-2d8378ab0159</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4bf89ba421e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Spatial SQL: Window Functions]]></title>
            <link>https://simonwrigley.medium.com/advanced-spatial-sql-window-functions-cb1d4ada72ba?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb1d4ada72ba</guid>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 17:23:05 GMT</pubDate>
            <atom:updated>2022-12-15T17:23:05.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEb_cA_k-Q0ITpnNDeqTzw.png" /></figure><p>Here we will use the <a href="https://console.cloud.google.com/marketplace/product/noaa-public/hurricanes">NOAA Global Hurricane Tracks</a> dataset, freely available as a BigQuery public dataset. It is a point dataset containing the position and intensity for every Tropical Cyclone (or hurricane) from 1950–2021. We are going to use window functions to calculate the maximum wind speed for each storm, along with the cumulative and total distance covered by each storm.</p><h3>Maximum Wind Speed (per Storm)</h3><p>The dataset contains the maximum sustained wind speed for each point. Whilst this raw data makes for an interesting visualisation, to see how each storm evolves along its course:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jn3_RULGaZmyPk8N" /></figure><p>It would also be interesting to visualise the maximum wind speed on a per storm basis so it is easier to compare them. To do this you can use a window function as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z2cOvs7Lw1w57R5k" /></figure><p>Here, instead of grouping by sid (storm identifier) we are partitioning the dataset using a window function. Window functions at their most basic take the form:</p><p>AGGREGATE_FUNCTION( ) OVER ( PARTITION BY field_to_partition_on ORDER BY field_to_order_by)</p><p>Here we calculate the maximum wind speed over each partition (for each individual storm). This allows us to plot the max wind speed per storm to compare their relative intensity (darker colours = higher max windspeed):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9qCHk32O19vSgFad" /></figure><p>Whilst a GROUP BY clause would have resulted in a single row for each storm with the maximum wind speed, this query results in the maximum wind speed being appended to every row for each storm, allowing for the visualisation shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tsMu_u1S0A6W-gmE" /></figure><h3>Distance Travelled</h3><p>As well as calculating aggregate statistics across entire partitions, window functions also allow for much more advanced operations, such as utilising rows preceding and following the one currently being evaluated. We can use this to calculate the cumulative distance that the storm has travelled at each point along it’s track.</p><p>Firstly, we need to calculate the distance between every point, for each storm track:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8Crop6ma0ZlXso7" /></figure><p>Here we are partitioning the dataset by sid (storm identifier) and then ordering the rows by time. We then calculate the distance between the geometry currently being evaluated and the previous geometry in the partition, using LAG(geom, 1) before dividing by 1000 to get the result in KM. Once we know the distance between every point, we can calculate the cumulative distance along the track using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*47rFWUKV3-EosgYV" /></figure><p>Again, we are partitioning by the storm identifier, ordering the points by time, but this time we are calculating the SUM of the distance. UNBOUNDED PRECEDING means that we are summing from the start of the partition up to the CURRENT ROW. As we have ordered each partition (each storm) by time, this calculates the cumulative distance travelled by the storm which is plotted on the map below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KzPgZozv6VJjltTO" /></figure><p>Finally, we can calculate the total distance travelled using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*meb_hXAZECU22bic" /></figure><p>With lighter colours representing the longest storm tracks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQCKU4uQyCN7WPbH" /></figure><p>Combining this, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*98-pxrdCXYyIvKPd" /></figure><p>Which you can copy to test in BigQuery yourself from a Github Gist <a href="https://gist.github.com/wriglz/36d56ed14e0c1aef6ac97bdcb12db5e9">here</a>. Click on the image below to view a fully interactive map created in <a href="http://carto.com/">CARTO</a> where you can explore the entire North Atlantic basin dataset (not just 2020):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wiApKGnsi63tZkOb" /></figure><h3>Resources:</h3><ul><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls#compute_a_cumulative_sum">Window functions documentation</a></li><li><a href="https://console.cloud.google.com/marketplace/product/noaa-public/hurricanes">NOAA Global Hurricane Track dataset</a></li><li><a href="https://gist.github.com/wriglz/36d56ed14e0c1aef6ac97bdcb12db5e9">Code used in this example</a></li><li><a href="https://clausa.app.carto.com/map/cae8700d-d23b-4464-980c-0491a3bd88fd">CARTO Map</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb1d4ada72ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Coastline Paradox]]></title>
            <link>https://medium.com/swlh/the-coastline-paradox-de3adee92b65?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3adee92b65</guid>
            <category><![CDATA[fractals]]></category>
            <category><![CDATA[geography]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[geometry]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 15:08:40 GMT</pubDate>
            <atom:updated>2020-01-10T18:17:24.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnG3p-MrrQmPWHdTDAkyyA.png" /><figcaption>Data from <a href="http://naturalearthdata.com/">http://naturalearthdata.com</a></figcaption></figure><h4><strong>Statistical Self-Similarity and Fractal Dimensions.</strong></h4><p>On first reflection, if someone asked you the question: “<em>How long the coastline of Great Britain?</em>” (or any other landmass for that matter) You’d probably give it your best guess and return an integer in miles or kilometres.</p><p>The true answer however, is that it depends! Determining the length of a countries coastline is nowhere near as simple as it would first appear.</p><p>In 1951, Lewis Fry Richardson, a mathematician and pacifist was studying armed conflict. More specifically, he was trying to answer the hypothesis of whether the length of border shared by two countries had any bearing upon the likelihood of them going to war.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*xfneCgz052uTYoLS2_DlfQ.jpeg" /><figcaption>Chart Dividers</figcaption></figure><p>At the time, the prevailing method of estimating the length of a border (or coastline) was to use a large scale map or aerial photograph and a set of chart dividers. The dividers were then used to divide the border into <strong><em>n</em></strong> equal length, straight line segments of length <strong><em>l </em></strong>where the end of each line bisected the border or coastline being measured (<em>effectively down-sampling the level of detail</em>).</p><p>Richardson discovered that the sum of the segments (<em>total border length</em>) is inversely proportional to the common length of the segments <strong><em>l</em></strong>.<strong><em> </em></strong>The result astounded Richardson as in other words, the finer the resolution you use to measure a coastline, the longer the total measurement will be — as <strong><em>l</em></strong> approaches zero, the length of the coastline will tend towards infinity.</p><blockquote>The measured length of a coastline directly depends on the resolution of measurement used.</blockquote><p>Whilst conducting his research into border disputes, Richardson noticed that the Spanish/Portuguese border was stated to be 987 km by Spain and 1,214km by Portugal, a difference of 227 km, which could now be explained purely by the fact that the two countries had measured their border using different scales. This was the beginning of the coastline paradox.</p><p>If the coastline of Britain is measured using units 100 km long, the total length of the coastline is approximately 2,800 km long whereas if units of 50km are used, the total length is approximately 3,400 km, a difference of 600 km.</p><h3>The beginnings of Fractal Geometry</h3><p>This coastline paradox, first observed by Richardson provided the inspiration for one of <a href="https://en.wikipedia.org/wiki/Benoit_Mandelbrot">Benoit Mandelbrot’s</a> initial publications on the topic of fractals. Mandlebrot’s paper <em>“How Long Is the Coast of Britain? Statistical Self-Similarity and Fractional Dimension” </em>was first published in Science in 1967, although it wasn’t until 1975 that he coined the term fractal.</p><p>In the paper, Mandelbrot discusses an empircal law discovered by Richardson which could be approximated by a function of the form:</p><blockquote>L(G) = MG¹⁻ᴰ</blockquote><p>Where:</p><ul><li>L = length</li><li>G = Measurement scale</li><li>M = positive constant</li><li>D = constant called the dimension, ≥ 1.</li></ul><p>Intuitively, if a coasline looks smooth, the dimension should be closer to 1, and the more irregular the coastline, the closer D should be to 2.</p><p>Mandlebrot goes on to describe various mathematical curves related to the <a href="https://en.wikipedia.org/wiki/Koch_snowflake">Koch Snowflake</a>, the earliest described <a href="https://en.wikipedia.org/wiki/Fractal">Fractal</a>. These curves are defined as being strictly self similar whereas coastlines are less definite in their construction as they are formed by natural events that create patterns in statistically random ways. Idealised fractals on the other hand are formed by the repeated iteration of simple sequences.</p><p>Whilst Mandlebrot does not claim that any coastline or border actually has fractional dimension he shows that Richardsons law is compatible with the idea that geographic shapes such as coastlines can be modelled by random self-similar figures of fractional dimension i.e. Coastlines are inherently fractal in nature.</p><p>This is how the simple question of “How long is the Coast of Britain?” and the Coastline Paradox informed some of Mandlebrot’s earliest thinking on fractals and formed the basis of his linking of mathematical objects to natural forms, an overriding theme of the rest of his life’s work.</p><h4>Reference:</h4><p>How long is the Coast of Britain? Statistical Self-Similarity and the Fractal Dimension, Benoit Mandlebrot. <a href="https://science.sciencemag.org/content/156/3775/636">https://science.sciencemag.org/content/156/3775/636</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3adee92b65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-coastline-paradox-de3adee92b65">The Coastline Paradox</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the most remote buildings in Britain.]]></title>
            <link>https://medium.com/swlh/finding-the-most-remote-buildings-in-britain-8437cf29717d?source=rss-514380d23687------2</link>
            <guid isPermaLink="false">https://medium.com/p/8437cf29717d</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgis]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Simon Wrigley]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 16:00:37 GMT</pubDate>
            <atom:updated>2019-11-21T12:08:48.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dedM-TqCHzh2s5W6kGrTg.png" /></figure><h4>A geospatial big-data challenge using PostGIS, QGIS and open-source data.</h4><h3>Introduction</h3><p>My passions in life all revolve around the great outdoors. When out hiking, running or mountain biking in the mountains, I’ve always been intrigued when stumbling across incredibly remote buildings, imagining the human stories connected to them and how the buildings came to be part of the landscape.</p><p>I thought it would be interesting to combine this with my work interests as a GIS Developer to find out where the most remote buildings in Britain are, using Open Source tools &amp; datasets.</p><blockquote>Remote<br>/rɪˈməʊt/<br><em>adjective<br>1. </em>(of a place) situated far from the main centres of population; distant.</blockquote><p>For the rest of the article, I will walk you through how I chose to go about the challenge.</p><h3>The data:</h3><h4>Building data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Jx2EwPNVhmlFozo-vJ8HA.png" /><figcaption>Ordnance Survey buiding dataset (left) and Open Street Map building dataset (right)</figcaption></figure><p>The <a href="https://www.ordnancesurvey.co.uk/">Ordnance Survey</a> is the UK’s national mapping agency and they provide some of the most comprehensive geospatial data available. They have a fantastic <a href="https://www.ordnancesurvey.co.uk/opendatadownload/products.html">open-data portal</a> full of great datasets. We are going to make use of the building dataset available as part of their OS Open Map — Local product. At the time of writing this dataset contains 14,115,477 individual building polygons!</p><p>The only downside of the OS data from an openness point of view is that a building classification is not available as part of the dataset so you cannot identify what type of building you are looking at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gNcpJdCWjzHXeu7IQzjrQ.png" /><figcaption>Ordanance Survey Building dataset in detail.</figcaption></figure><p>Plotting the building polygons alone results in a beautiful depiction of Great Britain, clearly showing the interplay between topography and the built environment.</p><p>In an attempt to try and compensate for the lack of classification in the OS dataset, I will also make use of the Openstreetmap buildings dataset which is fully open-source. This is so we can discount ruins/sheds etc. from the result set. Whilst Openstreetmap data in general is excellent, it is a lot less comprehensive than the OS data. This difference in data density is clearly visible in the initial image above. The Openstreetmap dataset contains only 7,475,147 building polygons (~40% fewer than the OS dataset), hence not using it as the principle dataset.</p><h4>Boundary data:</h4><p>In order to set the bounds of the analysis, I extracted the UK coastline from a 10m vector dataset from <a href="https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/physical/ne_10m_land.zip">www.naturalearthdata.com</a> — an excellent source of global small-scale vector data.</p><p><em>Links to all datasets used are at the end of the article.</em></p><h3>The Method</h3><p>To analyse data of this scale, it’s advisable use a geodatabase, in this case PostgreSQL with PostGIS. If you are not familiar with PostGIS you should read <a href="https://medium.com/@tjukanov?source=post_page-----9eccd26bc42b----------------------">Topi Tjukanov</a>’s excellent introductory article <a href="https://medium.com/@tjukanov/why-should-you-care-about-postgis-a-gentle-introduction-to-spatial-databases-9eccd26bc42b">here</a>.</p><p>Having downloaded all of the data as .shp files, we can use theshp2pgsql bash script to import the data into a series of Postgres tables (<a href="https://www.bostongis.com/pgsql2shp_shp2pgsql_quickguide.bqg">cheat sheet</a>):</p><ul><li>boundary</li><li>os_buildings</li><li>osm_buildings</li></ul><p>Analysing the spread of geographical data using Nearest Neighbour algorithms can be an expensive calculation to complete, as you are calculating the distance between an object of interest and all surrounding objects. It is clearly not feasible (nor sensible) to do this at a large scale (especially not for 14 million buildings!). Therefore, the first step we can take is to significantly reduce our input dataset in a sensible way to minimise calculation time.</p><h4>Data reduction</h4><p>To reduce the dataset, we are going to first create a grid covering Great Britain. The building datasets can then be binned into each grid cell allowing us to calculate a building count for each cell. We can then discount any cell where building count &gt; cutoff value from any further analysis.</p><p>I created a 5km hexagon grid (Why not, hexagons are awesome!?) using the excellent QGIS plugin — MMQGIS. The choice of grid dimension was fairly arbitrary however you don’t want to make the grid cells too large, otherwise all cells will contain too many buildings. Make the grid cells too small however and it will significantly increase the computational cost of intersecting the building dataset with the grid.</p><p>The grid was then trimmed to the boundary of the UK using a spatial intersection:</p><pre><strong>SELECT</strong> * <strong>FROM</strong> hex_grid <strong>JOIN</strong> boundary <br><strong>ON</strong> ST_Intersects(boundary.geom, hex_grid.geom);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAizuALxYmTa50g3du0b7Q.png" /><figcaption>5km Hexagon grid covering Great Britain.</figcaption></figure><p>With a trimmed grid, it is now possible to do a building count for each polygon. To further reduce the dataset (and speed up calculations) I first generated the centroid point of each building polygon. This reduces the number of nodes from ≥ 4 per building (depending on the building complexity) to one point per building. GIST spatial indexes were then created for all tables:</p><pre><strong>CREATE INDEX</strong> index_name <strong>ON</strong> table_name <strong>USING</strong> GIST(geom);</pre><p>The grid table was then updated to add a column to hold the building count for each cell. This could then be populated using the following code:</p><pre><strong>WITH</strong> building_count <strong>AS</strong><br>  (<strong>SELECT</strong> t.id <strong>AS</strong> id,<br>          count(*) <strong>AS</strong> total<br>   <strong>FROM</strong> os_buildings_centroid os,<br>        trimmed_grid t<br>   <strong>WHERE</strong> ST_Intersects(t.geom, os.geom)<br>   <strong>GROUP</strong> <strong>BY</strong> t.id)<br><strong>UPDATE</strong> trimmed_grid<br><strong>SET</strong> os_building_count = building_count.total<br><strong>FROM</strong> building_count<br><strong>WHERE</strong> trimmed_grid.id = building_count.id;</pre><p>Firstly a <a href="https://www.postgresql.org/docs/9.1/queries-with.html">CTE</a> is used to calculate the building count of each grid cell, followed by an UPDATE statement to assign the building count to each cell of the grid. This binned 14,115,477 building centroids into 8,973 grid cells in 43.9 seconds, resulting in the following map, plotted using QGIS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPXMW6Rx0EjletSI790dLw.png" /><figcaption>Building count grid.</figcaption></figure><p>The grid map clearly highlights all of the major population centres of the UK alongside some of the more remote areas. Along with just how densely populated the South of England is, another feature that particularly stands out is the Scottish Central Belt linking Edinburgh and Glasgow — This area contains over 70% of Scotlands population.</p><p>The real insights in our hunt for remoteness however come when we highlight the extremes — grid cells with ≤ 1 building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEm1OUfZlkaXEF_g0EtnsQ.png" /><figcaption>Red grid cells containing one building or less.</figcaption></figure><p>The majority of wilderness where there are no buildings can be found in Scotland however there are some other notable exceptions; Dartmoor in the far South West, and a couple of grid cells in Wales and the Peak District. The map also makes you realise how densely populated the rest of the country is.</p><p>The next step in finding the most remote buildings was to merge all grid cells with ≤1 buildings to form clusters. The largest single cluster of grid cells will then contain the most remote buildings.</p><pre><strong>CREATE</strong> <strong>TABLE</strong> grid_clusters <strong>AS</strong><br><strong>SELECT</strong> ST_Union(geom) <strong>AS</strong> geom<br><strong>FROM</strong> trimmed_grid<br><strong>WHERE</strong> building_count &lt;=1;</pre><p>The area of each cluster can then be calculated using:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> grid_clusters <strong>ADD</strong> <strong>COLUMN</strong> area double precision;</pre><pre><strong>UPDATE</strong> grid_clusters<br><strong>SET</strong> area = ST_Area(geom);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3xmW5WICKIg32WYQrzzoA.png" /><figcaption>Clustered grid cells with ≤ 1 building, coloured by area (darker = larger).</figcaption></figure><p>If we zoom in on the largest two clusters over the Cairngorm Mountain Range, you can clearly see the the linear building clusters following the main valleys with Aviemore and Kingussie in the centre, Ballater to the East and Pitlochry to the South.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtsW61hUMH36tTTtaQo-6g.png" /><figcaption>The two largest clusters of grid cells with ≤ 1 building.</figcaption></figure><p>In order to find which buildings are the most remote, we need to also capture the buildings surrounding these areas with ≤ 1 building so we can calculate the distance to surrounding buildings. To do this, I buffered the two largest clusters by 1000m and then did another UNION of the original grid cells which intersected these new buffered areas, giving the following analysis area with the buildings contained within it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXIuqAzcEW51Xh4pVfwNEA.png" /><figcaption>Analysis area containing the remotest buildings &amp; their surrounds.</figcaption></figure><p>This has narrowed down the original input dataset of 14,115,477 buildings to 2,482, a much more manageable dataset, ready for further analysis.</p><h4>Finding the most remote buildings:</h4><p>In order to find the most remote building within this area, there are two methods we can use. For a very quick, visual exploration of the data, we can use the building centroid dataset as seed points to create a <a href="https://en.wikipedia.org/wiki/Voronoi_diagram">Voronoi diagram</a>. The largest Voronoi cell will then give an indication of the most remote building. For a more thorough investigation of the data we can use a Nearest Neighbours calculation.</p><h4>Method 1: Voronoi Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdS6vPV7bA654mS0fbnr2w.png" /><figcaption>Analysis area &amp; Building centroids.</figcaption></figure><p>The following query generates Voronoi cells using the building dataset as seed points, trimming the result to the bounding polygon.</p><pre><strong>CREATE</strong> <strong>TABLE</strong> voronoi <strong>AS</strong><br>  (<strong>WITH</strong> centroids <strong>AS</strong><br>     (<strong>SELECT</strong> ST_Collect(geom) <strong>AS</strong> geom<br>      <strong>FROM</strong> building_centroids ),<br>voronoi <strong>AS</strong><br>(<strong>SELECT</strong> (ST_Dump(ST_VoronoiPolygons(centroids.geom,0))).geom <strong>AS</strong> geom<br>      <strong>FROM</strong> centroids) <br><strong>SELECT</strong> ST_intersection(voronoi.geom, bc.geom)<br>   <strong>FROM</strong> voronoi<br>   <strong>INNER</strong> <strong>JOIN</strong> buffered_clusters bc <strong>ON</strong> ST_intersects(voronoi.geom, bc.geom));</pre><p><em>N.B. The PostGIS function</em> ST_VoronoiPolygons() <em>contains a parameter </em>extend_to <em>which can be used to constrain the result to a bounding box. This only works however, when the bounding box is larger than the default envelope which is the input data extent + 50%.</em></p><p>Calculating the area of each Voronoi cell then gives a visual indication of remoteness, as the larger the cell, the more remote the building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-DtBxZVlGvxvFapBXYhTg.png" /><figcaption>Voronoi Cells coloured by area.</figcaption></figure><p>A Voronoi diagram provides a quick visual assessment as to the remoteness of each building however it is not completely robust and is at best a visual proxy for remoteness. This is because small clusters of buildings which are themselves remote to other buildings, can still result in large Voronoi cells. The figure below shows such a case where there are two buildings very close to one another but a long way from any other building. This results in two large Voronoi cells even though the two buildings are very close together and therefore not individually remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gr8epku6B8i-2lSnG728Pw.png" /><figcaption>Two immediately adjacent buildings that still give rise to large Voronoi cells.</figcaption></figure><p>The PostGIS ST_VoronoiPolygons() function can be parameterised with a tolerance to treat nearby seed points as one, which could be used to class a remote farm as a single building for example however it does not help our search for the most remote individual buildings.</p><h4>Method 2: K-Nearest Neighbours</h4><p>As the dataset has been narrowed to ~2000 points, it is well within the realms of a Nearest Neighbour analysis which can be used to provide an objective, accurate measure of the distance to every buildings closest neighbour without using large amounts of compute. To do this, the following query was constructed, taking inspiration from the examples in the documentation <a href="https://postgis.net/workshops/postgis-intro/knn.html">here</a>:</p><pre><strong>SELECT</strong> a.id, a.geom, st_distance(a.geom, b.geom) <strong>AS</strong> dist<br><strong>FROM</strong> building_centroids a<br><strong>CROSS JOIN LATERAL</strong>(<strong>SELECT</strong> * <strong>FROM</strong> building_centroids b <br><strong>WHERE</strong> a.id != b.id<br><strong>ORDER</strong> <strong>BY</strong> a.geom &lt;-&gt; b.geom <br><strong>LIMIT</strong> 1) <strong>AS</strong> b<br><strong>ORDER</strong> <strong>BY</strong> dist desc<br><strong>LIMIT</strong> 3;</pre><p>This works by:</p><ul><li>Calculating the distance between every point in the dataset (dist)</li><li>Using a CROSS JOIN LATERAL to join the building centroid dataset to itself. This lets Postgres iterate over the records returned by the first query, giving the sub-query access to that record.</li><li>The sub-query then removes any direct self joins, orders the results by distance, and returns only the distance for each point to it’s nearest neighbour.</li><li>Finally, the full result set is ordered by distance from largest to smallest, returning only the top 3.</li></ul><p>This has the end result of returning the three buildings with the greatest distance to their nearest neighbour, or more succinctly, the three most remote buildings in the entire dataset — voila!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHq_0NYbstI2UUQiHEM81Q.png" /><figcaption>The three most remote buildings in Britain, shown with the straight line distance in metres to the next closest building.</figcaption></figure><p>Interestingly, both the nearest neighbour analysis and the Voronoi diagram do highlight the same three points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7wzvm8dEkgryJXSIRxjrQ.png" /><figcaption>The three most remote buildings in Britain, shown with the distance in metres to their nearest neighbour.</figcaption></figure><p>The three most remote buildings are all <a href="https://www.mountainbothies.org.uk/">mountain bothies</a> hidden deep in the Cairngorm mountain range — simple buildings, maintained to provide free shelter for walkers and climbers in wild, mountainous areas. They are often historic farm buildings or shepherds huts which would otherwise have fallen to ruin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*GMkIxc26M52fisOG.jpg" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Corrour_Bothy_-_geograph.org.uk_-_1546559.jpg">Corrour Bothy</a>.</figcaption></figure><p>Traditionally, although you can find the buildings marked on Ordnance Survey maps, bothy locations were never published. The only way of finding their location was by it being passed on by word of mouth. Therefore, to continue this spirit, I am not going to identify which bothies are shown on the map above. There is already plenty of information available online now if you wish to go and stay in one yourself! In some ways it is surprising that the most remote building in Britain is only 7.3km straight-line distance to it’s nearest neighbour but it gives you an idea of just how densely populated an island it is.</p><p>It would be interesting to repeat this exercise for other countries with similar open data. If you feel inspired to try, do let me know how you get on and please feel free to ask any questions about the workflow I’ve outlined in this article.</p><p>Thank you to the Ordnance Survey for making such great datasets available with an open source license.</p><h3>Datasets used:</h3><ul><li>Ordnance Survey Open Map Local Building Polygons: — <a href="https://www.ordnancesurvey.co.uk/opendatadownload/products.html">https://www.ordnancesurvey.co.uk/opendatadownload/products.html</a></li><li>OpenStreetMap Building Polygons: — <a href="http://download.geofabrik.de/europe/great-britain.html">http://download.geofabrik.de/europe/great-britain.html</a></li><li>Natural Earth land polygon data: — <a href="https://www.naturalearthdata.com/downloads/10m-physical-vectors/">https://www.naturalearthdata.com/downloads/10m-physical-vectors/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8437cf29717d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/finding-the-most-remote-buildings-in-britain-8437cf29717d">Finding the most remote buildings in Britain.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>