Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Session 7, land-surface track: soil water in a model of the western United States

🖥️ Model & simulation · 💧 Land water · 💧 Hydrology & land-surface modeling

Updated 14 October, afternoon: more cells where you write the analysis yourself. If you already finished the earlier version, submit it as is.

Guiding question. When and where does soil water in the western United States fall into drought, and how much of that does precipitation alone explain?

Learning outcomes. After this session you can:

  1. Trace a gridded soil-water product back to what was measured, and say what the model added.

  2. Show that a downloaded file is complete and unmodified, and explain why it may differ from an earlier copy.

  3. Read a model grid: axis order, longitude convention, units, missing values, cells that cannot be right.

  4. Tell a real climate extreme from an error in soil-water data.

  5. Measure how data problems bias a drought frequency, and name those that cleaning cannot undo.

  6. Set up drought classification on the grid without leaking test data into training.

  7. Write rules and instructions that let another person, or an AI tool, rerun your chain from the PSL files to the drought frequency, and check whether it did.

Objectives for today. You will:

PartWhat you doRough time (min)
0Predict when the model’s soil bucket is fullest near Spokane3
1Download the Climate Prediction Center (CPC) model output from NOAA and check it11
2Read one model cell near Spokane as a table: limits, a real extreme, an error11
3Read its time series and the frozen-soil gaps of a station’s probes12
4Map the grid and find the cells that cannot be right (if you have time)12
5Hunt five problems planted in a synthetic copy and measure their effect on drought frequency28
6Correlate precipitation with soil water, and test the model against the station12
7Write the steps from raw file to a training table for drought classification12
8Give an AI tool the same synthetic file; start your instructions for it (if you have time)7
Wrap-upThree answers and the summary3

The times are rough estimates of how long each part takes, not a schedule: Parts 0 to 3, 5 to 7 and the wrap-up take about 90 minutes; do Part 4, Q1.2 and Part 8 if you have time. Each question has a self-check and, below it, a hidden worked solution. In the cells marked Your turn you write 2 to 6 lines of the analysis yourself, from a short instruction and a one-line hint; if your code fails or you leave None, the next cells say so and continue with a reference result. The names a worked solution assigns end in _sol (for example t_sol), so running it keeps your own results.

Setup. Work in your own copy (replace UWNETID), opened from book/Chapter2-DataManipulation; do not commit, push or stash.

cd mlgeo-book
git pull
cp book/Chapter2-DataManipulation/lab_s07_land_surface_model.ipynb book/Chapter2-DataManipulation/lab_s07_land_surface_model_UWNETID.ipynb
pixi run jupyter lab

Submit by Friday 16 October, 9:00 (see the end). Completion only: the work does not count toward your grade, but a missing submission costs 10 points.

Not using git pull? Download this track as one zip, lab_s07_land_surface_model.zip, unzip it and open the notebook from the unzipped folder; the start page explains how.

course copies in snapshots
downloads off (offline mode)
your files go to (temporary folder of the book build)/mlgeo_s07_lsm
NetID: not set; Part 5 will use the class seed

Part 0. The system and the question (about 3 min)

What to do: read, run the map, predict.

Soil water is the store between the sky and the rivers: precipitation fills it; evaporation, transpiration, runoff and drainage empty it. Months of low soil water dry out crops and rangeland and lengthen the fire season: agricultural drought. No instrument measures the whole root zone across the West. Satellites (the Soil Moisture and Ocean Salinity mission since 2009, the Soil Moisture Active Passive mission since 2015) see the top 5 cm or so in footprints of about 40 km (NASA; Entekhabi et al., 2010; Kerr et al., 2010). Point sensors, such as the U.S. Climate Reference Network (USCRN) station near Spokane (Part 2), reach a metre deep but sample a few square metres.

So NOAA’s Climate Prediction Center computes soil water with “a one-layer hydrological model (Huang et al., 1996; van den Dool et al, 2003). The model takes observed precipitation and temperature and calculates soil moisture, evaporation and runoff” (CPC). The layer holds at most 760 mm, a 1.6 m column at a porosity of 0.47. Each cell is a leaky bucket (van den Dool et al., 2003):

dWdt=P−E−R−G,\frac{dW}{dt} = P - E - R - G,

with WW the soil water (mm), PP precipitation, EE evaporation (its potential rate computed from air temperature), RR runoff and GG loss to groundwater. The model has no snowpack (Arevalo et al., 2021): snow enters the soil in the month it falls. NOAA’s Physical Sciences Laboratory (PSL) serves the monthly output on a 0.5 degree grid (Fan and van den Dool, 2004).

<Figure size 700x700 with 2 Axes>
Map lines (Natural Earth) cover the Pacific Northwest only; farther south the edge of the coloured cells is the model's coastline.
992 cells with model soil water, 360 months from 1991-01 to 2020-12

Q0. Predict. Near Spokane, winters are wet and summers dry and warm. In which calendar month (1 to 12) is the bucket fullest, on average?

not answered yet
Notebook Cell
       soilw_mm  precip_mm_per_day
month                             
1        239.80               1.59
2        258.65               1.34
3        270.11               1.47
4        272.65               1.19
5        262.28               1.22
6        240.96               0.97
7        200.32               0.37
8        162.29               0.36
9        140.67               0.56
10       143.99               1.15
11       170.31               1.82
12       207.60               1.90
fullest month: 4 | emptiest month: 9
correct

