Skip to content

Instantly share code, notes, and snippets.

@anisotropi4
Last active April 4, 2021 18:16
Show Gist options
  • Save anisotropi4/54c29e6e6192cf758e12279e1981e889 to your computer and use it in GitHub Desktop.
Save anisotropi4/54c29e6e6192cf758e12279e1981e889 to your computer and use it in GitHub Desktop.
Railway Stations in Great Britain
Released license:MIT
height:780
border:no
Railway station locations in Great Britain
Source: National Department for Tranport national public transport access nodes dataset licensed under the Open Government Licence v.3.0.
Source: National Rail Enquiries station codes

Railway Stations in Great Britain

This UK Department for Transport publich the national public transport access nodes (NaPTAN) dataset with a unique identifier and location of every public transport access point in the UK. These scripts download this data and extract railway station locations in Great Britain.

Station CRS codes cross-referenced against National Rail Enquiries station code list are used to create the CRS-mismatch-report.tsv containing mismatched locations.

Creating the datafiles and associate geojson format report

Once the dependencies are met to create the report run:

$ ./prepublish

This will download and create ESRI Shape files in the shp directory for all stations locations, as well as a Leaflet JavaScript visualisation using the this data in a GeoJSON format.

Dependencies

These are environment and project dependencies.

python dependencies

For ease of use manage package python packages dependencies with a local virtual environment venv:

$ virtualenv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

If missing install the python virtualenv package

$ sudo apt install virtualenv

Data License

Uses National Public Transport Access Node (NaPTAN) data under the Open Government Licence Open Street Map data is used under the Open Street Map license

