Capstone: Soil Carbon and Cropland of Every Great Plains County
This capstone combines the whole chapter in one workflow at a scale that needs it. For each of the 225 counties of Colorado, Kansas, New Mexico and Wyoming it asks: how much of the county is cropland, and how much organic carbon do its soils hold? Answering takes 21 billion pixels of the 2025 10 m Cropland Data Layer, 12 covariate rasters of 262 million pixels each, a machine learning model of soil carbon predicted for every 90 m pixel, zonal statistics, and spatial statistics of the county results. Every step runs out of core or on the GPU through geolattice.distributed, the pipeline is timed stage by stage, and the results are written as GeoParquet and a Cloud-Optimized GeoTIFF.
Overview
The question
Soil organic carbon (SOC) is the largest terrestrial store of carbon and a measure of soil health. Cultivation usually lowers it, while climate and vegetation set its overall level: wetter, cooler and greener places hold more. A county-level picture of SOC next to cropland share is the kind of summary that carbon accounting, conservation programmes and soil health initiatives start from, and it needs exactly the operations of this chapter.
spatial cross-validation, XGBoost on CPU and GPU (09)
561 rows
4. SOC map
12 covariates, 90 m
chunked prediction (09), COG output (02)
262 million pixels
5. County summaries
SOC map, covariates
zonal statistics (05)
225 zones x 4 rasters
6. Spatial patterns
county table
weights, Moran’s I, LISA, G* (06)
225 counties
What counts as done
The final products are a county GeoParquet file with cropland areas, mean predicted SOC, climate and terrain summaries and hot spot statistics; a SOC map as a COG; and a timing table showing where the time went.
The Capstone with GeoLattice
All stages use the functions of the previous notebooks: dd.cdl, dd.gp_raster and dd.gp_stack (lazy readers, grids aligned), pdist.raster.map_tiles, pdist.zonal_stats, pdist.extract_values, pdist.ml.fit, pdist.ml.predict_raster, pdist.write_raster, pdist.analysis.weights, morans_i, local_morans, getis_ord_local and pdist.vector.sjoin. The GPU is used where notebooks 03 to 09 showed it pays off (model prediction, zonal partial sums); I/O-bound stages stay on the CPU.
Learning objectives
Plan a multi-stage spatial pipeline and choose CPU or GPU per stage from earlier measurements.
Summarize 21 billion 10 m pixels by county out of core.
Build, validate and apply a soil carbon model to 262 million pixels.
Combine raster and vector results into a county table and analyse its spatial patterns.
Time each stage and write analysis-ready outputs.
Data
Dataset
Content
2025 CDL
10 m crop codes, Great Plains window of 154,776 x 137,219 pixels
Great Plains covariates
12 continuous 90 m rasters, aligned to the elevation grid
Great Plains SOC samples
570 points, kg m-2
Great Plains counties and states
225 counties, 4 states (EPSG:5070)
Outputs go to outputs/capstone/: counties_soc_cropland.parquet and soc_map_cog.tif.
Contents
Setup
Stage 1: cropland by county from the 10 m CDL
Stage 2: the training table
Stage 3: a validated soil carbon model
Stage 4: the soil carbon map
Stage 5: county summaries
Stage 6: spatial patterns
Outputs and the time budget
Summary and exercises
Setup
Code
import warnings # warning controlwarnings.filterwarnings("ignore") # hide routine library warningsimport os # environment and CPU countimport time # wall-clock timingfrom pathlib import Path # file pathsimport matplotlib.pyplot as plt # figuresimport numpy as np # arraysimport pandas as pd # tablesimport geopandas as gpd # vector dataimport xarray as xr # labelled rastersimport geolattice # GeoLatticeimport geolattice.distributed as pdist # distributed and GPU spatial computingimport dist_data as dd # chapter helper: paths, cached downloads, timersplt.rcParams.update({"figure.dpi": 110}) # figure resolutionpd.set_option("display.width", 140) # wider printed tablesOUT = Path("outputs") # results and scratch files written by this chapterOUT.mkdir(exist_ok=True) # create it if neededcaps = pdist.capabilities() # engines and GPUs on this machineprint("GeoLattice", geolattice.__version__, "|", os.cpu_count(), "CPU cores |", caps["gpus"], "GPU(s)", # versionsf"({caps.get('gpu_memory_total', 0) /1e9:.0f} GB)"if caps["gpus"] else"") # GPU memoryimport dask # Dask configurationfrom sklearn.cluster import KMeans # spatial blocks for cross-validationfrom sklearn.metrics import r2_score, mean_squared_error # accuracyCAP = OUT /"capstone"# outputs of this notebookCAP.mkdir(parents=True, exist_ok=True) # create the folderbudget = {} # seconds per stagegpu ="gpu"if caps["gpus"] else"cpu"# where GPU stages runcounties = dd.gp_counties() # 225 countiesprint(f"{len(counties)} counties; GPU stages run on: {gpu}") # setup
GeoLattice 0.3.49 | 24 CPU cores | 1 GPU(s) (17 GB)
225 counties; GPU stages run on: gpu
Stage 1: cropland by county from the 10 m CDL
A lazy three-band flag raster (all cropland, wheat, corn) is built from the CDL with lookup tables, and pdist.zonal_stats sums it within each county (notebook 05). Reading and decompressing 21 billion pixels is CPU work, so this stage runs on the CPU.
Code
gp = counties.total_bounds # extent of the countiescdl = dd.cdl(chunks={"y": 4096, "x": 4096}).sel(x=slice(gp[0], gp[2]), y=slice(gp[3], gp[1])) # lazy 10 m window; 4096 chunks bound memory (notebook 05)luts = {} # lookup table per flagfor band, groups in [("crop", dd.CROP_GROUPS), ("wheat", ["Wheat"]), ("corn", ["Corn"])]: # three flags lut = np.zeros(256, np.float32) # 0 elsewherefor gname in groups: # codes of the groups lut[dd.CDL_GROUPS[gname]] =1.0# 1 for them lut[0] = np.nan # no data luts[band] = lut # keepflags = xr.concat([pdist.raster.map_tiles(cdl, lambda b, xp, l=l: xp.asarray(l)[b], dtype="float32", compute="cpu") # one band per flagfor l in luts.values()], dim="band").assign_coords(band=list(luts)) # (3, y, x)with dd.PeakMemory() as pm: # watch memory t0 = time.perf_counter() # start crop = pdist.zonal_stats(counties[["FIPS", "geometry"]], flags, stats=["count", "sum"], compute="cpu") # one pass budget["1 cropland by county (21 billion pixels)"] = time.perf_counter() - t0 # timekm2 =100/1e6# one 10 m pixel in km2counties["mapped_km2"] = crop["count_crop"].values * km2 # mapped landfor band in luts: # areas counties[f"{band}_km2"] = crop[f"sum_{band}"].values * km2 # km2 of each flagcounties["crop_share"] = counties.crop_km2 / counties.mapped_km2 # cropland shareprint(f"{budget['1 cropland by county (21 billion pixels)'] /60:.1f} min, peak memory {pm.peak_gb:.1f} GB; "# time and memoryf"cropland {counties.crop_km2.sum():,.0f} km2 ({counties.crop_km2.sum() / counties.mapped_km2.sum():.1%} of the land)") # totals
6.4 min, peak memory 23.4 GB; cropland 117,687 km2 (11.2% of the land)
Stage 2: the training table
The 12 covariates are aligned to the elevation grid by dd.gp_stack (notebook 02 found the files on five slightly different grids) and extracted at the 570 sampling points.
Code
t0 = time.perf_counter() # startstack = dd.gp_stack() # lazy (12, y, x)soc = dd.gp_points() # 570 pointstable = pdist.extract_values(soc, stack, name="v") # covariates at the pointstable = table.rename(columns=lambda c: c[2:] if c.startswith("v_") else c).dropna(subset=dd.PREDICTORS) # complete rowsX = table[dd.PREDICTORS].to_numpy(np.float32) # predictorsy = np.log(table.SOC.to_numpy()) # log SOCbudget["2 training table"] = time.perf_counter() - t0 # timeprint(f"{len(table)} samples; SOC median {np.median(table.SOC):.2f} kg m-2, range {table.SOC.min():.2f} to {table.SOC.max():.2f}") # summary
561 samples; SOC median 4.73 kg m-2, range 0.15 to 30.47
Stage 3: a validated soil carbon model
XGBoost with spatial cross-validation (5 blocks of the sample coordinates), then a final fit on all samples. Training 561 rows is quick on either target; the GPU model is used because stage 4 predicts on the GPU.
Code
t0 = time.perf_counter() # startparams =dict(n_estimators=400, learning_rate=0.03, max_depth=4, subsample=0.8, colsample_bytree=0.8) # settings from notebook 09blocks = KMeans(5, random_state=0, n_init=10).fit_predict(np.column_stack([table.geometry.x, table.geometry.y])) # spatial blockspred = np.empty_like(y) # held-out predictionsfor b inrange(5): # each block m = pdist.ml.fit("xgb", X[blocks != b], y[blocks != b], task="regression", compute=gpu, **params) # fit without it pred[blocks == b] = np.asarray(m.predict(X[blocks == b])).ravel() # predict itmodel = pdist.ml.fit("xgb", X, y, task="regression", compute=gpu, **params) # final model on all samplesbudget["3 model and spatial cross-validation"] = time.perf_counter() - t0 # timeprint(f"spatial CV: R2 {r2_score(y, pred):.2f}, RMSE {mean_squared_error(y, pred) **0.5:.2f} (log units); engine {model.geolattice_engine}") # accuracy
pdist.ml.predict_raster predicts every pixel chunk by chunk; the map is back-transformed to kg m-2 and written as a COG.
Code
t0 = time.perf_counter() # startlog_map = pdist.ml.predict_raster(model, stack) # lazy (y, x) log SOCsoc_map = np.exp(log_map).astype("float32").rename("soc").rio.write_crs(5070) # kg m-2, still lazysoc_map = soc_map.compute() # predict once and keep the 1 GB map in memory for stages 4 and 5budget["4a predict 262 million pixels"] = time.perf_counter() - t0 # timet0 = time.perf_counter() # startpdist.write_raster(soc_map.chunk({"y": 2048, "x": 2048}), CAP /"soc_map_cog.tif", format="cog") # Cloud-Optimized GeoTIFFbudget["4b write the map as a COG"] = time.perf_counter() - t0 # timeprint(f"predicted pixels: {int(np.isfinite(soc_map.values).sum()):,}; COG {(CAP /'soc_map_cog.tif').stat().st_size /1e6:.0f} MB") # outputs
predicted pixels: 123,333,752; COG 568 MB
Stage 5: county summaries
Mean predicted SOC, NDVI, precipitation, temperature and slope per county, in one zonal pass over a five-band stack. Zone labels are burned per chunk and partial statistics combined (notebook 05); the partial sums run on the GPU.
Code
t0 = time.perf_counter() # startcov = dd.gp_stack(["ndvi", "preci", "temp", "slope"]) # four covariates, lazyfive = xr.concat([soc_map.chunk({"y": 2048, "x": 2048}).expand_dims(band=["soc"]), cov], dim="band") # SOC plus four covariateszs = pdist.zonal_stats(counties[["FIPS", "geometry"]], five, stats=["mean"], compute=gpu) # county meansfor b in five.band.values: # copy the columns counties[f"{b}_mean"] = zs[f"mean_{b}"].values # county meancounties["soc_Tg"] = counties.soc_mean * counties.area /1e9# total SOC stock, teragrams (kg m-2 x m2 / 1e9)budget["5 county zonal statistics (5 rasters)"] = time.perf_counter() - t0 # timecounties[["county", "state", "crop_share", "soc_mean", "ndvi_mean", "preci_mean", "temp_mean"]].describe().round(2) # overview
Is county SOC spatially clustered, and does cropland share explain it once climate is accounted for? Queen weights, Moran’s I, LISA and G* (notebook 06) on the county means, then a simple regression of county SOC on cropland share, precipitation and temperature.
Code
t0 = time.perf_counter() # startw = pdist.analysis.weights(counties, "queen") # queen contiguitymi = pdist.analysis.morans_i(counties.soc_mean.values, w, permutations=999, seed=0, compute=gpu) # globallisa = pdist.analysis.local_morans(counties.soc_mean.values, w, permutations=999, seed=0, compute=gpu) # localgstar = pdist.analysis.getis_ord_local(counties.soc_mean.values, w) # hot spotscounties["lisa_q"] = np.where(lisa.p_sim <0.05, lisa.q.map({1: "HH", 2: "LH", 3: "LL", 4: "HL"}), "ns") # significant quadrantscounties["gstar_z"] = gstar.Zs.values # z-scoresZ = np.column_stack([np.ones(len(counties)), counties.crop_share, counties.preci_mean /100, counties.temp_mean]) # design matrixbeta, *_ = np.linalg.lstsq(Z, counties.soc_mean.values, rcond=None) # least squaresfit = Z @ beta # fitted valuesresid = counties.soc_mean.values - fit # residualsmi_res = pdist.analysis.morans_i(resid, w, permutations=999, seed=0) # are residuals still clustered?budget["6 spatial statistics and regression"] = time.perf_counter() - t0 # timeprint(f"Moran's I of county SOC {mi.statistic:.2f} (p_sim {mi.p_sim:.3f}); LISA clusters: {counties.lisa_q.value_counts().to_dict()}") # global and localprint("SOC = {:.2f} + {:.2f} crop share + {:.2f} per 100 mm precipitation + {:.2f} per degree C; R2 {:.2f}".format(*beta, r2_score(counties.soc_mean, fit))) # regressionprint(f"Moran's I of the residuals {mi_res.statistic:.2f} (p_sim {mi_res.p_sim:.3f})") # remaining clustering
Moran's I of county SOC 0.78 (p_sim 0.001); LISA clusters: {'ns': 115, 'HH': 59, 'LL': 51}
SOC = 4.27 + 1.32 crop share + 0.93 per 100 mm precipitation + -0.39 per degree C; R2 0.84
Moran's I of the residuals 0.61 (p_sim 0.001)
County SOC is strongly clustered (Moran’s I about 0.8): a high-high cluster in the wetter east of Kansas and another in the Colorado mountains, low-low clusters across New Mexico and the dry plains of south-eastern Colorado. Precipitation and temperature explain most of the county differences. The regression gives cropland share a positive coefficient, which seems to contradict the expectation that cultivation lowers SOC. It does not: in the Great Plains, cropland is concentrated on the deeper, wetter soils of central and eastern Kansas, and the regression picks up where crops are grown, not what cultivation does to a given soil. The scatter shows it: at the same rainfall, cropland and SOC are hardly related. A county regression cannot separate the two; answering the causal question needs paired comparisons of cultivated and uncultivated soils, or the causal methods of chapter 03. The residuals are still clustered, so a spatial regression model (chapter 05) would be the next step.
Outputs and the time budget
Code
keep = ["FIPS", "county", "state", "mapped_km2", "crop_km2", "wheat_km2", "corn_km2", "crop_share", "soc_mean", "soc_Tg", # columns"ndvi_mean", "preci_mean", "temp_mean", "slope_mean", "lisa_q", "gstar_z", "geometry"] # to keepcounties[keep].to_parquet(CAP /"counties_soc_cropland.parquet") # GeoParquet for GIS and later chaptersprint("wrote", CAP /"counties_soc_cropland.parquet", "and", CAP /"soc_map_cog.tif") # outputstb = pd.Series(budget, name="seconds").to_frame() # time budgettb["share %"] =100* tb.seconds / tb.seconds.sum() # sharesprint(f"total {tb.seconds.sum() /60:.1f} minutes") # totaltb.round(1) # table
wrote outputs/capstone/counties_soc_cropland.parquet and outputs/capstone/soc_map_cog.tif
total 7.0 minutes
seconds
share %
1 cropland by county (21 billion pixels)
384.6
91.3
2 training table
6.6
1.6
3 model and spatial cross-validation
1.7
0.4
4a predict 262 million pixels
10.7
2.5
4b write the map as a COG
11.4
2.7
5 county zonal statistics (5 rasters)
5.9
1.4
6 spatial statistics and regression
0.1
0.0
Code
top = counties.nlargest(10, "soc_Tg")[["county", "state", "soc_mean", "soc_Tg", "crop_share"]] # the largest SOC stocksprint(f"total predicted SOC stock in the 225 counties: {counties.soc_Tg.sum() /1000:.2f} Pg") # totaltop.round(2) # table
total predicted SOC stock in the 225 counties: 5.40 Pg
county
state
soc_mean
soc_Tg
crop_share
71
Park County
WY
7.16
129.33
0.02
146
Teton County
WY
11.31
123.49
0.00
136
Carbon County
WY
5.38
111.04
0.00
129
Fremont County
WY
4.05
97.19
0.02
114
Sublette County
WY
6.69
85.48
0.02
177
Rio Arriba County
NM
5.50
83.91
0.00
90
Lincoln County
WY
7.20
76.35
0.02
161
Gunnison County
CO
8.87
74.91
0.00
138
Campbell County
WY
5.80
72.27
0.02
152
Catron County
NM
3.85
69.00
0.00
Summary and exercises
One pipeline joined every part of the chapter: an out-of-core pass over 21 billion CDL pixels, aligned covariate stacks, a spatially validated model, a 262 million pixel prediction, zonal statistics on CPU and GPU, and spatial statistics of the county table.
Reading and decompressing the 10 m CDL dominated the time budget; that stage is I/O-bound and stays on the CPU, while the GPU took over the prediction and the zonal partial sums.
County SOC was strongly clustered: high in the wetter east and the mountains, low on the warm, dry southern plains. A regression on cropland share, precipitation and temperature explained most of it (R2 about 0.8). Its positive cropland coefficient reflects where crops are grown, not an effect of cultivation, and its residuals remained clustered, so a spatial model (chapter 05) would be the next step.
The results are analysis-ready: a county GeoParquet file and a COG of the SOC map.
Exercises
Run the whole notebook with gpu = "cpu" and compare the time budget stage by stage.
Replace cropland share with wheat share and corn share in the regression. Which crop is associated with lower SOC after accounting for climate?
Add the prediction uncertainty: fit 10 models on bootstrap samples, predict the map with each, and compute the county mean of the standard deviation.
Extend the cropland stage to the whole of Nebraska and South Dakota (the CDL is national) and compare their cropland shares with Kansas.
Option B for further work
The outline of this chapter also proposed a Bangladesh flood exposure capstone: Microsoft building footprints of Bangladesh (from the same Planetary Computer collection as the Kansas buildings), the Sentinel-1 char land flood maps of the remote sensing capstone, a partitioned spatial join of buildings to flooded areas, zonal counts per upazila, HDBSCAN settlement clusters and network distance to the nearest road. Every step uses functions shown in notebooks 02 to 07.