Part 1. Download the raw data and check it (about 11 min)

What to do: start the download, compare with the course copy, native resolution.

1a. Download from the provider

PSL serves soil water and the precipitation that drives the model (PREC/L, CPC’s PRECipitation REConstruction over Land; Chen et al., 2002) as global files from 1948 to last month. PSL’s subset service refused every request while this lab was built, so the cell downloads the whole global files (about 545 MB), checks that each is complete, cuts 31 to 49 N and 235 to 251 E (125 to 109 W) for 1991 to 2020 as the course copy was cut, and deletes the global files. It runs in the background, about 18 minutes at the 0.5 MB/s measured from PSL. On a slow or metered connection, set DOWNLOAD = False.

No download in this run.
'Yours' below is the course copy rewritten by lab.write_grid: it tests that writing is repeatable.
The wrap-up compares your download from PSL with the course copy.

1b. Is your file the same as the course copy?

Four checks tell whether a file was modified or corrupted:

  1. Size in bytes. A truncated file is shorter. A changed value keeps the size: a 32-bit number takes 4 bytes whatever its value.

  2. Counts. Months, latitudes, longitudes, land cells.

  3. First and last records. First and last month, and the soil water at the Spokane cell.

  4. Fingerprint. SHA-256 (Secure Hash Algorithm, 256 bits) turns every byte into 64 characters; one changed byte changes it completely. PSL publishes none, so we compare with the record in snapshots/cpc_soilw_precl_westUS_1991-2020.provenance.json.

A difference is not always damage. PSL appends a month every month, so the whole files’ fingerprints change while 1991-2020 does not: that is why we fingerprint the cut. CPC also reruns the model when the precipitation analysis improves: “Soil moisture calculations will be repeated” (CPC). PSL’s version 2 differs from version 1 “particularly over Africa”.

Loading...
fingerprint in the provenance record: 7c8fda8209cfb8cc5fc4c3181382c64b56c2a8ff7971302b689bc4ec8fcf9d7b
course copy unchanged since then: True

Q1.1 Do your file and the course copy have the same bytes? (True or False.)

not answered yet
Notebook Cell
same fingerprint: True
correct

Q1.2 (if you have time) The next cell adds 0.001 mm to one value in a copy of the course file. Does the size change? The fingerprint?

course copy: 3322416 bytes, 7c8fda8209cfb8cc5fc4c3181382c64b56c2a8ff7971302b689bc4ec8fcf9d7b
demo copy:   3322416 bytes, 097812dea1161dbb3590df4ee811169acb13bad9e545782afe8d35cbeea37c64
not answered yet
Notebook Cell
correct

1c. Native resolution: what was sampled, and what this file delivers

No instrument measured the soil water in this file:

StepWhat samples or computesResolutionSource
Rain gaugesstation precipitation, collected in the Global Historical Climatology Network (GHCN) and the Climate Anomaly Monitoring System (CAMS)a point, read daily, reported as monthly totalsChen et al. (2002): “over 17 000 stations” worldwide
PREC/L analysisoptimal interpolation of the gauges onto a grid0.5 degree, monthly mean rate (mm/day)PSL PREC/L page
Thermometers, GHCN+CAMS analysisstation air temperature interpolated with a lapse-rate adjustment0.5 degree, monthly meanFan and van den Dool (2008)
Leaky-bucket modelone 1.6 m layer, capacity 760 mm, parameters “constant spatially (tuned based on Oklahoma observed runoff data)”0.5 degree cell, monthly forcingCPC explanation page
This filemonthly mean soil water and precipitation, cut to our box0.5 degree, monthlyPSL

Gauges catch less than falls in wind, most of all snow, and stand mostly in valleys, so mountain precipitation is under-sampled. CPC’s page mentions no undercatch correction and lists “orographic adjustment/enhancement” as still to come; both errors pass into the soil water. The model’s time step is not stated in the pages we read (a 2002 CPC abstract by Fan et al.: “operating on monthly data”).

So the file is a derived product: 0.5 degree and one month are the model’s grid and step, not a sensor’s resolution. static holds PREC/L’s count of gauges per cell and month.

Spokane model cell centred at 47.25 N; gauges in it, all 360 months: [0]
<Figure size 1200x450 with 3 Axes>

Q1.3 The north-south and east-west size of the Spokane cell in km (one degree of latitude is about 111.2 km); the mean number of gauges per month in the box’s land cells in 1991-1996 and in 1997-2020 (static["gauges_total"]); is this file raw or derived?

Your turn (1c). Compute q1_cell_km, a tuple (north-south km, east-west km) for the 0.5 degree cell centred at latitude c_lat, and q1_gauges, a tuple (mean gauges per month in 1991-1996, mean in 1997-2020) from static["gauges_total"]. Hint: a degree of longitude is 111.2 km times np.cos(np.deg2rad(c_lat)); static["gauges_total"].to_series() is a pandas Series whose .index.year you can select on.

q1_cell_km: not answered yet
q1_gauges: not answered yet
Notebook Cell
q1_cell_km: correct
q1_gauges: correct
cell at 47.25 N: 55.6 km north-south, 37.7 km east-west, about 2098 km2
gauges per month in the box: 295 (1991-1996), 51 (1997-2020)
not answered yet
Notebook Cell
correct

Part 2. The table: one model cell near Spokane (about 11 min)