#!/usr/bin/env python3
import json
import geopandas as gp
import pandas as pd
from shapely.geometry import Point
pd.set_option('display.max_columns', None)
DATA = []
def get_point(this_json):
return Point([float(this_json['Place']['Location']['Translation'][k])
for k in ['Longitude', 'Latitude']])
ATCOS = {}
ATCOT = {}
with open('work/StopPoint.jsonl') as fin:
for i in fin:
this_json = json.loads(i)
this_code = this_json['AtcoCode']
ATCO = this_code[:4]
nptg = this_json['Place']['NptgLocalityRef']
if ATCO in ['9200', '9300']:
continue
if ATCO not in ['9100', '9400']:
if nptg not in ATCOS:
ATCOS[nptg] = set()
ATCOS[nptg].add(ATCO)
if 'MainNptgLocalities' in this_json['Place']:
j = this_json['Place']['MainNptgLocalities']['NptgLocalityRef']
for k in j if isinstance(j, list) else [j]:
v = k['value']
if v in ATCOS and ATCO in ATCOS[v]:
continue
if v not in ATCOT:
ATCOT[v] = set()
ATCOT[v].add(ATCO)
else:
output_json = {}
output_json['Name'] = this_json['Descriptor']['CommonName']
output_json['Status'] = this_json['Status']
output_json['Type'] = this_json['StopClassification']['StopType']
output_json['Station_Name'] = output_json['Name']
if 'OffStreet' in this_json['StopClassification']:
output_json['TIPLOC'] = this_json['StopClassification']['OffStreet']['Rail']['AnnotatedRailRef']['TiplocRef']
output_json['CRS'] = this_json['StopClassification']['OffStreet']['Rail']['AnnotatedRailRef']['CrsRef']
output_json['Station_Name'] = this_json['StopClassification']['OffStreet']['Rail']['AnnotatedRailRef']['StationName']
if 'xml:lang' in output_json['Station_Name']:
output_json['Station_Name'] = output_json['Station_Name']['value']
if 'StopAreas' in this_json:
output_json['StopAreaCode'] = this_json['StopAreas']['StopAreaRef']['value']
output_json['AdministrativeAreaRef'] = this_json['AdministrativeAreaRef']
output_json['code'] = this_code
output_json['NPTG'] = nptg
p = get_point(this_json)
output_json['geometry'] = p
DATA.append(output_json)
CRSDATA = pd.read_csv('station_codes.csv')
CRS = pd.DataFrame(columns=['Station_Name', 'CRS_code'])
for i in range(0, CRSDATA.shape[1], 2):
DF1 = CRSDATA.iloc[:, i:(i+2)]
DF1.columns = ['Station_Name', 'CRS_code']
CRS = CRS.append(DF1).dropna()
CRS = CRS.rename(columns={'Station Name': 'Station_Name', 'CRS Code': 'CRS_code'})
CRS['Rail_Station'] = CRS['Station_Name'] + ' Rail Station'
CRS = CRS.set_index('Rail_Station').drop('Station_Name', axis=1)
STATIONS = gp.GeoDataFrame(DATA)
def get_ATCO(k):
if k in ATCOS and ATCOS[k]:
return list(ATCOS[k])[0][:3]
if k in ATCOT and ATCOT[k]:
return list(ATCOT[k])[0][:3]
return None
STATIONS['ATCO'] = STATIONS['NPTG'].apply(get_ATCO)
STATIONS = STATIONS[STATIONS['Type'].isin(['RLY', 'MET'])]
for k in [' Railway)', ' Rly)', '(RHDR)', '(KESR)', '(Isle of Wight Steam Railway', '(Welsh Highland Rly-Caernarfon)', '(W&LLR)', '(Peak Rail)', '(Battfield Line)']:
n = len(k)
IDX = (STATIONS['Name'].str[-n:] == k)
STATIONS.loc[IDX, 'Type'] = 'HRT'
STATIONS = STATIONS.join(CRS, on='Name').fillna('-')
STATIONS.to_file('shp/Stations.shp', crs='EPSG:4326')
CRS_CODES = set(CRS['CRS_code'])
STATION_CODES = set(STATIONS['CRS'])
MISMATCH = list(CRS_CODES - STATION_CODES)
CRS[CRS['CRS_code'].isin(MISMATCH)].to_csv('CRS-mismatch-report.tsv', sep='\t')
STATIONS.to_file('output-stations.json', crs='EPSG:4326', driver='GeoJSON')
<!DOCTYPE html>
<html>
<head>
<title>Railway Stations in GB</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Cache-control" content="No-Cache">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico"/>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<script src="http://d3js.org/d3.v5.min.js"></script>
<div id="map" style="width: 1340px; height: 780px"></div>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
var radius = 3;
var weight = 1;
var linewidth = 2;
var log2 = Math.log(2.0);
var minZoom = 3;
var maxZoom = 18;
var map = L.map('map').setView([54.533, -2.53], 6);
L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: maxZoom,
minZoom: minZoom,
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'osm.standard'
}).addTo(map);
d3.json("output-stations.json").then(function(d) {
function get_colour(p) {
var fail = "#ff00ff";
if (p.Type == 'HRT')
return "#0de7d9"
if (p.Type == 'MET')
return "#1ab8e3"
if (p.Status == 'active')
return "#0000ff"
if (p.Status == 'inactive')
return "#00ccff"
return fail;
}
function onEachFeature(feature, layer) {
var this_feature = feature.properties;
var popupContent;
if (this_feature.Name)
popupContent = this_feature.Name;
var lookup = {
"AdministrativeAreaRef": "Admin Area",
"CRS": "CRS",
"Station_Name": "Station Name",
"Status": "Status",
"StopAreaCode": "Area Code",
"TIPLOC": "TIPLOC",
"code": "Atco Code"
}
var k = Object.keys(this_feature).filter(i=>(i != "Name" && i != "geometry" && i != "Type" && i != "is_in" && i != "z_order" && i != "CRS_code"))
for (var i = 0; i < k.length; i++) {
if (k[i] in this_feature) {
popupContent += '<br>' + lookup[k[i]] + ': ' + this_feature[k[i]];
}
}
layer.bindPopup(popupContent);
}
L.geoJSON(d, {
style: function(feature) {
var c = get_colour(feature.properties);
switch (feature.geometry.type) {
case 'Point':
return {
color: c,
radius: radius,
weight: weight,
opacity: 0.8,
fillOpacity: 0.4
};
default:
return {
colour: c,
weight: weight
};
}
},
onEachFeature: onEachFeature,
pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng, {
opacity: 1,
fillOpacity: 0.8
});
}
}).addTo(map);
});
</script>
</body>
</html>
MIT License
Copyright (c) 2020 Will Deakin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment