Skip to main content

Data processing pipeline

code/processing/ holds the R pipeline that turns the public raw files in data/raw/ into the four model input CSVs in data/processed/ and the input package in data/packages/. main.R sources the numbered scripts in code/processing/R/ in order; every script starts with rm(list = ls()), reads its inputs from files and writes its outputs to files, so the scripts communicate only through data/interim/ and data/processed/. The header block at the top of each script (Purpose, Reads, Writes, Depends, Notes) is the authoritative description; this page collects those headers. Sources and download links for every raw file are in Raw data sources; the refresh procedure for a new data vintage is in Updating raw data.

How to run

Three equivalent entry points:

  • scripts/run_r_pipeline_unix.sh (Linux, macOS, WSL): runs Rscript main.R from code/processing/ inside the bsat micromamba environment created by scripts/bootstrap_unix.sh (or the devcontainer environment).
  • scripts\run_r_pipeline_windows.bat: the same, using the portable environment under .bsat_local\ created by scripts\bootstrap_windows.bat.
  • Rscript main.R from code/processing/, with R 4.4 or later that has the packages listed in R/00_load_packages.R (nothing is installed; a missing package stops the run with its name). main.R also runs from RStudio (source("main.R")); it sets the working directory to its own folder either way.

Data location. main.R resolves the data root as <repo>/data and stores it in the R option bsat.data_dir; every script reads it with base_dir <- getOption("bsat.data_dir", file.path("..", "..", "data")). To use data kept elsewhere, set the environment variable BSAT_DATA_DIR to a folder that contains raw/; main.R creates interim/ and processed/ under it:

BSAT_DATA_DIR=/path/to/data scripts/run_r_pipeline_unix.sh

A single script can be run on its own after source("R/00_load_packages.R"), with code/processing/ as the working directory (the fallback ../../data then points at the repository data folder) or after options(bsat.data_dir = "...").

Order of execution in main.R: 00 01 10 11 12 20 21 [22] [23] 24 30 40 50 60. Script 50 runs last, right before packaging, so that script 20 computes the expenditure share from the unrepaired quantities of script 12, as the model authors do. Scripts 22 and 23 run only when their raw inputs that are not distributed with the repository are present; otherwise main.R reuses the derived files shipped in data/interim/ (see “Large files and the NTM step”). Script 25 is never sourced (see “Diagnostics”). A full run takes a few minutes; script 23, when it runs, adds several more because it reads the 460 MB BACI file.

What the pipeline produces

data/processed/ (tracked in git) holds the four model inputs, all in the same long schema (region, year, nest, commodity, input, attribute, value, unit, attribute_type, attribute_description, region_name, nest_name, commodity_name):

  • data_targets.csv: baseline levels the model is calibrated to (area, yield, production, imports, exports, consumption, stocks, feed use by livestock product) for 42 regions, 12 commodities and the crop years 2025 to 2034.
  • data_exogenous.csv: levels of the exogenous drivers: calibrated elasticities and productivity parameters, international prices, population and GDP per capita, import tariffs and export taxes, non-tariff measures, land cost shares (phi_f), livestock inventory and slaughter, and unit price normalizations.
  • data_shocks.csv: a zero-filled scaffold of the ten shock attributes for every region, commodity and year. Editing it defines a counterfactual scenario.
  • data_params_init.csv: initial values of the seven commodity-level elasticities.

data/packages/baseline_2025_Input.zip (tracked) bundles the four CSVs plus a METADATA.csv in the Input/ layout the model runner reads (Package and file format). Because the shocks are neutral, running the model on it reproduces the USDA baseline.

data/interim/ (regenerated by every run; untracked except the five derived files that replace raw inputs not distributed with the repository, see “Large files and the NTM step”) holds the intermediate files listed under each script below, including harmonization_log.csv, which records every market-year with a nonzero consumption or supply-demand residual and what script 50 did with it.

Scripts

00_load_packages.R

  • Purpose: check that every package the pipeline uses is installed and attach it; nothing is installed. Sourced first by main.R; later scripts clear objects but keep the attached packages. A missing or broken package stops the run with its name.
  • Reads: none.
  • Writes: none.
  • Depends: dplyr, tidyr, stringr, readr, readxl, openxlsx, zip, data.table, lfe, ggplot2 (from setup/environment.yml)
  • Notes: stringr, data.table and ggplot2 are loaded but no numbered script currently calls them; lfe is used only by 23.

01_check_region_commodity_coverage.R

  • Purpose: expand the region-commodity list of the USDA baseline to the full region x commodity grid and flag the pairs the baseline does not cover.
  • Reads: raw/region_commodity_list_2025.xlsx (sheet Sheet1, columns region, commodity).
  • Writes: interim/region_commodity_coverage.csv.
  • Notes: audit only; no later script reads the output.

10_read_baseline_data.R

  • Purpose: read the commodity sheets of the USDA International Long-Term Projections workbook and reshape them into one long table (commodity x region x year) holding the baseline variables.
  • Reads: raw/2025 International Long-Term Projections to 2034.xlsx (one sheet per commodity); raw/region_commodity_list_2025.xlsx (region order within each sheet).
  • Writes: interim/baseline_projections_long.csv.
  • Notes: the workbook name is the constant baseline_data. The sheet layout is hard-coded: region blocks are 25 rows apart and 21 rows tall, starting at row 9 (Poultry) or row 7 (other commodities); the number and meaning of the columns per commodity group is fixed in the script; the regions of a sheet are those of the region list, in order, followed by World. The string -- marks missing values; crop years such as 2025/26 keep the first year.

11_compute_feed_use_decomposition.R

  • Purpose: split each region’s total feed use of every feed crop across beef, pork and poultry in proportion to FAOSTAT livestock value-of-production shares.
  • Reads: raw/mapping.csv; raw/FAOSTAT_total_livestock_value_constant_IntlD.csv; raw/FAOSTAT_each_livestock_value_constant_IntlD.csv; interim/baseline_projections_long.csv.
  • Writes: interim/livestock_value_shares.xlsx; interim/feed_use_decomposition.xlsx.
  • Notes: feed use of a crop is feed_only + ind_feed_other + feed_seed_waste for Barley, Corn, Sorghum, Soybeans, Soybean meal, Soybean oil and Wheat, and is split by the 2015 value shares. A missing value share is read as no demand. Myanmar is recoded MMR to BUR. Only group A regions and years from 2025 are kept.

12_generate_data_targets.R

  • Purpose: build data_targets.csv from the long baseline table and the feed-use decomposition.
  • Reads: interim/baseline_projections_long.csv; interim/feed_use_decomposition.xlsx; raw/mapping.csv; raw/baseline_units.csv.
  • Writes: processed/data_targets.csv (overwritten afterwards by script 50).
  • Notes: lst_obsv_yr <- 2025 is the first year of the analysis period and must equal first_yr in script 30. Commodities are renamed to model codes (Beef, SoyMeal, SoyOil, Soybean) and assigned to nests. A soybean-market consistency check reallocates SoyOil in BGD to OAO and SoyOil and SoyMeal in ECO to ONA when those regions have soy product projections but no soybean market. Quantity attributes are rounded to whole units; yields and extraction rates are not (script 50 re-derives them).

20_compute_ag_expenditure_share.R

  • Purpose: compute the agricultural expenditure share (spending on the twelve modeled commodities as a percentage of real GDP) by region for 2025, and save the annual international price series built along the way.
  • Reads: processed/data_targets.csv; raw/2026-06-19 IMF Commodity Prices external-data.xlsx (sheet External); raw/2026-06-19 International Prices FAO Meat.xlsx (sheet data); raw/2026-06-24 CPI_US.xlsx (sheet Sheet1); raw/Global GDP Shares and GDP Growth Assumptions to 2035.xlsx; raw/mapping.csv.
  • Writes: interim/international_prices_annual.csv (marketing-year averages, native units, all years); interim/ag_expenditure_shares.csv.
  • Notes: IMF series are picked by the code in row 1 (PBARL, PWHEAMT, PCOTTIND, PRICENPQ, PMAIZMT, PSORG, PSOYB, PSMEA, PSOIL); FAO meat prices are simple averages of fixed column positions. Prices are deflated to 2017 USD with CPI_2017 and averaged over USDA marketing years; an incomplete last year uses the last 12 observed months. The GDP workbook is read by column position and its region labels must match the crosswalk in the script. Only 2025 is exported.