What to do: read the table, physical limits, one real extreme and one error.

One row per month at the cell nearest USCRN Spokane 17 SSW (Turnbull National Wildlife Refuge), in lab.TABLE_FILE.

Your turn (2a). Read the table into a pandas DataFrame named t, look at its column types and first rows, and count the missing values in each column into a pandas Series named n_missing. Hint: pd.read_csv(lab.TABLE_FILE); display(t.dtypes) and display(t.head()) show them (in a cell, only the last line shows by itself); t.isna().sum() counts.

not answered yet
Notebook Cell
month                         str
cell_lat                  float64
cell_lon_east             float64
soilw_mm                  float64
precip_mm_per_day         float64
n_gauges                    int64
air_temp_degK             float64
soilw_ltm_1991_2020_mm    float64
dtype: object
Loading...
month                     0
cell_lat                  0
cell_lon_east             0
soilw_mm                  0
precip_mm_per_day         0
n_gauges                  0
air_temp_degK             0
soilw_ltm_1991_2020_mm    0
dtype: int64
correct
Using the reference result so you can continue; compare with yours.
units from the provider's attributes: {'soilw': 'mm', 'precip': 'mm/day'}
long names: {'soilw': 'Model-Calculated Monthly Mean Soil Moisture', 'precip': 'Average Monthly Rate of Precipitation'}

A row is one month over about 56 by 38 km. Units are in the NetCDF (Network Common Data Form) attributes printed above. In the provider’s files, cells that are not model land hold -9.96921e+36, which xarray reads as NaN.

Q2.1 Before looking, write the physical limits for soil water (mm) and for a monthly mean precipitation rate (mm/day), from the model (Part 0) and the climate, not from this cell.

not answered yet
Notebook Cell
soilw_mm: Spokane cell 102.406 to 398.034; whole box 0.000 to 741.667; values outside [0.0, 760.0] in the box: 0
precip_mm_per_day: Spokane cell 0.011 to 3.803; whole box 0.000 to 27.820; values outside [0.0, 60.0] in the box: 0
correct: your limits bracket every value and follow the physics

Q2.2 One real extreme. Find the month with the least soil water at this cell. Real or error? Look at the precipitation before it.

Your turn (2b). Find the row with the least soil water: store its month as a string named driest (“YYYY-MM”) and show that row with the four months before it. Hint: i = t["soilw_mm"].idxmin() gives the row label; display(t.loc[i - 4:i, ["month", "soilw_mm", "precip_mm_per_day"]]) shows the five months.

not answered yet
Notebook Cell
Loading...
correct

Q2.3 One error. The USCRN station’s readme (snapshots/uscrn_daily01_readme.txt, note C) says how missing values are written. Which number stands for a missing soil moisture value? The next cell shows its effect on a monthly mean.

smallest values in the 5 cm column as served: [-9.9e+01  1.1e-02  1.2e-02]
January 2017 mean, codes left in: -99.0 m3/m3
January 2017 mean, codes removed: nan m3/m3 (every day of January 2017 is a code)
Q2.2: not answered yet
Q2.3: not answered yet
Notebook Cell
       month  soilw_mm  precip_mm_per_day  air_temp_degK
137  2002-06   198.773             1.1890         289.84
138  2002-07   158.870             0.1687         294.44
139  2002-08   131.399             0.9128         291.75
140  2002-09   113.104             0.4180         288.22
141  2002-10   102.406             0.3029         280.12
142  2002-11   108.777             1.5995         276.79
Q2.2: correct
Q2.3: correct

Part 3. A 1D array: the time series at the Spokane cell (about 12 min)

What to do: sampling interval and gaps, the series, a real sensor problem in the station’s record, monthly means from daily values.

One value per calendar month and no gaps, but months differ in length: a monthly mean rate times the days gives the total. The bucket’s memory smooths the noise of precipitation.

Q3.1 and your turn (3a). Turn the month column of t into dates (dates, a pandas Series of datetimes); compute the steps between consecutive records in days (steps, a Series) and q3_interval, the (shortest, longest) step; and the precipitation total of each month in mm (precip_total, a Series: the rate times the days in that month). Hint: pd.to_datetime(t["month"]), then dates.diff().dt.days and dates.dt.days_in_month.

not answered yet
q3_interval: not answered yet
Notebook Cell
correct
q3_interval: correct
Using the reference result so you can continue; compare with yours.
<Figure size 1100x550 with 2 Axes>

A real sensor problem: frozen soil. The station’s Stevens Hydra Probe II sensors (5, 10, 20, 50 and 100 cm, three sets) measure the soil’s dielectric permittivity at 50 MHz and convert it to volumetric water content (National Centers for Environmental Information, NCEI). Liquid water has a permittivity near 80 and ice near 3, so frozen soil looks almost dry. The daily value averages the hourly values of the three probes (readme, note J). Look at the winters.

<Figure size 1100x500 with 2 Axes>

Q3.2 and your turn (3b). What percent of days in December to February (2015-2020) have no 5 cm soil moisture value, and what percent in June to August? Store the two as a tuple named q3_frozen. In u, the station’s daily table indexed by date, the missing-value codes are already NaN. Hint: u["SOIL_MOISTURE_5_DAILY"].isna() is True on missing days, the mean of True/False values is a fraction; multiply by 100 for a percent, and u.index.month.isin([12, 1, 2]) selects winter days.

