Note
Go to the end to download the full example code.
Group mapped PV farms and test an area-capacity model#
Convert raw OSM features into geometry, remove duplicate representations, group nearby installations and attach historical settlement context. Keep generator-group area separate from whole-plant land and landscape extent.
Calibrate the model form in Dunnett et al. (2020) using the authors’ original, anonymised Wiki Solar join table. Spain is completely withheld from calibration. The graph reports country-transfer error, not in-sample fit. Source capacities are reported MW without an AC/DC declaration.
The historical profile uses the archived script’s 400 m point / 800 m polygon grouping settings. Its polygon-area proxy can include site land; it must not be substituted for pixel-derived module area. The approximate prediction interval omits mapping error and geographic domain shift. The substantial held-out errors are part of the result.
GHSL uses epoch 2015, release R2023A, at native 1 km resolution. This later edition differs from the paper’s R2019A input. Here farm centroids are sampled, rather than taking the original feature-centroid majority. These classifications describe historical settlement context, not the land use at the image date.
Run with orbital-pv[ground,examples] and the companion _data folder.
All data are bundled, real snapshots with checksums. OSM © contributors,
ODbL; GHSL © European Union; calibration archive CC0. See _data/README.txt.
directory = Path(__file__).resolve().parent if "__file__" in globals() else Path.cwd()
data = directory / "_data"
inventories = {}
for name in ("cestas", "rengo", "tenerife"):
mapped = opv.osm_pv_features(json.loads((data / f"{name}-osm.json").read_text()))
farms = opv.cluster_pv_farms(mapped, profile="dunnett2020")
settlement = opv.load_settlement_raster(data / f"{name}-ghsl.tif")
inventories[name] = opv.classify_pv_farms(farms, settlement)
rows = [
{"site": name, **feature["properties"]}
for name, inventory in inventories.items()
for feature in inventory["features"]
]
table = pd.DataFrame(rows)
pprint(
table[
["site", "source_feature_count", "panel_area_m2", "osm_polygon_area_m2", "urban"]
].to_dict("records")
)
[{'osm_polygon_area_m2': 2504941.537143598,
'panel_area_m2': 2134170.0316084796,
'site': 'cestas',
'source_feature_count': 23,
'urban': False},
{'osm_polygon_area_m2': 247168.382482318,
'panel_area_m2': nan,
'site': 'rengo',
'source_feature_count': 1,
'urban': False},
{'osm_polygon_area_m2': 40714.6171751925,
'panel_area_m2': 16730.813126087724,
'site': 'tenerife',
'source_feature_count': 52,
'urban': False}]
Rinconada has no mapped generator-group area. A missing area is not zero.
fig, ax = plt.subplots(figsize=(9, 4.8), layout="constrained")
x = np.arange(len(table))
for shift, key, label, color in (
(-0.2, "panel_area_m2", "Mapped generator-group area", "#149c95"),
(0.2, "osm_polygon_area_m2", "Union of mapped polygon land", "#526f9a"),
):
values = table[key].to_numpy(dtype=float) / 10000
bars = ax.bar(x + shift, values, 0.4, label=label, color=color)
ax.bar_label(
bars,
labels=[f"{v:.2f}" if np.isfinite(v) else "Unavailable" for v in values],
padding=3,
fontsize=9,
)
for position in np.flatnonzero(~np.isfinite(values)):
ax.text(x[position] + shift, 0.65, "Unavailable", ha="center", va="bottom", fontsize=8)
ax.set(
xticks=x,
xticklabels=table.site,
yscale="log",
ylim=(0.5, 800),
ylabel="Area [ha, log scale]",
title="Area provenance prevents double counting",
)
ax.legend()
fig.supxlabel("© OpenStreetMap contributors (ODbL) · Snapshot 30 October 2026", fontsize=8)
plt.show()

csv = data / "wiki_solar_join.csv"
metadata = json.loads(csv.with_suffix(".csv.meta.json").read_text())
assert hashlib.sha256(csv.read_bytes()).hexdigest() == metadata["sha256"]
reference = pd.read_csv(csv)
training = reference[reference.GID_0 != "ESP"]
held_out = reference[reference.GID_0 == "ESP"]
model = opv.fit_pv_capacity_model(
training["panel.area"].to_numpy() * 1e6,
training.power.to_numpy(),
urban=training.urban.astype(bool).tolist(),
capacity_basis="reported",
area_basis="osm_polygon_proxy",
source="Dunnett2020 Figshare v2 Wiki Solar; Spain withheld",
)
prediction = model.predict(
held_out["panel.area"].to_numpy() * 1e6,
urban=held_out.urban.astype(bool).tolist(),
area_basis="osm_polygon_proxy",
)
metrics = opv.evaluate_pv_capacity(held_out.power.to_numpy(), prediction)
pprint(metrics, sort_dicts=False)
{'n_total': 159,
'n_evaluated': 158,
'n_withheld': 1,
'n_extrapolated': 1,
'rmse_mw': 13.1261248663146,
'mae_mw': 8.492859331324697,
'bias_mw': 7.969652026399075,
'r2': 0.23218520324239988,
'interval_coverage': 0.9873417721518988,
'nominal_confidence': 0.95,
'capacity_basis': 'reported',
'area_basis': 'osm_polygon_proxy'}
valid = prediction.eligible
observed, estimated = held_out.power.to_numpy()[valid], prediction.mean_mw[valid]
fig, axes = plt.subplots(1, 2, figsize=(11, 4.8), layout="constrained")
axes[0].scatter(observed, estimated, s=24, alpha=0.7, color="#526f9a")
maximum = max(observed.max(), estimated.max()) * 1.05
axes[0].plot([0, maximum], [0, maximum], "--", color="#555555", label="Exact agreement")
axes[0].set(
xlabel="Reported capacity [MW]",
ylabel="Estimated capacity [MW]",
title=f"Spain: {metrics['n_evaluated']} evaluated, {metrics['n_withheld']} withheld",
)
axes[0].legend()
axes[1].hist(estimated - observed, bins=18, color="#149c95", edgecolor="white")
axes[1].axvline(0, color="#555555", linestyle="--")
axes[1].set(
xlabel="Estimate - reported capacity [MW]",
ylabel="Held-out records",
title=f"MAE {metrics['mae_mw']:.2f} MW · RMSE {metrics['rmse_mw']:.2f} MW",
)
fig.suptitle("Country-held-out capacity validation · reported MW, AC/DC unspecified")
fig.supxlabel("Source: Dunnett (2020), Figshare v2 Wiki Solar calibration table · CC0", fontsize=8)
plt.show()

tenerife = opv.estimate_pv_farm_capacity(inventories["tenerife"], model)
pprint([feature["properties"] for feature in tenerife["features"]], sort_dicts=False)
[{'source_ids': ['way/430266023',
'way/430266024',
'way/430266025',
'way/954753485',
'way/954753486',
'way/954753487',
'way/954753488',
'way/954753489',
'way/954753490',
'way/954753491',
'way/954753492',
'way/954753493',
'way/954753494',
'way/954753495',
'way/954753496',
'way/954753497',
'way/954753498',
'way/954753499',
'way/954753500',
'way/954753501',
'way/954753502',
'way/954753503',
'way/954753504',
'way/954753505',
'way/954753506',
'way/954753507',
'way/954753508',
'way/954753509',
'way/954753510',
'way/954753511',
'way/954753512',
'way/954753513',
'way/954753514',
'way/954753515',
'way/954753516',
'way/954753517',
'way/954753518',
'way/954753519',
'way/954753520',
'way/954754219',
'way/954754220',
'way/954754221',
'way/954754222',
'way/954754223',
'way/954754224',
'way/954754225',
'way/954754226',
'way/954754227',
'way/954754228',
'way/954754229',
'way/954754230',
'way/954754231'],
'source_feature_count': 52,
'unique_geometry_role_count': 52,
'is_cluster': True,
'generator_feature_count': 50,
'plant_feature_count': 2,
'point_feature_count': 0,
'panel_area_m2': 16730.813126087724,
'osm_polygon_area_m2': 40714.6171751925,
'plant_area_m2': 40714.61717519251,
'landscape_area_m2': 66961.58672335626,
'capacity_area_m2': 40714.6171751925,
'capacity_area_basis': 'osm_polygon_proxy',
'centroid_lon': -16.443453267628218,
'centroid_lat': 28.195453221961994,
'profile': 'dunnett2020',
'geometry_source': 'grouped source features',
'settlement': {'longitude': -16.443453267628218,
'latitude': 28.195453221961994,
'class_code': 11,
'settlement_class': 'very low density rural',
'urban': False,
'water': False,
'status': 'valid',
'epoch': 2015,
'edition': 'R2023A',
'sampling': 'native cell containing point'},
'urban': False,
'water': False,
'estimated_capacity_mw': 3.086876749767849,
'capacity_lower_mw': 0.0,
'capacity_upper_mw': 48.61252681102637,
'capacity_basis': 'reported',
'capacity_extrapolated': False,
'capacity_estimate_status': 'within_calibration_range'}]
Total running time of the script: (0 minutes 0.710 seconds)