Skip to content

Open Infrastructure Map, a view of infrastructure data in OpenStreetMap

Power line stats

Russ Garrett1cbd1ea21c11
diff --git a/data.py b/data.py
index e56590a..ef0c7ee 100644
--- a/data.py
+++ b/data.py
@@ -1,4 +1,8 @@
from config import database
+from itertools import chain
+from more_itertools import windowed
+
+VOLTAGE_SCALE = [0, 10, 25, 52, 132, 220, 330, 550]
async def get_countries():
@@ -8,3 +12,50 @@ async def get_countries():
AND pol_type IN (\'Union EEZ and country\', \'Landlocked country\')
ORDER BY "union" ASC"""
)
+
+
+async def stats_power_line(country=None):
+ stats_date = (await database.fetch_one("SELECT max(time) FROM stats.power_line"))[0]
+ values = {"time": stats_date}
+ country_clause = ""
+
+ if country:
+ country_clause = " AND country = :country"
+ values["country"] = country
+
+ lines = {}
+ for low, high in windowed(chain(VOLTAGE_SCALE, [None]), 2):
+ low = low * 1000
+ query = (
+ "SELECT sum(length) FROM stats.power_line WHERE time = :time AND voltage >= :low"
+ + country_clause
+ )
+ vals = values.copy()
+ vals["low"] = low
+
+ if high is not None:
+ high = high * 1000
+ query += " AND voltage < :high"
+ vals["high"] = high
+
+ res = await database.fetch_one(query, vals)
+ lines[(low, high)] = res[0]
+
+ unspecified = await database.fetch_one(
+ "SELECT sum(length) FROM stats.power_line WHERE time = :time AND voltage IS NULL"
+ + country_clause,
+ values,
+ )
+
+ total = await database.fetch_one(
+ "SELECT sum(length) FROM stats.power_line WHERE time = :time" + country_clause,
+ values,
+ )
+
+ data = {
+ "date": stats_date.date(),
+ "lines": lines,
+ "total": total[0],
+ "unspecified": unspecified[0],
+ }
+ return data
diff --git a/main.py b/main.py
index f60c401..49d0a05 100644
--- a/main.py
+++ b/main.py
@@ -4,17 +4,27 @@ from starlette.templating import Jinja2Templates
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
-from template_functions import format_power, osm_link, country_name
+from template_functions import (
+ format_power,
+ osm_link,
+ country_name,
+ format_length,
+ format_voltage,
+ format_percent,
+)
from config import database, config
from util import cache_for, country_required
from sitemap import sitemap
-from data import get_countries
+from data import get_countries, stats_power_line
DEBUG = config("DEBUG", cast=bool, default=False)
templates = Jinja2Templates(directory="templates")
templates.env.filters["power"] = format_power
+templates.env.filters["distance"] = format_length
+templates.env.filters["voltage"] = format_voltage
+templates.env.filters["percent"] = format_percent
templates.env.filters["country_name"] = country_name
templates.env.globals["osm_link"] = osm_link
@@ -33,7 +43,7 @@ app = Starlette(
@app.route("/")
async def main(request):
# Dummy response - this endpoint is served statically in production from the webpack build
- return PlainTextResponse('')
+ return PlainTextResponse("")
@app.route("/about")
@@ -51,8 +61,14 @@ async def copyright(request):
@app.route("/stats")
@cache_for(86400)
async def stats(request):
+ power_lines = await stats_power_line()
return templates.TemplateResponse(
- "index.html", {"request": request, "countries": await get_countries()}
+ "index.html",
+ {
+ "request": request,
+ "countries": await get_countries(),
+ "power_lines": power_lines,
+ },
)
@@ -83,6 +99,8 @@ async def country(request, country):
values={"gid": country["gid"]},
)
+ power_lines = await stats_power_line(country["union"])
+
return templates.TemplateResponse(
"country.html",
{
@@ -90,6 +108,7 @@ async def country(request, country):
"country": country["union"],
"plant_stats": plant_stats,
"plant_source_stats": plant_source_stats,
+ "power_lines": power_lines
},
)
@@ -115,13 +134,21 @@ async def plants_country(request, country):
)
source = None
- if 'source' in request.query_params:
- source = request.query_params['source'].lower()
- plants = [plant for plant in plants if source in plant['source'].lower().split(';')]
+ if "source" in request.query_params:
+ source = request.query_params["source"].lower()
+ plants = [
+ plant for plant in plants if source in plant["source"].lower().split(";")
+ ]
return templates.TemplateResponse(
"plants_country.html",
- {"request": request, "plants": plants, "country": country["union"], "source": source},
+ {
+ "request": request,
+ "plants": plants,
+ "country": country["union"],
+ "source": source,
+ },
)
+
import wikidata # noqa
diff --git a/poetry.lock b/poetry.lock
index 5de461a..f306dd1 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -139,6 +139,14 @@ category = "main"
optional = false
python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*"
+[[package]]
+name = "more-itertools"
+version = "8.6.0"
+description = "More routines for operating on iterables, beyond itertools"
+category = "main"
+optional = false
+python-versions = ">=3.5"
+
[[package]]
name = "multidict"
version = "5.1.0"
@@ -218,7 +226,7 @@ typing-extensions = {version = ">=3.7.4", markers = "python_version < \"3.8\""}
[metadata]
lock-version = "1.1"
python-versions = ">=3.7"
-content-hash = "b26fa0d8979edc1f9b16cd0419f49fe188b61b4a7df3a08fa9dc265a75a4de90"
+content-hash = "52b37ef1c427e664912cf682f39d840231d20859fb56520f5280582e0fdcc1ba"
[metadata.files]
aiofiles = [
@@ -362,6 +370,10 @@ markupsafe = [
{file = "MarkupSafe-1.1.1-cp38-cp38-win_amd64.whl", hash = "sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be"},
{file = "MarkupSafe-1.1.1.tar.gz", hash = "sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b"},
]
+more-itertools = [
+ {file = "more-itertools-8.6.0.tar.gz", hash = "sha256:b3a9005928e5bed54076e6e549c792b306fddfe72b2d1d22dd63d42d5d3899cf"},
+ {file = "more_itertools-8.6.0-py3-none-any.whl", hash = "sha256:8e1a2a43b2f2727425f2b5839587ae37093f19153dc26c0927d1048ff6557330"},
+]
multidict = [
{file = "multidict-5.1.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:b7993704f1a4b204e71debe6095150d43b2ee6150fa4f44d6d966ec356a8d61f"},
{file = "multidict-5.1.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:9dd6e9b1a913d096ac95d0399bd737e00f2af1e1594a787e00f7975778c8b2bf"},
diff --git a/pyproject.toml b/pyproject.toml
index 71624f9..2b48ab0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,6 +14,7 @@ jinja2 = "^2.11.2"
uvicorn = "^0.12.2"
asgi-sitemaps = "^0.3.2"
aiohttp = "^3.7.3"
+more-itertools = "^8.6.0"
[tool.poetry.dev-dependencies]
diff --git a/static/main.css b/static/main.css
index 62ee096..f8c34d2 100644
--- a/static/main.css
+++ b/static/main.css
@@ -63,13 +63,29 @@ p.footnote {
color: #444;
}
+.table-wrapper {
+ width: max-content;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+.table-wrapper p.footnote {
+ font-size: 0.7em;
+ margin-top: 5px;
+ color: #666;
+}
+
table {
font-size: 0.9em;
margin-top: 8px;
- width: 100%;
table-layout: fixed;
border-collapse: collapse;
border: 1px solid #eee;
+ min-width: 500px;
+}
+
+.table-full-width {
+ width: 100%;
}
caption {
@@ -86,6 +102,11 @@ tbody tr:nth-child(even) {
background-color: #fafafa;
}
+tfoot tr {
+ background-color: #eee;
+ font-weight: bold;
+}
+
th, td {
padding: 4px;
}
diff --git a/template_functions.py b/template_functions.py
index 4ca747b..6b6fab8 100644
--- a/template_functions.py
+++ b/template_functions.py
@@ -4,13 +4,42 @@ from jinja2 import Markup
def format_power(val):
if val is None:
- return ""
+ res = ""
elif val >= 50e6:
- return Markup("{:,.0f}&nbsp;MW".format(val / Decimal(1e6)))
+ res = "{:,.0f}&nbsp;MW".format(val / Decimal(1e6))
elif val >= 1e6:
- return Markup("{:.2f}&nbsp;MW".format(val / Decimal(1e6)))
+ res = "{:.2f}&nbsp;MW".format(val / Decimal(1e6))
else:
- return Markup("{:.0f}&nbsp;kW".format(val / Decimal(1e3)))
+ res = "{:.0f}&nbsp;kW".format(val / Decimal(1e3))
+ return Markup(res)
+
+
+def format_length(val):
+ if val is None:
+ res = ""
+ elif val >= 1000:
+ res = "{:,.0f}&nbsp;km".format(val / Decimal(1e3))
+ else:
+ res = "{:,.0f}&nbsp;m".format(val)
+ return Markup(res)
+
+
+def format_voltage(val):
+ if val is None:
+ res = ""
+ elif val >= 1000:
+ res = "{:,.0f}&nbsp;kV".format(val / Decimal(1e3))
+ else:
+ res = "{:,.0f}&nbsp;V".format(val)
+ return Markup(res)
+
+
+def format_percent(val):
+ if val is None:
+ res = ""
+ else:
+ res = "{:,.1f}%".format(val * 100)
+ return Markup(res)
def osm_link(osm_id, geom_type):
diff --git a/templates/_tables.html b/templates/_tables.html
new file mode 100644
index 0000000..40f25fb
--- /dev/null
+++ b/templates/_tables.html
@@ -0,0 +1,36 @@
+{% macro power_lines_table(power_lines) -%}
+<div class="table-wrapper">
+ <table>
+ <caption>Power Lines</caption>
+ <thead>
+ <tr>
+ <th>Voltage</th>
+ <th>Length</th>
+ <th>Percentage</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for voltages, length in power_lines.lines.items() %}
+ <tr>
+ <td>{{voltages[0]|voltage}} &ndash; {{voltages[1]|voltage}}</td>
+ <td>{{length|distance}}</td>
+ <td>{{(length / power_lines.total)|percent}}</td>
+ </tr>
+ {% endfor %}
+ <tr>
+ <td>No voltage tagged</td>
+ <td>{{power_lines.unspecified|distance}}</td>
+ <td>{{(power_lines.unspecified / power_lines.total)|percent}}</td>
+ </tr>
+ </tbody>
+ <tfoot>
+ <tr>
+ <td>Total</td>
+ <td>{{power_lines.total|distance}}</td>
+ <td>{{1|percent}}</td>
+ </tr>
+ </tfoot>
+ </table>
+ <p class="footnote">Updated {{power_lines.date}}</p>
+</div>
+{%- endmacro %}
diff --git a/templates/country.html b/templates/country.html
index 8b11d1b..39ab54b 100644
--- a/templates/country.html
+++ b/templates/country.html
@@ -1,32 +1,41 @@
{% extends "_base.html" %}
+{% import "_tables.html" as tables %}
{% set breadcrumbs = [('Stats', url_for('stats')), (country, None)] %}
{% block title %}{{country}}{% endblock %}
{% block description -%}
Statistics on the electricity network in {{country|country_name}} from OpenStreetMap.
{%- endblock %}
{% block content -%}
- <p><strong>{{country|country_name(true)}}</strong> has {{plant_stats.count}} power plants totalling {{plant_stats.output|power}} mapped on OpenStreetMap.</p>
+ <p><strong>{{country|country_name(true)}}</strong> has {{plant_stats.count}} power plants totalling {{plant_stats.output|power}} and {{power_lines.total|distance}} of power lines mapped on OpenStreetMap.</p>
- <table>
- <caption>Power plants in {{country|country_name}} by source</caption>
- <thead>
- <tr>
- <th>Source</th>
- <th>Output</th>
- <th>Count</th>
- <tr>
- </thead>
- <tbody>
- {% for row in plant_source_stats %}
- <tr>
- <td><a href="{{url_for('plants_country', country=country)}}?source={{row.source or ''}}">{{row.source or '[unspecified]'}}</a></td>
- <td>{{row.output|power}}</td>
- <td>{{row.count}}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <p><a href="{{url_for('plants_country', country=country)}}">See all plants</a>.</p>
-
- <p class="footnote">If multiple sources are listed for a power plant, only the first source is used in this breakdown.</p>
+ <div class="table-wrapper">
+ <table>
+ <caption>Power plants in {{country|country_name}} by source</caption>
+ <thead>
+ <tr>
+ <th>Source</th>
+ <th>Output</th>
+ <th>Count</th>
+ <tr>
+ </thead>
+ <tbody>
+ {% for row in plant_source_stats %}
+ <tr>
+ <td><a href="{{url_for('plants_country', country=country)}}?source={{row.source or ''}}">{{row.source or '[unspecified]'}}</a></td>
+ <td>{{row.output|power}}</td>
+ <td>{{row.count}}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ <tfoot>
+ <tr>
+ <td><a href="{{url_for('plants_country', country=country)}}">All</a></td>
+ <td>{{plant_stats.output|power}}</td>
+ <td>{{plant_stats.count}}</td>
+ </tr>
+ </tfoot>
+ </table>
+ <p class="footnote">If multiple sources are listed for a power plant, only the first source is used in this breakdown.</p>
+ </div>
+ {{ tables.power_lines_table(power_lines) }}
{% endblock %}
diff --git a/templates/index.html b/templates/index.html
index 55cb4bd..2d32ed0 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -1,9 +1,12 @@
{% extends "_base.html" %}
+{% import "_tables.html" as tables %}
{% set breadcrumbs = [('Stats', None)] %}
{% block description -%}
Statistics on the global electricity network from OpenStreetMap
{%- endblock %}
{% block content -%}
+
+ {{ tables.power_lines_table(power_lines) }}
<p>Select an area to view stats:</p>
<form id="areas-form">
<input list="areas" placeholder="Select area" id="area_select">
diff --git a/templates/plants_country.html b/templates/plants_country.html
index 67883bd..411f4a6 100644
--- a/templates/plants_country.html
+++ b/templates/plants_country.html
@@ -19,7 +19,7 @@
{% if plants|length == 0 %}
<p>There are currently no power plants mapped in {{country|country_name}} on OpenStreetMap.</p>
{% else %}
- <table class="plants-table">
+ <table class="plants-table table-full-width">
<caption>All {{plants|length}} {% if pretty_source %}{{pretty_source}} {% endif %}power plants in {{country|country_name}}</caption>
<thead>
<tr>
@@ -28,12 +28,12 @@
<th>English Name</th>
{% endif %}
<th>Operator</th>
- <th>Output</th>
+ <th style="width: 100px">Output</th>
{% if not pretty_source %}
<th>Source</th>
{% endif %}
<th>Method</th>
- <th>Wikidata</th>
+ <th style="width: 100px">Wikidata</th>
</tr>
</thead>
<tbody>