not answered yet
Notebook Cell
correct
missing 5 cm days: 51.8 % in Dec-Feb, 0.0 % in Jun-Aug
median 5 cm soil temperature on missing days: 0.0 degC; on other days: 12.2 degC
days with 5 cm soil at or below 0 degC: 191, of which without a 5 cm value: 191

Your turn (3c). From daily to monthly values, as the model works: sm5_monthly, the monthly mean of the 5 cm soil moisture (a pandas Series, one value per month), and n_valid, the number of days with a value in each month (a Series), which you plot. Hint: u["SOIL_MOISTURE_5_DAILY"].resample("MS").mean(), and .count() in place of .mean().

not answered yet
Notebook Cell
<Figure size 640x480 with 1 Axes>
correct

Part 4. A 2D array: the grid (about 12 min, if you have time)

What to do: axes and their order, the climatology and its seasonal range, a cell that cannot be right.

The grid is a 3D array (time, latitude, longitude); a map of one month is a 2D array.

<xarray.Dataset> Size: 3MB
Dimensions:  (time: 360, lat: 36, lon: 32)
Coordinates:
  * time     (time) datetime64[ns] 3kB 1991-01-01 1991-02-01 ... 2020-12-01
  * lat      (lat) float32 144B 48.75 48.25 47.75 47.25 ... 32.25 31.75 31.25
  * lon      (lon) float32 128B 235.2 235.8 236.2 236.8 ... 249.8 250.2 250.8
Data variables:
    soilw    (time, lat, lon) float32 2MB 596.5 655.6 666.0 ... 116.6 101.1
    precip   (time, lat, lon) float32 2MB 7.939 6.54 4.804 ... 0.255 0.2587
Attributes:
    title:              CPC soil moisture (V2) and PREC/L precipitation, mont...
    source:             NOAA PSL, https://psl.noaa.gov/data/gridded/data.cpcs...
    subset_written_by:  lab_s07_lsm_synthetic.write_grid
first latitudes: [48.75 48.25 47.75] | first longitudes: [235.25 235.75 236.25]
spacing: -0.5 degree in latitude, 0.5 in longitude

Q4.1 Is latitude stored from south to north (“ascending”) or north to south (“descending”)? Give the file’s coordinates (lat, lon in its own convention) of the cell nearest the Spokane station (47.41 N, 117.52 W).

Your turn (4a). Write the order as q4_lat_order, select the soil-water series of the cell nearest the station (cell, an xarray DataArray along time) and store its coordinates as q4_cell = (lat, lon) as stored in the file. The station is at st_lat, st_lon (degrees, negative west). Hint: grid["soilw"].sel(lat=..., lon=..., method="nearest"), with the station longitude converted to 0-360 by st_lon % 360.

Q4.1 order: not answered yet
Q4.1 cell: not answered yet
Notebook Cell
Q4.1 order: correct
Q4.1 cell: correct

Your turn (4b). Compute the 1991-2020 climatology clim, an xarray DataArray of 12 maps (one per calendar month), and its seasonal range srange, one map: at each cell, the largest monthly mean minus the smallest. Hint: group grid["soilw"] by "time.month" and average; then reduce over "month" with .max and .min.

not answered yet
Notebook Cell
correct
Using the reference result so you can continue; compare with yours.
largest difference between our 1991-2020 climatology and the provider's (mm): 0.0
<Figure size 1500x500 with 6 Axes>

Q4.2 Where is the seasonal range largest? A. the Pacific slope from northern California to Washington, west of the Sierra Nevada and the Cascades; B. the Great Basin of Nevada and Utah; C. the deserts of Arizona and southeastern California; D. about the same everywhere.

not answered yet
Notebook Cell
correct

Q4.3 and your turn (4c). Find the land cells whose soil water never exceeds 1 mm in 30 years: smax, the 1991-2020 maximum of each cell as a pandas Series indexed by (lat, lon); bad, the part of smax below 1 mm; and q4_bad_cell, one of them as (lat, lon). Then look at their precipitation and land percent in the worked solution. Hint: grid["soilw"].max("time").to_series(), then boolean selection; bad.index[0] is the first (lat, lon).

not answered yet
Notebook Cell
lat    lon   
42.75  235.25    0.089776
35.25  238.75    0.062272
Name: soilw, dtype: float32
correct
42.75 N, 124.75 W: max soil water 0.090 mm, mean precipitation 4.34 mm/day, land 2 %, missing months 84
35.25 N, 121.25 W: max soil water 0.062 mm, mean precipitation 1.33 mm/day, land 1 %, missing months 84

Part 5. A synthetic twin with planted problems (about 28 min)

What to do: build your twin; (a) list what could go wrong; (b) hunt and record findings; (c) drought frequency three ways; (d) reflect.

The twin has the structure of the real Pacific Northwest grid and a known truth: our own small leaky bucket (not CPC’s code: snow below +2 degC, Thornthwaite (1948) evaporation) run on synthetic weather around each cell’s 1991-2020 climatology, with a dry spell in early 2015, a warm anomaly that year and a warming of 0.02 degC per year. Five problems typical of land-surface products are planted in the forcing, the model run or the file writing; your NetID picks which five of ten kinds, and where.