21_compute_land_cost_share.R

  • Purpose: compute the land cost share of value added (phi_f) for every region and crop from U.S. per-acre variable costs, relative yields and the USDA international TFP land cost shares.
  • Reads: raw/AgTFPInternational2023.xlsx (sheet Cost Shares); the five workbooks in raw/variable_costs_2025/ matching vc_pattern <- "to 2035"; raw/mapping.csv; interim/baseline_projections_long.csv.
  • Writes: interim/variable_costs_us_2025.csv; interim/region_commodity_land_cost_shares.csv.
  • Notes: the EUR land share is hard-coded at 0.113. Cost workbooks are parsed by row label (Table ... U.S. <crop>, Item, Variable costs of production, Per acre). Land rents solve a one-equation root-finding problem per region and year; shares are winsorized at the 5th and 95th percentiles within each year. Years from 2025 are exported.

22_compute_tariff_ave.R

  • Purpose: compute region-commodity ad valorem import tariffs (simple average of WITS MFN tariffs, latest reported year per product) and a zero export-tax scaffold.
  • Reads: raw/trade_barriers/tariff_ave_WITS_2023.csv (not distributed); raw/trade_barriers/country_code_WITS.xlsx; raw/mapping.csv.
  • Writes: interim/tariff_ave_region.csv; interim/export_taxes_comm_reg.csv (both tracked in git as the shipped derived products).
  • Notes: sourced by main.R only when the WITS 2023 extract is present; otherwise the two shipped outputs are reused. HS codes are mapped to commodities by fixed 4- and 6-digit lists. Missing tariffs are set to 0 (with the current data: all of Iraq, Saudi Arabia pork, Pakistan soybean oil). The EU is one reporter (EUN). Export taxes are not observed and are 0 everywhere. The year column of the tariff output is the string 2023 (or last observed).

23_compute_NTM_ave.R

  • Purpose: estimate a model of non-tariff-measure ad valorem equivalents (AVE) on tariffs, GDP per capita and agricultural imports with region x product fixed effects, impute missing AVEs, and aggregate them into GDP-weighted region-commodity import NTMs; export NTMs are a zero scaffold.
  • Reads: under raw/trade_barriers/: ave_hs_importer.csv, BACI_HS92_Y2014_V202401b.csv (not distributed), country_codes_V202401b.csv, ag_hs_products.csv (not distributed), ag_tariff_USA_2014.xls (not distributed, optional), tariff_ave_2014_WITS.csv (not distributed), country_code_WITS.xlsx, country_region_WB.xlsx; under raw/: current_GDPpc_2014_WB.csv, current_GDP_2014_WB.csv, current_GDPpc_IMF.xls, current_GDP_IMF.xls, mapping.csv; interim/commodity_hs6_mapping.csv when the WTO schedule is absent.
  • Writes: interim/model_estimates.RData; interim/NTM_regression_results.csv and interim/NTM_regression_table.tex (regression coefficients, standard errors and fit statistics, as CSV and as a LaTeX table for the paper); interim/NTM_ave_imputed.RData; interim/NTM_IMP_ave_region.csv; interim/NTM_EXP_ave_region.csv; interim/commodity_hs6_mapping.csv (rewritten only when the WTO schedule is present).
  • Notes: sourced by main.R only when BACI_HS92_Y2014_V202401b.csv, tariff_ave_2014_WITS.csv and ag_hs_products.csv are all present; otherwise the two shipped NTM outputs are reused. The commodity-to-HS6 mapping is rebuilt from ag_tariff_USA_2014.xls when that file is present and read from the shipped interim/commodity_hs6_mapping.csv otherwise. Regression: ave ~ AVE_Tariff + AVE_Tariff_ag + log_GDPpc + log_total_imp_ag | region_geo:product_id (felm). Negative imputations are set to 0; gaps for Barley, Sorghum, Soybeans and Wheat take the country’s Corn, Rice and Cotton average; Iraq takes its geographic-region average. All inputs refer to 2014.

