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.

2.5 Gridded data: coordinates, units and the file on disk

🖥️ Lecture slides — Session 06 (Mon Oct 12)

Climate models, reanalyses, ocean products and satellite images all arrive as grids: arrays of numbers whose position stands for a time, a latitude, a longitude or a depth. A grid fails quietly. Pick the wrong cell, forget a unit conversion, or read a different version of the file, and you still get a plausible number. Nothing raises an error.

This notebook works with one real grid, an atmospheric reanalysis over North America, and asks what a single value in it means and how each processing step can change that meaning. An agent can write every line of code here in seconds. What it cannot do for you is decide which cell is Seattle, whether the numbers are still in kelvin, or whether the file is the one you think you downloaded. Those decisions are the subject of this notebook.

You should be able to:

  1. Describe one value in the grid: the variable, the model level it sits on, the grid spacing, the time in UTC, and how much of it comes from the model rather than from observations.

  2. Estimate the memory a grid needs from its shape and data type before loading it, and read how it is packed on disk.

  3. Select a location by coordinate with a stated tolerance, and catch the two traps that return an empty or wrong selection without an error.

  4. Convert units on a copy whose metadata still describe the numbers, and show that a rerun gives the same result.

  5. Give a failing check table to an agent, verify its fix, and log the exchange.

PartQuestionModeMinutes
0What does “Seattle’s temperature” in this file stand for?by hand2
1Which file is this, and will it fit in memory?by hand6
2Is this a thermometer reading at 4 pm?by hand8
3Which cell is Seattle?by hand, then assistant allowed10
4Do the metadata still describe the numbers?assistant allowed7
5Is the agent’s Seattle series from the right cell, in °C?agent, then verify15
Data cardFill the grid fieldsby hand10, after class
ExtensionsArea weighting, the annual cycle, what a tensor forgetsassistant allowed (569 required)self-paced

Two calls to be able to read in any agent’s code: .sel(..., method="nearest", tolerance=...), which decides which cell you get, and .encoding, which says how the numbers are stored on disk. You do not need to memorize the rest of the syntax; you need to check what it returns.

The dataset

NCEP/NCAR Reanalysis 1, air temperature at the lowest model level, every 6 hours, 2013 to 2014, over North America.

🖥️ Model & simulation · 🌤️ Atmosphere · 🌡️ Atmospheric & climate science

A reanalysis runs one fixed weather-forecast model forward in time and pulls it toward the observations available at each step: radiosondes, aircraft, satellites, surface stations, ships. The result is a complete, gridded estimate of the atmosphere, even where nobody measured. This grid holds air temperature on the model’s lowest level (sigma = 0.995, meaning a pressure 99.5% of the surface pressure), four times a day, on a 2.5° latitude-longitude grid.

  • Provider: NOAA Physical Sciences Laboratory (PSL), NCEP/NCAR Reanalysis 1.

  • Reference: Kalnay, E., et al. (1996). The NCEP/NCAR 40-year reanalysis project. Bulletin of the American Meteorological Society, 77, 437–471. doi:10.1175/1520-0477(1996)077<0437:TNYRP>2.0.CO;2

  • This copy: a two-year subset distributed by the Xarray project in pydata/xarray-data, pinned below to one commit and one checksum.

Two statements from Kalnay et al. (1996) decide how you may use these numbers. The model “has 5 levels in the boundary layer”, and “the lowest model level is about 5 hPa from the surface”. And “temperature at the lowest sigma level” is a class B variable: “although there are observational data that directly affect the value of the variable, the model also has a very strong influence on the analysis value”. Keep both in mind when you compare this grid with a thermometer.

0. Predict first

Before opening the file, write down in a markdown cell what you expect “Seattle’s air temperature” in this grid to stand for:

  • At what height above the ground?

  • Over what area: a point, a city, or something larger?

  • At what local times of day?

  • Measured by a thermometer, or estimated by a model?

You will check each answer against the file and the provider in parts 1 and 2.