Twin(netid='', file=lsm_twin_class.csv, 5 planted problems, 14 x 20 cells, 360 months)
Synthetic twin of the CPC soil moisture grid, Pacific Northwest, monthly, January 1991 to December 2020.
Columns: time (first day of the month), lat (degrees north, cell centre), lon (degrees east from 0 to 360,
cell centre), soil_moisture_mm (monthly mean water in a one-layer 1.6 m soil column, holding capacity 760 mm),
precip_mm_per_day (monthly mean precipitation rate from a gauge analysis over land only).
Grid: 0.5 degree. Rows exist where at least one of the two variables has a value.

your file: (temporary folder of the book build)/lsm_twin_class.csv (4.4 MB, 99000 rows)
Loading...

(a) Before you look. List at least three things that could go wrong in a monthly soil-water product: gauges, gridded analysis, model run, file writing.

not answered yet

(b) Hunt. From the summary and one cell below, follow your list: the limits of Q2.1, rows per month, coordinates, the seasonal cycle of each cell, whether soil water answers precipitation in time and place. Record each problem as a finding (variable, first and last month, lat and lon range or None, what is wrong, why it is implausible). A finding counts when variable, months and cells overlap a planted problem; for a whole-record problem, “what” and “why” must name the mechanism. Wet coast, dry inland, the 2015 dry spell and the wettest coastal winters are real structure. A single value far from its cell’s usual range: compare each value with its cell’s mean and standard deviation (d.groupby(["lat", "lon"])["precip_mm_per_day"].transform("std")).

Loading...

Your turn (5b). Three counts that expose problems of file writing. rows_per_month: the number of rows in each month (a pandas Series indexed by time); dups: the rows whose (time, lat, lon) appears more than once (a DataFrame); med: the median soil water over all rows of each month (a Series), which you plot. For some twins the first two counts show nothing wrong; that is a result too. The median plot is where most twins show a problem. Hint: d.groupby("time").size(), d[d.duplicated(["time", "lat", "lon"], keep=False)] and d.groupby("time")["soil_moisture_mm"].median().

not answered yet
Notebook Cell
275    360
Name: count, dtype: int64
months with repeated rows: <ArrowStringArray>
[]
Length: 0, dtype: str
<Figure size 640x480 with 1 Axes>
correct. Now read them against what you expect of a monthly grid
<Figure size 1100x500 with 2 Axes>
not answered yet
not answered yet

(c) Drought frequency, three ways. The percent of cell-months in 2011-2020 below the 20th percentile of the same cell and calendar month in 1991-2010 (20 % of baseline months by construction). Its true value depends on your twin’s weather. Cleaning can move it away from the truth: removing months shortens the baseline, and a forcing error stays in the soil water.

Your turn (5c). Inside my_clean, write one line per finding, each with a comment giving its reason; it returns the cleaned table. Hint: out["lon"] % 360, out.drop_duplicates([...]) and boolean selection such as out[out["time"] >= "1993-01-01"] cover most problems; out.groupby(["lat", "lon"])["soil_moisture_mm"].transform("std") puts each cell’s standard deviation on every row.

drought months 2011-2020: truth 17.2 %, file as received 8.1 %, after your cleaning 8.1 %
my_clean: not answered yet (your cleaning has not changed the drought frequency)
Notebook Cell
drought months 2011-2020: truth 17.2 %, file as received 8.1 %, after your cleaning 5.6 %
distance to the truth: 9.1 points before cleaning, 11.6 after (further). Part (d) asks why.

(d) Reflect. For each problem you found, did it push the drought frequency up or down, and why? Which could cleaning not undo? Which leave it untouched but would harm another use of the file?

not answered yet
Notebook Cell
negative longitudes from 1999-11
8 constant cells, value 760.0
zero month 2017-06
spin-up: first 27 months obvious, drift settles after 28 months: dropped
step in east/west precipitation ratio in 2009: x1.31
The worked solution located 5 of the 5 planted problems.
Nothing missed.
drought months 2011-2020: truth 17.2 %, file 8.1 %, worked cleaning 8.4 %; the cleaning moved the number closer to the truth

Part 6. Correlations on the real data (about 12 min)

What to do: expected sign, correlations with lags, effective sample size, what the correlation means.

Q6.1 What sign do you expect for the correlation between this month’s precipitation and soil water at the Spokane cell?

not answered yet

The traps.

  1. A shared seasonal cycle. Part of the raw correlation is “winter is wetter than summer”. Anomalies remove the calendar-month means.

  2. Lag. A wet month raises the soil water at the end of the month, and the monthly mean only partly. (In nature, snow would add a delay until melt; this model cannot.)

  3. Autocorrelation. Soil water remembers last month; precipitation hardly does. The effective number of independent pairs is about Neff=N (1−rxry)/(1+rxry)N_{\mathrm{eff}} = N\,(1 - r_x r_y)/(1 + r_x r_y), with rxr_x, ryr_y the lag-one autocorrelations of the two anomaly series (Bretherton et al., 1999).

  4. A model driven by precipitation must correlate with it.

Your turn (6a). Compute the anomalies at the Spokane cell: a, a DataFrame with the columns soilw_mm and precip_mm_per_day, each value minus the 1991-2020 mean of its calendar month. Hint: with cols = ["soilw_mm", "precip_mm_per_day"] and cal = pd.to_datetime(t["month"]).dt.month, group t[cols] by cal, use .transform("mean"), then subtract.

not answered yet
Notebook Cell
correct