24_generate_data_exogenous.R

  • Purpose: assemble data_exogenous.csv from the calibrated parameters, 2025 international prices, population and GDP per capita, unit price normalizations, livestock inventory and slaughter, and the interim results of scripts 20 to 23.
  • Reads: raw/exogenous_data.csv; raw/mapping.csv; raw/population_WB_2025.xls; raw/population_IMF_WEO_2025.csv; raw/Current_GDP_WB_2025.xls; raw/Current_GDP_IMF_WEO_2025.csv; raw/FAOSTAT_Livestock_Inventory_2024.csv; raw/FAOSTAT_Slaughtered Livestock_2024.csv; interim/international_prices_annual.csv; interim/ag_expenditure_shares.csv; interim/region_commodity_land_cost_shares.csv; interim/tariff_ave_region.csv; interim/export_taxes_comm_reg.csv; interim/NTM_IMP_ave_region.csv; interim/NTM_EXP_ave_region.csv.
  • Writes: processed/data_exogenous.csv.
  • Notes: prices, population and GDP use 2025; livestock inventory and slaughter use FAOSTAT year 2024. The IMF WEO files supply Taiwan only. Prices become million 2017 USD per 1,000 native units (cotton: 1,000 480-lb bales). baseline_units.csv is declared as an input but not read.

30_generate_data_shocks.R

  • Purpose: generate data_shocks.csv, a zero-filled scaffold of every shock attribute for each region, commodity and year of the analysis period.
  • Reads: raw/mapping.csv.
  • Writes: processed/data_shocks.csv.
  • Notes: first_yr <- 2025 and last_yr <- 2034 define the horizon; keep first_yr equal to lst_obsv_yr in script 12. Ten shock attributes: four trade barriers (all commodities), TFP value added and land productivity (crops), TFP feed use (livestock), TFP intermediates (SoyMeal, SoyOil), and two region-level shocks (ag expenditure share, land supply). Two attribute names contain spaces.

40_generate_data_params_init.R

  • Purpose: generate data_params_init.csv, the initial values of the seven commodity-level substitution and transformation elasticities.
  • Reads: none.
  • Writes: processed/data_params_init.csv.
  • Notes: values are hard-coded in the script: sigma_d 3.8, sigma_f 1.1, sigma_c 5, sigma_l 0.25, sigma_z 0.5, sigma_w 3.8, omega_s 5; 42 rows.

50_harmonize_targets.R

  • Purpose: apply to the rounded targets of script 12 the same three adjustments the model would make on its own, in the model’s order, so that the model finds no residual to repair.
  • Reads: processed/data_targets.csv.
  • Writes: processed/data_targets.csv (overwritten); interim/harmonization_log.csv (columns region, year, commodity, check, residual, adjusted, delta, status).
  • Notes: the three adjustments, in order. (a) A consumption residual (total consumption less food consumption, feed to livestock, other feed and crushing) within plus or minus 2 is added to the largest of those components, the first maximum in that order; when the largest is feed to livestock or other feed, the rows are left alone and the residual is left to the model (status left to the model: feed component): the model repairs it in its internal feed totals but reports feed consumption from the unrepaired target, so an untouched row is what reproduces its output. (b) A supply-demand residual within plus or minus 2 is subtracted from the largest of beginning stocks, production and imports, the first maximum in that order. (c) Yields are derived as production over area (cotton via 217.728111162486 kg per bale) and extraction rates as 100 times production over soybean crushing, both from the adjusted values. A residual outside plus or minus 2 is left alone, logged with a status containing outside the model's ±2 window and warned about; the model then refuses that year. With these adjustments the model’s run on the package gives the same solution as its run on the unharmonized targets (the regression test checks this against the model authors’ own package), and the neutral run reproduces every target exactly. Inspect the log after every run.

60_build_input_package.R

  • Purpose: bundle the four processed CSV files and a METADATA.csv into the standard model input package (a zip with an Input/ folder) specified in Package and file format.
  • Reads: the four files in processed/.
  • Writes: packages/baseline_<first year>_Input.zip, where the first year is the smallest year in data_targets.csv (currently baseline_2025_Input.zip).
  • Notes: METADATA.csv records author, description, comments and the build timestamp. An existing zip with the same name is replaced.

Large files and the NTM step

