API Reference¶
This section provides automatically generated documentation for the workflow scripts and utility modules.
Core Scripts¶
Model Building and Solving¶
- workflow.scripts.build_model.add_carriers_and_buses(n, crop_list, food_list, residue_feed_items, food_group_list, nutrient_list, nutrient_units, countries, regions, water_regions)[source]¶
Add all carriers and their corresponding buses to the network.
Regional land buses remain per-region.
Crops, residues, foods, food groups, and macronutrients are created per-country.
Primary resources (water) and emissions (co2, ch4, n2o) use global buses.
Fertilizer has a global supply bus with per-country delivery buses.
- workflow.scripts.build_model.add_primary_resources(n, primary_config, region_water_limits, co2_price, ch4_to_co2_factor, n2o_to_co2_factor)[source]¶
Add primary resource components and emissions bookkeeping.
- workflow.scripts.build_model.add_fertilizer_distribution_links(n, countries, synthetic_n2o_factor)[source]¶
Connect the global fertilizer supply bus to country-level fertilizer buses.
- workflow.scripts.build_model.add_regional_crop_production_links(n, crop_list, yields_data, region_to_country, allowed_countries, crop_prices_usd_per_t, luc_lef_lookup=None, residue_lookup=None)[source]¶
Add crop production links per region/resource class and water supply.
Rainfed yields must be present for every crop; irrigated yields are used when provided by the preprocessing pipeline. Output links produce into the same crop bus per country; link names encode supply type (i/r) and resource class.
- Parameters:
- Return type:
- workflow.scripts.build_model.add_grassland_feed_links(n, grassland, land_rainfed, region_to_country, allowed_countries, luc_lef_lookup=None)[source]¶
Add links supplying ruminant feed directly from rainfed land.
- workflow.scripts.build_model.add_spared_land_links(n, land_class_df, luc_lef_lookup)[source]¶
Add optional links to allocate spared land and credit CO2 sinks.
The AGB threshold filtering is now applied directly in the LEF calculation, so this function simply uses the LEF values as provided.
- Parameters:
n (pypsa.Network) – The network to add links to.
land_class_df (pd.DataFrame) – Land area by region/water_supply/resource_class.
luc_lef_lookup (Mapping) – Land-use change emission factors (tCO2/ha/yr) by (region, class, water, use). The spared land LEFs already incorporate AGB threshold filtering.
- Return type:
- workflow.scripts.build_model.add_food_conversion_links(n, food_list, foods, countries, crop_to_fresh_factor, exception_crops, food_to_group, loss_waste)[source]¶
Add links for converting crops to foods via processing pathways.
Pathways can have multiple outputs (e.g., wheat → white flour + bran). Each pathway creates one multi-output Link per country.
- workflow.scripts.build_model.add_feed_supply_links(n, ruminant_categories, ruminant_mapping, monogastric_categories, monogastric_mapping, crop_list, food_list, residue_items, countries)[source]¶
Add links converting crops and foods into categorized feed pools.
Uses pre-computed feed categories and mappings to route items to appropriate feed pools (4 ruminant + 4 monogastric quality classes).
- workflow.scripts.build_model.add_feed_to_animal_product_links(n, animal_products, feed_requirements, ruminant_feed_categories, countries)[source]¶
Add links that convert feed pools into animal products with CH4 emissions.
- Parameters:
n (pypsa.Network) – The network to add links to
animal_products (list) – List of animal product names
feed_requirements (pd.DataFrame) – Feed requirements with columns: product, feed_category, efficiency
ruminant_feed_categories (pd.DataFrame) – Ruminant feed categories with CH4 yields (columns: category, MY_g_CH4_per_kg_DMI)
countries (list) – List of country codes
- Return type:
- workflow.scripts.build_model.add_food_group_buses_and_loads(n, food_group_list, food_groups, food_groups_config, countries, population, *, per_country_equal=None)[source]¶
Add carriers, buses, and loads for food groups defined in the CSV.
Supports min/max/equal per-person-per-day targets per food group. Country-level equality overrides can be supplied via
per_country_equal
.
- workflow.scripts.build_model.add_macronutrient_loads(n, macronutrients_config, countries, population, nutrient_units)[source]¶
Add per-country loads and stores for macronutrient bounds.
- workflow.scripts.build_model.add_food_nutrition_links(n, food_list, foods, food_groups, nutrition, nutrient_units, countries)[source]¶
Add multilinks per country for converting foods to groups and macronutrients.
Byproduct foods (those with group=’byproduct’) are excluded from human consumption.
- workflow.scripts.build_model.add_crop_trade_hubs_and_links(n, trade_config, regions_gdf, countries, crop_list)[source]¶
Add crop trading hubs and connect crop buses via hubs.
- workflow.scripts.build_model.add_animal_product_trade_hubs_and_links(n, trade_config, regions_gdf, countries, animal_product_list)[source]¶
Add trading hubs and links for animal products.
- workflow.scripts.solve_model.rescale_objective(m, target_max_coeff=100000000.0)[source]¶
Scale objective to keep coefficients within numerical comfort zone.
Data Preparation¶
Process UN WPP population data for total and age-specific counts.
Pre-compute health data for SOS2 linearisation in the solver.
- class workflow.scripts.prepare_health_costs.RelativeRiskTable[source]¶
Bases:
Dict
[Tuple
[str
,str
],Dict
[str
,ndarray
]]Container mapping (risk, cause) to exposure grids and log RR values.
- workflow.scripts.prepare_health_costs.main()[source]¶
Main entry point for health cost preparation.
- Return type:
- workflow.scripts.build_regions.cluster_regions(gdf, target_count, allow_cross_border, method='kmeans', random_state=0)[source]¶
Cluster level-1 administrative regions into target_count clusters.
Clustering is based on centroids in a projected CRS (EPSG:3857) for a reasonable Euclidean approximation. When cross-border clustering is not allowed, clustering is performed per country and the per-country targets are allocated proportionally to the number of base regions.
Yield and Land Processing¶
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
- workflow.scripts.aggregate_class_areas.load_scaled_fraction(path, *, target_shape=None, target_transform=None, target_crs=None)[source]¶
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
Water Resources¶
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
- workflow.scripts.build_region_water_availability.compute_month_overlaps(start_day, length_days)[source]¶
Return array of day overlaps per month for given season.
start_day is 1-indexed (GAEZ convention). length_days can exceed 365; values above one year are capped at 365 to avoid infinite wrap.
- workflow.scripts.build_region_water_availability.compute_region_monthly_water(shares, monthly_basin)[source]¶
Utility Modules¶
SPDX-FileCopyrightText: 2025 Koen van Greevenbroek
SPDX-License-Identifier: GPL-3.0-or-later
- workflow.scripts.raster_utils.calculate_all_cell_areas(src, *, repeat=True)[source]¶
Return per-pixel area in hectares for a geographic (lon/lat) raster.
- Parameters:
src (
DatasetReader
) – Raster opened with rasterio, expected in lon/lat coordinates.repeat (
bool
) – When True (default) repeat the per-row areas across columns, yielding a 2D array matching the raster shape. When False, return the 1D per-row areas without repeating, which is useful when the caller can rely on broadcasting to avoid materialising the full 2D matrix.
- Return type:
Visualization Scripts¶
- workflow.scripts.plotting.plot_results.extract_crop_production(n)[source]¶
Extract total crop production aggregated across regions/classes.
Link naming convention from build_model.py: produce_{crop}_{region}_class{resource_class} We aggregate by the {crop} token only.
- workflow.scripts.plotting.plot_results.extract_food_production(n)[source]¶
Extract food production from solved network.
- workflow.scripts.plotting.plot_results.plot_crop_production(crop_production, output_dir)[source]¶
Create bar plot for crop production; always writes a PDF.
- workflow.scripts.plotting.plot_results.plot_resource_usage(n, output_dir)[source]¶
Create bar plot for resource usage; always writes a PDF.
Plot a Plate Carrée map of resource classes by grid cell.
- workflow.scripts.plotting.plot_resource_classes_map.plot_resource_classes_map(classes_path, regions_path, output_path)[source]¶
Plot objective breakdown and visualize health risk factors by region.
- class workflow.scripts.plotting.plot_health_impacts.HealthInputs(risk_breakpoints, cluster_cause, cause_log_breakpoints, cluster_summary, clusters, population, cluster_risk_baseline)[source]¶
Bases:
object
- Parameters:
- risk_breakpoints¶
- cluster_cause¶
- cause_log_breakpoints¶
- cluster_summary¶
- clusters¶
- population¶
- cluster_risk_baseline¶
- __init__(risk_breakpoints, cluster_cause, cause_log_breakpoints, cluster_summary, clusters, population, cluster_risk_baseline)¶
- class workflow.scripts.plotting.plot_health_impacts.HealthResults(cause_costs, risk_costs, intake, cluster_population)[source]¶
Bases:
object
- Parameters:
- cause_costs¶
- risk_costs¶
- intake¶
- cluster_population¶
- workflow.scripts.plotting.plot_health_impacts.compute_health_results(n, inputs, risk_factors, value_per_yll, tmrel_g_per_day, food_groups_df)[source]¶
Compute health costs from optimized network, relative to TMREL intake levels.
- Parameters:
- Return type:
- workflow.scripts.plotting.plot_health_impacts.compute_baseline_risk_costs(inputs, risk_factors, value_per_yll, tmrel_g_per_day, food_groups_df)[source]¶
Compute baseline health costs by risk factor and by cause, relative to TMREL intake levels.
Health costs represent the monetized burden from deviations from optimal (TMREL) intake. Both total costs and individual risk factor contributions are measured relative to TMREL.
- Return type:
- Returns:
(risk_costs_df, cause_costs_df) where risk_costs has columns (cluster, risk_factor, cost) and cause_costs has columns (cluster, cause, cost, log_total, rr_total, coeff).
- Parameters:
- workflow.scripts.plotting.plot_health_impacts.build_cluster_risk_tables(risk_costs_df, cluster_population)[source]¶
- workflow.scripts.plotting.plot_health_impacts.compute_total_health_costs_per_capita(cause_costs, cluster_population)[source]¶
Compute total health costs per capita for each cluster.
The total cost per cluster is the sum across causes (health costs are additive across different health outcomes).
- workflow.scripts.plotting.plot_health_impacts.plot_health_map(gdf, cluster_lookup, per_capita_by_risk, output_path, top_risks, *, diverging=True, value_label='Health cost per capita (USD)', total_per_capita=None)[source]¶
- workflow.scripts.plotting.plot_health_impacts.build_health_region_table(gdf, cluster_lookup, cost_by_risk, per_capita_by_risk)[source]¶
Plot global food consumption by food group per person per day.