Q6.2 and your turn (6b). Correlate the soil-water anomaly with the precipitation anomaly 0, 1, 2 and 3 months earlier: r_lead, a list of four Pearson correlations, and q6_lag, the lead with the largest one. Hint: a["precip_mm_per_day"].shift(k) puts the precipitation of k months earlier on each row; a["soilw_mm"].corr(...) skips missing pairs; print(np.round(r_lead, 3)) shows them.

Using the reference result so you can continue; compare with yours.
not answered yet
q6_lag: not answered yet
Notebook Cell
[0.287 0.473 0.424 0.358]
correct
q6_lag: correct

The next cell repeats your calculation for the raw series as well and adds the Spearman rank correlation, which uses only the order of the values.

Loading...

Q6.3 and your turn (6c). NeffN_{\mathrm{eff}} (trap 3) for the anomaly correlation, and for two series that both have the soil’s memory (rxr_x twice): store both as the tuple q6_neff. Hint: a["soilw_mm"].autocorr(1) is the lag-one autocorrelation, and N = len(a).

not answered yet
Notebook Cell
correct
r1 soil 0.94, r1 precipitation 0.12; N = 360, N_eff = 288; with the soil's memory on both sides N_eff = 24

Q6.4 The anomaly correlation measures: A. how strongly rain controls soil water in nature; B. that the model is wrong; C. how strongly the model turns its own precipitation input into soil water, a check of its equations, not independent evidence; D. nothing, because correlation is not causation.

not answered yet
Notebook Cell
q6_sign: correct
q6_meaning: correct

The only independent evidence in this track is the station’s own probes. Three limits: the probes reach 100 cm and the model column 160 cm; a few square metres stand for a cell of about 2100 km² (Q1.3); and a station month needs 20 complete days, so frozen winters drop out (Part 3) and mostly warm-season months remain, where the missing snowpack matters least.

model against station: 59 months, r = 0.72; months in Dec-Feb: 6, in Jun-Aug: 18
<Figure size 1000x350 with 1 Axes>

Part 7. From data to a learning problem (about 12 min)

What to do: your chain of steps in order, the task and the target’s distribution, split and balance.

Q7.1 Write, in order and each with its reason, the steps from the raw provider files to a table a model could learn from: selection of cells and months; what you remove, flag, or keep as a real extreme; aggregation; anomalies; a split by time or space that does not leak; balancing.

not answered yet
Notebook Cell
correct order on three points (a split exists; anomalies, thresholds and balancing come after it). Compare the rest with the worked solution

The task. Regression: emulate the model, predicting soil water (or its anomaly) from precipitation and temperature. Classification: predict drought months (below the 1991-2010 20th percentile of the cell and calendar month), a minority class. The labels on the real grid:

drought months: 20.0 % in 1991-2010, 24.2 % in 2011-2020 (cells with >= 50 % land)
<Figure size 1200x380 with 2 Axes>
anomalies beyond -100 mm: 3.2 %, beyond +100 mm: 4.4 % of land cell-months

Q7.2 and your turn (7a). Which task does the guiding question call for, and what percent of all model land cell-months in 2011-2020 are drought months? Compute that percent as rate_test (a number) from labels, which holds 1 for a drought month, 0 otherwise and NaN off land, and store q7_task = (the task, rate_test). Hint: labels.sel(time=slice("2011", "2020")).mean() skips NaN; float(...) makes it a number; multiply by 100.

not answered yet
Notebook Cell
correct

Balancing. Always answering “no drought” scores about 80 % accuracy and is useless. For classification, split first (by time and blocks of cells), then weight or resample the training rows only, and judge by recall and the precision-recall curve. The 20th percentile is moderate imbalance (4 to 1), class D1 (moderate drought) of the U.S. Drought Monitor (USDM); its D3 (extreme drought, 2nd to 5th percentile) is rare (USDM). For regression, the anomalies have heavy tails: weight training rows by the inverse frequency of their target bin, check that held-out blocks contain the tails, report errors per quantile. Stratifying by target cannot be combined with a split by time and blocks. Balancing changes the base rate the model learns; correct its probabilities before reading them as frequencies.

343440 rows, 26 blocks, 6 held out for testing

Your turn (7b). Split by time and by space: train, the rows of yy from 1991-2010 outside the test blocks, and test, the rows from 2011-2020 inside them (DataFrames). Then w1, the class weight for drought rows: the number of non-drought training rows divided by the number of drought training rows. Hint: combine conditions with &, using yy["time"].dt.year <= 2010 and yy["block"].isin(test_blocks); ~ turns True into False.

not answered yet
Notebook Cell
correct
Using the reference result so you can continue; compare with yours.
train: 178800 rows, 20.0 % drought | test: 25080 rows, 25.5 % drought
class weight for drought rows (training only): 4.00; base rate the weighted model sees: 50 %
regression: rows with |anomaly| > 100 mm are 6.9 % of training rows and carry 51.5 % of the weight after reweighting

Q7.3 Which split leaks? A. a random split of individual cell-months; B. train on 1991-2010, test on 2011-2020; C. hold out whole 4-degree blocks of cells; D. B and C together.

not answered yet
Notebook Cell
correct

Part 8. Instructions for an AI tool (about 7 min, if you have time)

What to do: give an AI tool your twin and the fixed instructions below, score its findings, answer Q8.