1. Which file is this, and will it fit in memory?

A grid you download today may not be the grid someone else downloads next year: providers reprocess, mirrors change, and files get edited by hand. The first habit is to fix which bytes you used. We download one pinned file, check its SHA-256 checksum against the value recorded here, and then make the local copy read-only, so that no later cell (and no agent) can overwrite the raw data by accident. Everything derived from it gets a new name.

Be precise about what the checksum proves. It was recorded from the Xarray project’s copy at commit 2baf0c2, a two-year North America subset. A match proves you hold the same bytes as that pinned copy. It does not prove the copy matches what NOAA PSL distributes, which is a set of global yearly files; the file’s own title, “4x daily NMC reanalysis (1948)”, shows it was repackaged. A subset made by someone else is a version of its own, and your data card should name it.

The grid has 2,920 time steps × 25 latitudes × 53 longitudes. Before running the next cells, estimate by hand how many megabytes it takes in memory as 64-bit floats (8 bytes per value). Write your number down.

file:      data/air_temperature_raw.nc
sha256:    c606b89c35970a2983b914b76df4adbb409003ef34aa7cfd7f582e41f307482b
writable:  False
on disk:   7.8 MB
dimensions: {'time': 2920, 'lat': 25, 'lon': 53}
in memory as float64 = 31.0 MB
on disk as   int16 with scale_factor 0.01
for scale: a global hourly 0.25 degree grid, one variable, one year, as float64 = 73 GB

The file stores each temperature as a 16-bit integer counting hundredths of a kelvin (scale_factor 0.01). That packing sets the precision of every number you will read: 0.01 K, no better. On loading, Xarray multiplies by the scale factor and holds the result as 64-bit floats, which is why the grid is four times larger in memory than on disk. Compare the printed size with your estimate.

The same arithmetic tells you, before you download anything, whether a grid fits on your laptop. The last line above does it for a global hourly grid at 0.25° (8,760 × 721 × 1,440 values for one variable and one year): far more than a laptop’s memory. That is the scale where Chapter 5’s chunked, lazy formats become necessary.

2. Is this a thermometer reading at 4 pm?

Read the file’s own description of the variable, then compare it with the provider’s documentation quoted above.

{
 "Conventions": "COARDS",
 "title": "4x daily NMC reanalysis (1948)",
 "description": "Data is from NMC initialized reanalysis\n(4x/day).  These are the 0.9950 sigma level values.",
 "platform": "Model",
 "references": "http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanalysis.html"
}
{
 "long_name": "4xDaily Air temperature at sigma level 995",
 "units": "degK",
 "precision": "2",
 "GRIB_id": "11",
 "GRIB_name": "TMP",
 "var_desc": "Air temperature",
 "dataset": "NMC Reanalysis",
 "level_desc": "Surface",
 "statistic": "Individual Obs",
 "parent_stat": "Other",
 "actual_range": "[185.16 322.1 ]"
}
latitude step (deg):  [-2.5]  -> latitude runs north to south
longitude step (deg): [2.5]  longitude range: 200.0 to 330.0
time step (hours):    [6]  hours of day (UTC): [0, 6, 12, 18]
one 2.5 x 2.5 degree cell at 47.5 N spans about 278 km north-south and 188 km east-west
5 hPa above a 1000 hPa surface at 10 C is about 41 m

Three things in the file’s own metadata do not match the provider’s description, and each one matters:

The file saysWhat it isWhy it matters
level_desc: SurfaceThe lowest model level, sigma 0.995, about 40 m above the model’s ground (computed in the code cell above; Kalnay et al. 1996, Table 1, puts sigma 0.995 at the middle of an 80 m thick lowest layer)Not the 2 m height of a weather-station thermometer
statistic: Individual ObsAn analysis: a model state pulled toward observations, class B in Kalnay et al. (1996)Observations affect the value directly, but “the model also has a very strong influence” on it: treat it as an estimate, not a measurement
units: degKKelvin. degK is a valid alias in UDUNITS, the unit library behind the COARDS and CF (Climate and Forecast) conventions; the CF standard names write the unit as KA check that compares the units string with "K" fails on this file; a unit-aware parser accepts it