Five inputs of scripts 22 and 23 are not distributed with the repository (they are listed in .gitignore), all under data/raw/trade_barriers/:

  • BACI_HS92_Y2014_V202401b.csv (CEPII BACI, HS92, release 202401b, 2014 file; about 460 MB, too large for git).
  • tariff_ave_2014_WITS.csv (World Bank WITS, 2014 applied tariff ad valorem equivalents; about 245 MB, too large for git).
  • tariff_ave_WITS_2023.csv (WITS, MFN applied tariffs, 2023 or last observed; UNCTAD TRAINS terms).
  • ag_hs_products.csv (WITS product group WTO_HS_Aggri; UNCTAD TRAINS terms).
  • ag_tariff_USA_2014.xls (WTO Tariff and Trade Data, United States applied MFN schedule 2014; WTO terms).

In their place the repository tracks the derived products in data/interim/: tariff_ave_region.csv and export_taxes_comm_reg.csv (outputs of script 22), commodity_hs6_mapping.csv (the commodity-to-HS6 mapping that script 23 derives from the WTO schedule, 67 HS6 codes), and NTM_IMP_ave_region.csv and NTM_EXP_ave_region.csv (outputs of script 23, shipped the same way). The rest of data/interim/ stays untracked.

scripts/fetch_large_raw_data.sh (and scripts\fetch_large_raw_data.bat) reports which of the five files is present. With --download it fetches the BACI archive from CEPII (about 2.4 GB, resumable) and extracts only the 2014 file. The WITS and WTO files cannot be downloaded by a script: it prints how to obtain them (WITS Advanced Query, TRAINS, all reporters, all partners, all HS6 products, year 2014 or 2023, AVE of applied tariff, CSV export; the WTO_HS_Aggri product group as CSV; the WTO export of the United States applied MFN schedule for 2014) and the names to save them under. Terms of use and the exact query settings are in Raw data sources.

main.R decides at run time what to do with scripts 22 and 23:

  1. Script 22 is sourced when tariff_ave_WITS_2023.csv exists; it regenerates interim/tariff_ave_region.csv and interim/export_taxes_comm_reg.csv. Otherwise, if both derived files exist, main.R prints 22_compute_tariff_ave: SKIPPED (WITS 2023 extract absent) and script 24 reads them as they are. If neither is available, main.R stops with a message naming the missing file.
  2. Script 23 is sourced when BACI_HS92_Y2014_V202401b.csv, tariff_ave_2014_WITS.csv and ag_hs_products.csv all exist; it regenerates interim/NTM_IMP_ave_region.csv, interim/NTM_EXP_ave_region.csv, interim/model_estimates.RData and interim/NTM_ave_imputed.RData. Otherwise, if interim/NTM_IMP_ave_region.csv and interim/NTM_EXP_ave_region.csv both exist, main.R prints 23_compute_NTM_ave: SKIPPED (large raw files absent) and script 24 reads them as they are. If neither is available, main.R stops with a message naming the missing files, and scripts 24, 30, 40 and 50 do not run.
  3. Inside script 23, the WTO schedule ag_tariff_USA_2014.xls is optional: when present, the commodity-to-HS6 mapping is rebuilt from it and interim/commodity_hs6_mapping.csv is rewritten; when absent, the shipped mapping is read and a message says so. The script stops only if both are missing.

A fresh clone therefore runs end to end from the tracked files alone, skipping scripts 22 and 23. The five raw files are needed only to rebuild the derived products, for instance after a change to the tariff mapping or the NTM imputation.

Diagnostics

R/25_compare_actual_imputed_NTM.R checks the quality of the NTM imputation in script 23. It is not sourced by main.R. It reads interim/NTM_ave_imputed.RData and writes to data/outputs/diagnostics/ (created if needed):

  • actual_vs_imputed_AVE.pdf: scatter plot of actual against imputed AVE for the country-commodity pairs that have both, with a fitted line, its slope and the number of observations.
  • NTM_AVE_diagnostics.xlsx: one sheet of metadata and four sheets listing the pairs whose AVE could not be imputed, those with no actual AVE, those where a missing actual AVE received a positive imputation, and those where the imputation failed (missing or negative).

Run it manually after script 23 has run (it therefore needs the raw files of script 23 that are not distributed), from code/processing/:

Rscript -e 'source("R/00_load_packages.R"); source("R/25_compare_actual_imputed_NTM.R")'

Set options(bsat.data_dir = "...") before the second source() if the data live outside <repo>/data.