For Canvas, fill the three templates in lab_s07_templates/, with land-surface hints: reproducibility_rules.md (rules an AI tool must follow on your project data, each answerable yes or no), pipeline_instructions.md (from the raw PSL files to the drought frequency) and ai_conversation.md (your conversation trying both on the real data, and what you checked and corrected). The twin test stays in this notebook (tool_findings, q8); item (d) is a separate conversation with your two files. The last cell of this part prints the real-data value to compare the tool’s number with. UW Purple cannot run code or open NetCDF: upload a CSV (your twin, or snapshots/cpc_soilw_precl_spokane_cell_1991-2020.csv). Claude or GitHub Copilot in VS Code open the files themselves.

file to attach: (temporary folder of the book build)/lsm_twin_class.csv
--------------------------------------------------------------------------------
I attach a CSV file. Here is what its provider says it contains:

Synthetic twin of the CPC soil moisture grid, Pacific Northwest, monthly, January 1991 to December 2020.
Columns: time (first day of the month), lat (degrees north, cell centre), lon (degrees east from 0 to 360,
cell centre), soil_moisture_mm (monthly mean water in a one-layer 1.6 m soil column, holding capacity 760 mm),
precip_mm_per_day (monthly mean precipitation rate from a gauge analysis over land only).
Grid: 0.5 degree. Rows exist where at least one of the two variables has a value.

Please (1) list every problem you find in this file: for each, the variable, the first and last month
affected (YYYY-MM), the latitude and longitude range affected, what is wrong, and why it is physically
implausible; (2) say which values you would keep as real extremes of the climate; (3) compute the percent
of cell-months in 2011-2020 that are drought months, where a drought month has soil moisture below the
20th percentile of the same cell and calendar month over 1991-2010, first on the file as it is and then
after your cleaning; (4) give your findings as a Python list of dictionaries with keys variable, start,
end, lat, lon, what, why (lat and lon as (min, max) tuples, or None for the whole grid).
not answered yet

Q8. What did the tool miss that you found? What did it invent (findings that match nothing)? Did it treat a real extreme, such as the 2015 dry spell or the wettest coastal winters, as an error? How far is its drought frequency from the truth, and why?

not answered yet
Notebook Cell
truth for comparison: 17.2 %
real data, drought frequency 2011-2020: 25.1 % over all model land cells as read; 24.2 % over cells with >= 50 % land and soil water above 1 mm

Wrap-up (about 3 min)

Back to Part 1. If your download finished, does your cut have the course copy’s bytes? If not, its values?

No download in this run.

Three answers, two to four sentences each, each with one number or date from today’s work:

  1. What sets the month-to-month variability of soil water in this system, and which numbers in the CPC file were measured, interpolated or computed?

  2. Which problem, real (Parts 1 to 4) or planted (Part 5), would do the most damage to a machine-learning model trained on these data, and how would you detect it in a new file?

  3. Your answer to the guiding question with numbers from today, and what you would need before trusting it (gauge network, missing snowpack, a station comparison of mostly warm-season months).

not answered yet

Sources

  • CPC soil moisture: van den Dool, H., J. Huang, and Y. Fan (2003), Performance and analysis of the constructed analogue method applied to U.S. soil moisture over 1981-2001, J. Geophys. Res., 108(D16), 8617, Dool et al. (2003) (the citation PSL asks for).

  • Fan, Y., and H. van den Dool (2004), Climate Prediction Center global monthly soil moisture data set at 0.5 degree resolution for 1948 to present, J. Geophys. Res., 109, D10102, Fan & Dool (2004).

  • Huang, J., H. M. van den Dool, and K. P. Georgakakos (1996), Analysis of model-calculated soil moisture over the United States (1931-1993) and applications to long-range temperature forecasts, J. Climate, 9, 1350-1362, doi:10.1175/1520-0442(1996)009<1350:AOMCSM>2.0.CO;2.

  • Chen, M., P. Xie, J. E. Janowiak, and P. A. Arkin (2002), Global land precipitation: A 50-yr monthly analysis based on gauge observations, J. Hydrometeor., 3, 249-266, doi:10.1175/1525-7541(2002)003<0249:GLPAYM>2.0.CO;2.

  • Fan, Y., and H. van den Dool (2008), A global monthly land surface air temperature analysis for 1948-present, J. Geophys. Res., 113, D01103, Fan & Dool (2008).

  • Arevalo, J., J. Welty, Y. Fan, and X. Zeng (2021), Implementation of snowpack treatment in the CPC water balance model and its impact on drought assessment, J. Hydrometeor., 22, 1235-1247, Arevalo et al. (2021).

  • Entekhabi, D., et al. (2010), The Soil Moisture Active Passive (SMAP) mission, Proc. IEEE, 98(5), 704-716, Entekhabi et al. (2010).

  • Kerr, Y. H., et al. (2010), The SMOS mission: New tool for monitoring key elements of the global water cycle, Proc. IEEE, 98(5), 666-687, Kerr et al. (2010).

  • Bell, J. E., et al. (2013), U.S. Climate Reference Network soil moisture and temperature observations, J. Hydrometeor., 14, 977-988, Bell et al. (2013).

  • Thornthwaite, C. W. (1948), An approach toward a rational classification of climate, Geographical Review, 38, 55-94, Thornthwaite (1948).

  • Bretherton, C. S., M. Widmann, V. P. Dymnikov, J. M. Wallace, and I. Bladé (1999), The effective number of spatial degrees of freedom of a time-varying field, J. Climate, 12, 1990-2009, doi:10.1175/1520-0442(1999)012<1990:TENOSD>2.0.CO;2.

  • Data provided by the NOAA PSL, Boulder, Colorado, USA, from their website at https://psl.noaa.gov (soil moisture, PREC/L, GHCN+CAMS; usage restrictions: none). USCRN data from NOAA NCEI, public domain. Map lines from Natural Earth, public domain. 24-hour precipitation records: NCEI State Climate Extremes Committee. Retrieval dates and fingerprints: snapshots/*.provenance.json.