Two more facts you computed above:

  • Time. The four daily values are instantaneous states at 00, 06, 12 and 18 UTC. In Seattle (UTC−8 in winter, UTC−7 in summer) that is late afternoon, evening, early morning and late morning. The 00 UTC value lands near the afternoon maximum and the 12 UTC value near the early-morning minimum, but neither is the daily extreme, so a daily mean of four values is not the same as the mean of a station’s daily maximum and minimum.

  • Area. Grid points are 2.5° apart, about 280 km × 190 km at Seattle’s latitude (computed above). Each value is interpolated to its grid point from the model’s native grid (192 × 94 points, Kalnay et al. 1996); it is not an average over the box. The model’s terrain is smoothed at its T62 spectral resolution (62 waves around a latitude circle, about 210 km), so the Olympic Mountains, the Cascades and Puget Sound are blurred into a few grid points.

Go back to your prediction from part 0 and correct it.

<Figure size 900x500 with 2 Axes>

Notice the blocks: each colored square is one grid value. Coastlines are drawn at a far finer resolution than the data, which makes the grid look more precise than it is.

For your data card (template in 2.13; the final project in 2.20 requires one). Fill these fields after part 5 or after class, in a markdown cell; it takes about 10 minutes. They are the fields a gridded dataset needs beyond the ones a table needs:

FieldThis grid
Variable and level
Grid spacing and extent
Coordinate convention (longitude range, latitude order)
Time: sampling, instantaneous or averaged, time zone
Units in the file, and in your derived product
Packing on disk and resulting precision
Observation versus model (Kalnay class)
Provider, the copy you used and its version, checksum

3. Which cell is Seattle?

A labeled array lets you select by coordinate value instead of by position. That removes one class of error (counting rows) and opens two others, because a coordinate selection can return the wrong cell without any warning. We first practise on a tiny test grid whose values encode their own position, so you can read the answer directly.

Before running the next three code cells, write two predictions in a markdown cell: (a) what test.sel(lat=slice(45, 50)) returns on a grid stored north to south; (b) which longitude method="nearest" returns when you ask a grid stored as −180 to 180° for longitude 237.7.

position [1, 1]:               47737.5
label lat=47.5, lon=237.5:     47737.5
slice lat 45 to 50 (ascending): []   <- empty
slice lat 50 to 45 (as stored): [50.  47.5 45. ]

Trap 1, latitude order. The reanalysis stores latitude from north to south, like the test grid. A slice written in the usual south-to-north order returns an empty array, and any mean taken over it is nan or an error several cells later. The same happens on the real grid:

cells with 40 <= lat <= 50, slice(40, 50): 0
cells with 40 <= lat <= 50, slice(50, 40): 5

Trap 2, longitude convention. This file uses degrees east from 0 to 360; Seattle is at 237.7° E. Many datasets use −180 to 180, where Seattle is −122.3°. A common processing step converts one convention to the other. Below, a copy of the grid is converted, and then queried with the 0-360 longitude:

original (0-360)       nearest to lon 237.7 -> lat  47.5, lon  237.5
converted (-180-180)   nearest to lon 237.7 -> lat  47.5, lon  -30.0
with tolerance=1.25 degrees: KeyError, no cell within half a grid step

On the converted copy, method="nearest" returns longitude −30°, the eastern edge of the grid in the Atlantic, about 6,500 km from Seattle, and raises nothing. “Nearest” always finds something. A tolerance of half a grid step (1.25°) turns the silent error into a KeyError. The check tables below report every longitude in degrees east, 0 to 360, whatever the grid stores, so this cell appears there as 330.00 E.

Two rules follow, and both are easy to check in anyone’s code, including an agent’s:

  1. Every nearest-neighbor selection carries a tolerance of half the grid spacing.

  2. After every selection, print or test the coordinates you got back, not only the values.

