Open Infrastructure Map, a view of infrastructure data in OpenStreetMap
More chart stuff
Russ Garrettbee65e8c7104
diff --git a/web-backend/charts.py b/web-backend/charts/__init__.pysimilarity index 87%rename from web-backend/charts.pyrename to web-backend/charts/__init__.pyindex 5cdb33a..379f3cd 100644--- a/web-backend/charts.py+++ b/web-backend/charts/__init__.py@@ -1,9 +1,9 @@+from charts.util import result_to_df+from charts.util import figurefrom config import database-from bokeh.plotting import figure as bokeh_figurefrom bokeh.models import ColumnDataSourceimport pandas as pdfrom bokeh.palettes import Category10-import decimalfrom bokeh.models import NumeralTickFormatter, HoverToolfrom bokeh.themes import Theme@@ -31,39 +31,6 @@ theme = Theme(})-# Apply the custom theme globally---def result_to_df(result):- # Convert rows to dictionaries and handle decimal.Decimal conversion- return pd.DataFrame.from_records(- [- dict(- (k, float(v) if isinstance(v, decimal.Decimal) else v)- for k, v in dict(row).items() # Explicitly convert row to a dictionary- )- for row in result- ]- )---def figure(**kwargs):- kwargs = {- "width": 600,- "height": 400,- "sizing_mode": "stretch_width",- "tools": "box_zoom,reset",- **kwargs,- }- fig = bokeh_figure(**kwargs)- fig.toolbar.active_drag = None- fig.toolbar.active_scroll = None- fig.toolbar.active_tap = None- fig.outline_line_width = 0- fig.xgrid.grid_line_color = None- fig.ygrid.grid_line_alpha = 0.5- return fig-async def line_length():data = await database.fetch_all(@@ -165,7 +132,7 @@ async def plant_count():p = figure(x_axis_type="datetime",- title="Power Plants by Type",+ title="Power plant count by source",y_range=(0, pivot_data.sum(axis=1).max() * 1.1),x_range=(pd.to_datetime("2014-01-01"),@@ -199,7 +166,7 @@ async def plant_output():WHEN source IN ('hydro', 'tidal', 'wave') THEN 'Hydro'ELSE 'Other'END AS type,- SUM(output) / 1e9 AS total_output -- Convert watts to gigawatts+ SUM(count * output) / 1e9 AS total_output -- Convert watts to gigawattsFROM stats.power_plantGROUP BY time, typeORDER BY time"""@@ -216,7 +183,7 @@ async def plant_output():p = figure(x_axis_type="datetime",- title="Power Plants by Output",+ title="Power plant output by source",y_range=(0, pivot_data.sum(axis=1).max() * 1.1),x_range=(pd.to_datetime("2021-01-11"),@@ -257,7 +224,7 @@ async def substation_count():p = figure(x_axis_type="datetime",- title="Substation Count",+ title="Substation count",y_range=(0, data["total_count"].max() * 1.1),x_range=(pd.to_datetime("2014-01-01"),diff --git a/web-backend/charts/country.py b/web-backend/charts/country.pynew file mode 100644index 0000000..5450417--- /dev/null+++ b/web-backend/charts/country.py@@ -0,0 +1,170 @@+from config import database+from bokeh.models import (+ ColumnDataSource,+ NumeralTickFormatter,+ Range1d,+ LinearAxis,+ HoverTool,+)+from charts.util import result_to_df, figure+++async def grid_summary(country_name: str):+ """Generate a Bokeh plot of the length of power lines and the number of substations in a country."""++ data = await database.fetch_all(+ """+ select date_trunc('month', coalesce(pl.time, ss.time)) AS date,+ avg(pl.line_length) AS line_length,+ avg(ss.substation_count) AS substation_count+ FROM+ (select time, sum(length) as line_length from stats.power_line+ WHERE country = :country_name+ group by time) pl+ full outer join (select time, sum(count) as substation_count FROM stats.substation+ WHERE country = :country_name+ group by time) ss+ ON ss.time = pl.time+ group by date_trunc('month', coalesce(pl.time, ss.time))+ order by date_trunc('month', coalesce(pl.time, ss.time))+ """,+ {"country_name": country_name},+ )++ df = result_to_df(data)+ df["line_length"] /= 1000 # Convert to km+ cds = ColumnDataSource(df)++ p = figure(+ x_axis_type="datetime",+ title=f"{country_name}: grid summary",+ y_range=(0, df["line_length"].max() * 1.1),+ )+ p.yaxis.axis_label = "Power Line Length (km)"+ p.yaxis.formatter = NumeralTickFormatter(format="0,0")++ p.extra_y_ranges = {+ "substation_count": Range1d(start=0, end=df["substation_count"].max() * 1.4)+ }++ ax2 = LinearAxis(y_range_name="substation_count", axis_label="Substation Count")+ p.add_layout(ax2, "right")+ ax2.axis_label = "Substation count"+ ax2.formatter = NumeralTickFormatter(format="0,0") # type: ignore++ p.line(+ "date",+ "line_length",+ source=cds,+ legend_label="Power line length",+ color="blue",+ )+ p.scatter("date", "line_length", source=cds, size=4, color="blue")+ p.line(+ "date",+ "substation_count",+ source=cds,+ legend_label="Substation count",+ color="green",+ y_range_name="substation_count",+ )+ p.scatter(+ "date",+ "substation_count",+ source=cds,+ size=4,+ color="green",+ y_range_name="substation_count",+ )++ hover = HoverTool(+ tooltips=[+ ("Month", "@date{%Y-%m}"),+ ("Line length", "@line_length{0,0} km"),+ ("Substation count", "@substation_count{0,0}"),+ ]+ )+ hover.formatters = {"@date": "datetime"}+ p.add_tools(hover)+ p.legend.location = "bottom_right"++ return p+++async def plant_summary(country_name: str):+ """Two-axis plot showing the number of power plants and their total output."""++ data = await database.fetch_all(+ """+ SELECT date_trunc('month', time) AS date,+ avg(count) AS plant_count,+ avg(output) / 1e9 AS total_output -- Convert watts to gigawatts+ FROM (+ SELECT time, SUM(count) AS count, SUM(count * output) AS output+ FROM stats.power_plant+ WHERE country = :country_name+ GROUP BY time+ ) subquery+ GROUP BY date_trunc('month', time)+ ORDER BY date_trunc('month', time)+ """,+ {"country_name": country_name},+ )++ df = result_to_df(data)+ cds = ColumnDataSource(df)++ p = figure(+ x_axis_type="datetime",+ title=f"{country_name}: power plant summary",+ y_range=(0, df["plant_count"].max() * 1.1),+ )+ p.yaxis.axis_label = "Plant Count"+ p.yaxis.formatter = NumeralTickFormatter(format="0,0")++ p.extra_y_ranges = {+ "total_output": Range1d(start=0, end=df["total_output"].max() * 1.2)+ }++ ax2 = LinearAxis(y_range_name="total_output", axis_label="Total Output (GW)")+ p.add_layout(ax2, "right")+ ax2.formatter = NumeralTickFormatter(format="0,0") # type: ignore++ p.line(+ "date",+ "plant_count",+ source=cds,+ legend_label="Count",+ color="blue",+ )+ p.scatter("date", "plant_count", source=cds, size=4, color="blue")+ p.line(+ "date",+ "total_output",+ source=cds,+ legend_label="Output",+ color="green",+ y_range_name="total_output",+ )+ p.scatter(+ "date",+ "total_output",+ source=cds,+ size=4,+ color="green",+ y_range_name="total_output",+ )++ hover = HoverTool(+ tooltips=[+ ("Month", "@date{%Y-%m}"),+ ("Total output", "@total_output{0,0.0} GW"),+ ("Plant count", "@plant_count{0,0}"),+ ]+ )+ hover.formatters = {"@date": "datetime"}+ p.add_tools(hover)++ p.legend.location = "bottom_right"++ return pdiff --git a/web-backend/charts/util.py b/web-backend/charts/util.pynew file mode 100644index 0000000..5204e44--- /dev/null+++ b/web-backend/charts/util.py@@ -0,0 +1,35 @@+from bokeh.plotting import figure as bokeh_figure+import pandas as pd+++import decimal+++def result_to_df(result) -> pd.DataFrame:+ return pd.DataFrame.from_records(+ [+ dict(+ (k, float(v) if isinstance(v, decimal.Decimal) else v)+ for k, v in dict(row).items()+ )+ for row in result+ ]+ )+++def figure(**kwargs):+ kwargs = {+ "width": 600,+ "height": 400,+ "sizing_mode": "stretch_width",+ "tools": "box_zoom,reset",+ **kwargs,+ }+ fig = bokeh_figure(**kwargs)+ fig.toolbar.active_drag = None+ fig.toolbar.active_scroll = None+ fig.toolbar.active_tap = None+ fig.outline_line_width = 0+ fig.xgrid.grid_line_color = None+ fig.ygrid.grid_line_alpha = 0.5+ return figdiff --git a/web-backend/main.py b/web-backend/main.pyindex 36f45aa..703a433 100644--- a/web-backend/main.py+++ b/web-backend/main.py@@ -34,6 +34,7 @@ from data import (get_commons_thumbnail,)import charts+import charts.countryDEBUG = config("DEBUG", cast=bool, default=False)templates = Jinja2Templates(directory="templates")@@ -151,11 +152,10 @@ async def country(request, country):plant_stats = tg.create_task(database.fetch_one(query="""SELECT SUM(convert_power(output)) AS output, COUNT(*)- FROM power_plant- WHERE ST_Contains(- (SELECT ST_Transform(geom, 3857) FROM countries.country_eez where gid = :gid),- geometry)- AND tags -> 'construction:power' IS NULL+ FROM power_plant, countries.country_eez_3857 AS eez+ WHERE ST_Contains(eez.geom, geometry)+ AND eez.gid = :gid+ AND tags -> 'construction:power' IS NULL""",values={"gid": country["gid"]},)@@ -164,11 +164,10 @@ async def country(request, country):plant_source_stats = tg.create_task(database.fetch_all(query="""SELECT first_semi(source) AS source, sum(convert_power(output)) AS output, count(*)- FROM power_plant- WHERE ST_Contains(- (SELECT ST_Transform(geom, 3857) FROM countries.country_eez WHERE gid = :gid),- geometry)- AND tags -> 'construction:power' IS NULL+ FROM power_plant, countries.country_eez_3857 AS eez+ WHERE ST_Contains(eez.geom, geometry)+ AND eez.gid = :gid+ AND tags -> 'construction:power' IS NULLGROUP BY first_semi(source)ORDER BY SUM(convert_power(output)) DESC NULLS LAST""",values={"gid": country["gid"]},@@ -176,6 +175,12 @@ async def country(request, country):)power_lines = tg.create_task(stats_power_line(country["union"]))+ grid_summary_chart = tg.create_task(+ charts.country.grid_summary(country["union"])+ )+ plant_summary_chart = tg.create_task(+ charts.country.plant_summary(country["union"])+ )return templates.TemplateResponse("country.html",@@ -185,6 +190,14 @@ async def country(request, country):"plant_stats": plant_stats.result()._mapping,"plant_source_stats": plant_source_stats.result(),"power_lines": power_lines.result(),+ "country_grid_summary": json.dumps(+ json_item(+ grid_summary_chart.result(), "country-grid-summary", charts.theme+ )+ ),+ "plant_summary": json.dumps(+ json_item(plant_summary_chart.result(), "plant-summary", charts.theme)+ ),"canonical": request.url_for("country", country=country["union"]),},)diff --git a/web-backend/templates/charts.html b/web-backend/templates/charts.htmlindex 33dee06..22bbdce 100644--- a/web-backend/templates/charts.html+++ b/web-backend/templates/charts.html@@ -6,13 +6,15 @@<script src="https://cdn.bokeh.org/bokeh/release/bokeh-3.7.0.min.js"crossorigin="anonymous"></script>+<p>Plant data from before 2021-01-11 is backfilled from Taginfo and has no source.+ Granular data was intermittently sampled between 2021 and 2025.</p>+<h3>Lines</h3><div class="chart" id="lines_plot"></div><h3>Plants</h3><div class="chart" id="plants_plot"></div>- <p>Plant data from before 2021-01-11 is backfilled from Taginfo and has no source.- Granular data was intermittently sampled between 2021 and 2025.</p>+<h3>Plant Output</h3><div class="chart" id="output_plot"></div>diff --git a/web-backend/templates/country.html b/web-backend/templates/country.htmlindex 9d9b5f3..7601477 100644--- a/web-backend/templates/country.html+++ b/web-backend/templates/country.html@@ -6,6 +6,9 @@Statistics on the electricity network in {{country|country_name}} from OpenStreetMap.{%- endblock %}{% block content -%}+<script src="https://cdn.bokeh.org/bokeh/release/bokeh-3.7.0.min.js"+ crossorigin="anonymous"></script>+<p><strong>{{country|country_name(true)}}</strong> has{{plant_stats.count}} power plant{%if plant_stats.count != 1 %}s{% endif -%}{%- if plant_stats.output %}@@ -43,7 +46,15 @@ Statistics on the electricity network in {{country|country_name}} from OpenStree<p class="footnote">If multiple sources are listed for a power plant, only the first source is used in this breakdown.</p></div><p><a href="{{url_for('plants_construction_country', country=country)}}">Show plants under construction</a></p>+ <div id="plant-summary"></div>+ <script>+ Bokeh.embed.embed_item({{ plant_summary | safe }}, "plant-summary");+ </script>{% if power_lines.total > 1 %}{{ tables.power_lines_table(power_lines) }}+ <div id="country-grid-summary"></div>+ <script>+ Bokeh.embed.embed_item({{ country_grid_summary | safe }}, "country-grid-summary");+ </script>{% endif %}{% endblock %}