Submit (Friday 16 October, 9:00)

To the Canvas assignment “Session 7: explore your system’s data” (Completion only: the work does not count toward your grade, but a missing submission costs 10 points):

  1. this notebook (.ipynb; HTML optional), run from the top so the summary below prints;

  2. reproducibility_rules.md, pipeline_instructions.md and ai_conversation.md (the transcript may be a PDF beside it), from lab_s07_templates/ (Part 8);

  3. a two- or three-sentence comment on how the AI tool did and what you corrected.

==== SESSION 7 SUMMARY ====
track: lsm
netid: not answered
parts answered: P0 0/1 | P1 0/5 | P2 0/5 | P3 0/4 | P4 0/5 | P5 0/5 | P6 0/6 | P7 0/4 | P8 0/2
self-checks passed: 0 of 31
planted problems found: not answered (seed 126538620593801)
derived quantity (truth / as given / after cleaning): 17.2 / 8.1 / not answered %
reflection 1: not answered
reflection 2: not answered
reflection 3: not answered
==== END SUMMARY ====
References
  1. van den Dool, H., Huang, J., & Fan, Y. (2003). Performance and analysis of the constructed analogue method applied to U.S. soil moisture over 1981–2001. Journal of Geophysical Research: Atmospheres, 108(D16). 10.1029/2002jd003114
  2. Fan, Y., & van den Dool, H. (2004). Climate Prediction Center global monthly soil moisture data set at 0.5° resolution for 1948 to present. Journal of Geophysical Research: Atmospheres, 109(D10). 10.1029/2003jd004345
  3. Huang, J., van den Dool, H. M., & Georgarakos, K. P. (1996). Analysis of Model-Calculated Soil Moisture over the United States (1931–1993) and Applications to Long-Range Temperature Forecasts. Journal of Climate, 9(6), 1350–1362. https://doi.org/10.1175/1520-0442(1996)009<;1350:aomcsm>2.0.co;2
  4. Chen, M., Xie, P., Janowiak, J. E., & Arkin, P. A. (2002). Global Land Precipitation: A 50-yr Monthly Analysis Based on Gauge Observations. Journal of Hydrometeorology, 3(3), 249–266. https://doi.org/10.1175/1525-7541(2002)003<;0249:glpaym>2.0.co;2
  5. Fan, Y., & van den Dool, H. (2008). A global monthly land surface air temperature analysis for 1948–present. Journal of Geophysical Research: Atmospheres, 113(D1). 10.1029/2007jd008470
  6. Arevalo, J., Welty, J., Fan, Y., & Zeng, X. (2021). Implementation of Snowpack Treatment in the CPC Water Balance Model and Its Impact on Drought Assessment. Journal of Hydrometeorology. 10.1175/jhm-d-20-0201.1
  7. Entekhabi, D., Njoku, E. G., O’Neill, P. E., Kellogg, K. H., Crow, W. T., Edelstein, W. N., Entin, J. K., Goodman, S. D., Jackson, T. J., Johnson, J., Kimball, J., Piepmeier, J. R., Koster, R. D., Martin, N., McDonald, K. C., Moghaddam, M., Moran, S., Reichle, R., Shi, J. C., … Van Zyl, J. (2010). The Soil Moisture Active Passive (SMAP) Mission. Proceedings of the IEEE, 98(5), 704–716. 10.1109/jproc.2010.2043918
  8. Kerr, Y. H., Waldteufel, P., Wigneron, J.-P., Delwart, S., Cabot, F., Boutin, J., Escorihuela, M.-J., Font, J., Reul, N., Gruhier, C., Juglea, S. E., Drinkwater, M. R., Hahne, A., Martín-Neira, M., & Mecklenburg, S. (2010). The SMOS Mission: New Tool for Monitoring Key Elements ofthe Global Water Cycle. Proceedings of the IEEE, 98(5), 666–687. 10.1109/jproc.2010.2043032
  9. Bell, J. E., Palecki, M. A., Baker, C. B., Collins, W. G., Lawrimore, J. H., Leeper, R. D., Hall, M. E., Kochendorfer, J., Meyers, T. P., Wilson, T., & Diamond, H. J. (2013). U.S. Climate Reference Network Soil Moisture and Temperature Observations. Journal of Hydrometeorology, 14(3), 977–988. 10.1175/jhm-d-12-0146.1
  10. Thornthwaite, C. W. (1948). An Approach toward a Rational Classification of Climate. Geographical Review, 38(1), 55. 10.2307/210739
  11. Bretherton, C. S., Widmann, M., Dymnikov, V. P., Wallace, J. M., & Bladé, I. (1999). The Effective Number of Spatial Degrees of Freedom of a Time-Varying Field. Journal of Climate, 12(7), 1990–2009. https://doi.org/10.1175/1520-0442(1999)012<;1990:tenosd>2.0.co;2