The check table below states these rules as tests, for a function that selects Seattle correctly:

4 of 4 checks pass
Loading...

Your turn. By hand, write down the tolerance you will use and the grid point you expect. Then, with an assistant if you like, select the cell for Fairbanks, Alaska (64.84° N, 147.72° W) on both ds and ds_w, print the coordinates you get back, and add two rows for it to the check table. Last, select the band from 40° N to 50° N on ds and confirm it holds 5 latitudes.

4. Do the metadata still describe the numbers?

Converting kelvin to Celsius is one subtraction. The error is in what is left behind: an attribute that still says degK, an actual_range still in kelvin, and, worst, an original grid that was changed in place because the conversion wrote into the same memory. Three habits prevent this:

  • convert on a copy, never on the raw grid;

  • update every attribute that describes the values, and record what was done in a history attribute;

  • fingerprint the result, so that a rerun can show it produced exactly the same numbers and metadata.

The fingerprint below hashes the values and the attributes. We hash the numbers and attributes rather than a written file, because two libraries, or two versions of one library, can write identical numbers into files whose bytes differ.

4 of 4 checks pass
Loading...

Your turn. First, find the gap: delete the history line in to_celsius, rerun, and notice that no row fails. Write the check that would catch it, then restore the line. Second, write to_kelvin(da) under the same three habits (a copy, updated attributes with a history entry, a fingerprint), and add two checks: that to_kelvin(to_celsius(air)) matches the raw values to within 0.01 K, the packing precision from part 1, and that to_celsius(air_c) raises an error instead of subtracting 273.15 a second time.

5. Is the agent’s Seattle series from the right cell, in °C?

The function below extracts Seattle’s temperature series in °C. It was written by the instructor to reproduce faults that coding agents commonly make; it is not a real agent transcript. It looks reasonable and it runs without error on both grids. Your job is to decide whether to accept it.

7 of 12 checks pass
                                   check                expected observed  pass
       original: input grid not modified        same fingerprint  changed False
  original: units attribute says Celsius                    degC     degK False
converted: cell is Seattle's (longitude) within 1.25 of 237.67 E 330.00 E False
      converted: input grid not modified        same fingerprint  changed False
 converted: units attribute says Celsius                    degC     degK False
Loading...

Before you prompt anything, write in a markdown cell which line of seattle_series_agent causes each failing row, and whether it is a wrong cell, a wrong unit label, or a side effect on the input. Notice also what passed: on the converted grid the function returns a cell in the mid-Atlantic (47.5° N, 30° W), and that cell passes both plausibility checks, the winter one by 0.1 °C (9.9 against an upper bound of 10). A believable winter mean and a seasonal cycle are not evidence of the right place; only the coordinate check catches it.

Then write one check of your own that the agent will not see, for example that the series has 2,920 values, or that its January 2013 mean equals the mean you compute yourself from the raw grid at 47.5° N, 237.5° E, minus 273.15. Then:

  1. Give your agent three things: the function seattle_series_agent, the function check_seattle_series (so it sees what is tested), and the failing rows printed above. If you use a coding agent in your clone of the course book, point it at this notebook instead of pasting. A prompt that works: “This function fails the checks below on two grids: ds, with longitude 0 to 360° E, and ds_w, with longitude −180 to 180°. Fix the function so that every check passes on both grids. Do not change the checks. Explain each change in one sentence.”

  2. Paste the agent’s function into the next cell, in place of the placeholder line, and run the checks again, including yours.

  3. Read the agent’s explanation against the table: did it fix the cause, or only make a check pass? A fix that deletes the longitude check, or that hard-codes −122.3 and so fails on the original grid, should be rejected.

  4. Save the conversation in AI_logs/ in your course repository, with your line-by-line diagnosis, your own check, and what you accepted, changed and verified (1.9).

A reference fix is at the end of this part. Open it only after your log entry is saved.

7 of 12 checks pass
Loading...

A rule worth adding to your AGENTS.md, in the checkable form of HW1 Step 7: “Select grid cells with method="nearest" only together with a tolerance of half the grid spacing, and print the coordinates of every selected cell.” Anyone can verify it by reading the code and the output.

Reference fix (open after logging your own)

Notebook Cell
12 of 12 checks pass
Loading...

Extensions

These are self-paced. Students in 569 do all three; students in 469 choose one.

E1. Does an unweighted mean overstate the north?

On a latitude-longitude grid, cells shrink toward the pole in proportion to the cosine of latitude (the last line below gives the ratio between 75° N and 15° N). An unweighted mean over the grid gives the high-latitude cells too much weight.

two-year mean over the grid, unweighted:            8.11 C
two-year mean over the grid, area-weighted (cos):  12.36 C
area of a cell at 75 N relative to one at 15 N: 0.27

Write two sentences: which way the weighting moves the mean and why, and what else this box mixes (land and ocean, mountains and plains) that an area weight does not fix. If you average by season, note that a December-January-February winter spans two calendar years: in this grid, January and February 2013 have no December before them.

E2. The annual cycle at Seattle

Fit a sinusoid with a period of 365.25 days to Seattle’s series and report its mean, amplitude and the date of the maximum. Before fitting, write down what you expect for each from what you know about the Pacific Northwest climate.

mean 10.2 C, amplitude 8.1 C, warmest around 26 July
<Figure size 900x300 with 1 Axes>

E3. What does a tensor no longer know?

Deep-learning libraries take plain arrays. Converting a labeled grid to a tensor keeps the numbers and drops everything else.

tensor shape: (2920, 25, 53)  dtype: torch.float32
dimension names, coordinates, units: gone. Record them before converting:
{
 "dims": [
  "time",
  "lat",
  "lon"
 ],
 "units": "degC",
 "lat_first_last": [
  75.0,
  15.0
 ],
 "lon_first_last": [
  200.0,
  330.0
 ],
 "source_sha256": "c606b89c35970a2983b914b76df4adbb409003ef34aa7cfd7f582e41f307482b"
}
round trip preserves the values to float32 precision: True

The order of dimensions in the tensor is the only record of which axis is time and which is latitude. A model trained on (time, lat, lon) and fed (time, lon, lat) runs without error.

What to carry forward

HabitHow you check it
Fix which bytes you usedA pinned checksum, and a raw file that is read-only
Know what one value meansVariable, level, grid spacing, time, observation versus model, written in the data card
Select by coordinate, safelyA tolerance of half a grid step, and the returned coordinates printed or tested
Keep metadata trueUnits and ranges updated on a copy, a history entry, a fingerprint that reruns identically
Accept agent code on evidenceA check table that fails before the fix and passes after, and an entry in AI_logs/

Section 2.6 takes the same grid’s time axis and asks what happens when you change its sampling.

References

  • Kalnay, E., et al. (1996). The NCEP/NCAR 40-year reanalysis project. Bulletin of the American Meteorological Society, 77, 437–471. doi:10.1175/1520-0477(1996)077<0437:TNYRP>2.0.CO;2

  • NOAA Physical Sciences Laboratory, NCEP/NCAR Reanalysis 1.

  • Xarray project, pydata/xarray-data, file air_temperature.nc at commit 2baf0c2.

  • Natural Earth, 1:50m coastline, public domain.

References
  1. Kalnay, E., Kanamitsu, M., Kistler, R., Collins, W., Deaven, D., Gandin, L., Iredell, M., Saha, S., White, G., Woollen, J., Zhu, Y., Leetmaa, A., Reynolds, R., Chelliah, M., Ebisuzaki, W., Higgins, W., Janowiak, J., Mo, K. C., Ropelewski, C., … Joseph, D. (1996). The NCEP/NCAR 40-Year Reanalysis Project. Bulletin of the American Meteorological Society, 77(3), 437–471. https://doi.org/10.1175/1520-0477(1996)077<;0437:tnyrp>2.0.co;2