The short version, for everyone: For the 2026 NASA Space Apps Challenge, our team in Kisumu built TerraTrend Observatory: pick any place on Earth and a climate variable, and it tells you, from 40 years of NASA data, whether that variable is really changing, how fast, and how sure we can be. This post shows how the statistics work, line by line, reproduces one of the app's findings from live NASA data, and is honest about where the maths can fool you.
We submitted TerraTrend Observatory to the 2026 NASA Space Apps Challenge as Team GreenGen, from Kisumu, Kenya.
- Live app: https://earth-science-trend-observatory.onrender.com/ (free hosting, so the first load can take about 20 seconds)
- Code: https://github.com/Christian3788/Earth-Science-Trend-Observatory
- Demo slides: https://github.com/altradits/terratrend-greengen-demo
Christian3788
/
Earth-Science-Trend-Observatory
Select a NASA satellite or global model variable, pick any region on Earth, remove seasonal cycles, and test whether the long-term trend is statistically significant.
TerraTrend Observatory
Is this place actually warming — or does it just feel that way? TerraTrend is an interactive Earth-science workbench that lets anyone point at a spot on Earth, pull decades of NASA observations for it, and test whether the trend is statistically real.
Data note: This application combines live NASA POWER data for supported variables with modeled mission-reference or climatology fallback series for other variables and when the upstream data service is unavailable. The interface identifies the source for each series. A fallback series is not a substitute for a direct satellite observation or peer-reviewed analysis.
The problem
Climate arguments usually die in anecdotes: one hot summer, one cold snap, one cherry-picked chart. Meanwhile NASA's open archives (POWER, GIBS, MERRA-2, MODIS, OMI, GPM…) hold 40+ years of observations — but they live behind scientific APIs no student, journalist, or policymaker will ever touch. TerraTrend closes that gap: pick…
Contents
- The challenge
- What it does
- Architecture
- Getting the data: NASA POWER
- Cleaning the data
- Step 1: remove the seasons
- Step 2: ordinary least squares, by hand
- Step 3: Mann-Kendall and Sen's slope
- The verdict logic
- Reproduce a finding from live NASA data
- Where the maths can fool you: autocorrelation
- Testing statistics without trusting yourself
- Surviving a NASA outage during judging
- What was hard, and what we would do next
The challenge
Our challenge was "Be An Earth System Trend Detective!": build a tool that picks Earth science variables, shows how they change over time, and answers four questions: what is changing, where, how much, and whether the change is significant.
Climate arguments often end in anecdotes: one hot year, one late rainy season. NASA holds decades of observations, but most students, journalists, teachers and local planners never touch scientific APIs. We wanted a three-step tool: pick a place, pick what to track, read the finding.
What it does
- Search for a city, a feature or coordinates, or click anywhere on a NASA Blue Marble world map.
- Pick one of six variables. All six are live NASA POWER data: Earth skin temperature, precipitation, surface albedo, soil moisture, 10 m wind speed and solar irradiance (from MERRA-2, CERES and GPM-based products).
- Get a verdict badge, a trend chart with a 95% confidence band, the statistics, a plain-words explanation, and a CSV export with a provenance header.
Architecture
| Layer | What | Where |
|---|---|---|
| Frontend | React 19, Vite, Tailwind CSS, hand-drawn SVG charts | src/ |
| API server | Node.js + Express: fetch, cache, retry, fall back to recorded data | server.ts |
| Data pipeline | Parse, validate and clean NASA POWER responses | src/utils/dataPipeline.ts |
| Statistics | OLS, Student-t, Mann-Kendall, Sen's slope, written from scratch |
src/utils/statistics.ts (462 lines) |
| Tests | 28 hand-computed science tests on Node's built-in runner | tests/science.test.ts |
| Hosting | Render |
We deliberately wrote the statistics ourselves instead of pulling in a stats library. In a 48-hour hackathon that sounds backwards, but it meant every number on screen came from code we could explain to a judge, and it kept the server dependency-light. The cost was that we had to prove our own maths, which is what the test suite is for.
Getting the data: NASA POWER
NASA POWER serves gridded climate data for any point on Earth over a plain HTTP API. One monthly request looks like this:
https://power.larc.nasa.gov/api/temporal/monthly/point
?parameters=TS&community=RE
&longitude=-156.79&latitude=71.29
&start=1985&end=2024&format=JSON
TS is Earth skin temperature. The answer is GeoJSON with one key per month, YYYYMM:
{"type":"Feature","geometry":{"type":"Point","coordinates":[-156.79,71.29,0.54]},
"properties":{"parameter":{"TS":{"198501":-15.94,"198502":-20.39,"198503":-18.61, ...
The server rounds coordinates to two decimals before building the request and the cache key, so nearby clicks share one cached response for 30 minutes:
const roundedLat = Number(lat.toFixed(2));
const roundedLon = Number(lon.toFixed(2));
const cacheKey = `${variable}:${roundedLat}:${roundedLon}:${startYear}:${endYear}:${resolution}`;
Every upstream call goes through fetchWithRetry, with a per-attempt timeout and exponential backoff, retrying only what is worth retrying:
const resp = await fetchImpl(url, { signal: controller.signal });
clearTimeout(timer);
if (resp.ok) return resp;
if (resp.status === 429 || resp.status >= 500) {
lastError = new Error(`Upstream HTTP ${resp.status}`); // retry
} else {
throw new Error(`Upstream HTTP ${resp.status}`); // 4xx: fail fast
}
...
await sleep(backoffMs * 2 ** attempt); // 800 ms, 1.6 s
A 404 means our request is wrong, and retrying it just wastes the user's time. A 500 or a 429 is NASA having a bad minute, and waiting helps.
Cleaning the data
Two traps in the NASA POWER format are easy to miss:
-
Missing values are
-999, a sentinel, notnull. Averaging a-999into a temperature series produces a spectacular and completely fake cooling trend. -
Month 13 exists. Each year includes a
YYYY13key holding the annual mean. Treat it as a month and you double-count every year.
parseNasaPowerMonthly drops both, and anything malformed, and counts what it dropped:
for (const [key, val] of Object.entries(raw)) {
if (val === NASA_POWER_SENTINEL || val === null || val === undefined) {
droppedSentinel += 1;
continue;
}
...
const y = Number(key.slice(0, 4));
const m = Number(key.slice(4, 6));
// Month 13 is the NASA POWER annual mean row — skip it.
if (!Number.isInteger(y) || !Number.isInteger(m) || m < 1 || m > 12) {
droppedInvalid += 1;
continue;
}
points.push({ date: `${y}-${String(m).padStart(2, '0')}`, year: y, month: m,
decimalYear: decimalYearMonthly(y, m), value: Number(val) });
}
For 1985–2024 at Utqiaġvik this keeps exactly 480 months and drops 40 rows: the 40 annual "month 13" entries. cleanTimeSeries then removes duplicates (last one wins), drops non-finite values and sorts by time, so the statistics never see a surprise.
Step 1: remove the seasons
Monthly temperature at 71°N swings from about −28 °C in winter to +6 °C in summer. A trend of half a degree per decade is invisible under that. So before fitting anything, the app subtracts each calendar month's long-term mean:
export function deseasonalizeMonthly(points: TimeSeriesPoint[]): TimeSeriesPoint[] {
const monthSums = new Array<number>(13).fill(0);
const monthCounts = new Array<number>(13).fill(0);
for (const pt of points) {
monthSums[pt.month] += pt.value;
monthCounts[pt.month] += 1;
}
const monthMeans = monthSums.map((sum, m) => (monthCounts[m] > 0 ? sum / monthCounts[m] : 0));
return points.map((pt) => ({ ...pt, value: Number((pt.value - monthMeans[pt.month]).toFixed(4)) }));
}
What remains is the anomaly: how much warmer or colder each January was than the average January, and so on. You will see below what a difference this makes.
Step 2: ordinary least squares, by hand
Time is a decimal year (1985 + (month − 0.5) / 12), so the slope comes out directly in units per year. The fit is the textbook one:
const slope = sxx > 0 ? sxy / sxx : 0;
const intercept = meanY - slope * meanX;
...
const df = n - 2;
const mse = df > 0 ? sse / df : 0;
const sErr = Math.sqrt(mse);
const seSlope = sxx > 0 ? sErr / Math.sqrt(sxx) : 0;
const tStat = seSlope > 0 ? slope / seSlope : 0;
const pValOLS = studentTTwoTailedPValue(tStat, df);
const tCrit = criticalT025(df);
The interesting part is the p-value. JavaScript has no Student-t distribution, so the code builds one. The two-tailed p-value for a t-statistic is a regularized incomplete beta function:
That needs ln Γ (via the Lanczos approximation) and a continued fraction for the incomplete beta (Lentz's method, the version in Numerical Recipes):
export function studentTTwoTailedPValue(tStat: number, df: number): number {
if (df <= 0 || !Number.isFinite(tStat)) return 1;
const x = df / (df + tStat * tStat);
return Math.min(1, Math.max(0, regularizedIncompleteBeta(x, df / 2, 0.5)));
}
The critical value for the 95% interval is found by bisection on that same function, so the interval and the p-value can never disagree:
function criticalT025(df: number): number {
let lo = 1.9, hi = 13.0;
for (let i = 0; i < 45; i++) {
const mid = 0.5 * (lo + hi);
if (studentTTwoTailedPValue(mid, df) > 0.05) lo = mid; else hi = mid;
}
return 0.5 * (lo + hi);
}
The shaded band on the chart is the confidence interval of the fitted line at each point, which is why it is narrowest in the middle of the record and flares at the ends:
const seLine = sErr * Math.sqrt(1 / n + (dx * dx) / sxx);
const margin = tCrit * seLine;
Step 3: Mann-Kendall and Sen's slope
OLS assumes the residuals are roughly normal, and one extreme year can drag the line. So every result is cross-checked with two non-parametric methods that only care about order, not size.
Mann-Kendall compares every pair of points and counts how often the later one is higher:
for (let i = 0; i < m - 1; i++) {
for (let j = i + 1; j < m; j++) {
const diff = ys[j] - ys[i];
if (diff > 0) S += 1;
else if (diff < 0) S -= 1;
const dt = xs[j] - xs[i];
if (dt > 0) pairSlopes.push(diff / dt);
}
}
Under "no trend", S has mean 0 and a known variance, corrected for tied values:
and the z-score uses a continuity correction of 1 towards zero. The p-value comes from the normal distribution via the Abramowitz & Stegun approximation of erfc, accurate to about 1.5 × 10⁻⁷, which is far finer than any decision the app makes.
Sen's slope reuses the same loop: it is simply the median of all pairwise slopes. For 480 months that is 114,960 slopes, sorted once. A single freak year moves the median hardly at all, which makes Sen's slope the robust partner to the OLS slope.
Mann-Kendall is O(n²), so for long daily series (over 500 points) the code evenly downsamples to 450 points to keep the UI responsive. Monthly 40-year series (480 points) are used in full.
The verdict logic
The badge is not just "p < 0.05". It encodes how much the two methods agree:
| OLS significant | Mann-Kendall significant | Badge |
|---|---|---|
| Yes | Yes | Statistically Significant Increasing / Decreasing Trend |
| One of them | Statistically Significant Increase / Decrease (Single Test) | |
| Neither, but either p < 0.15 | Emerging Upward / Downward Drift (Not Yet Significant at α = 0.05) | |
| Neither | No Statistically Significant Trend |
A correction to what we wrote on submission day: we said the two tests "must agree". The code is more nuanced. A single significant test still produces a significant verdict, but the badge says "(Single Test)" so the reader knows the evidence is weaker.
Reproduce a finding from live NASA data
The app's showcase example is Utqiaġvik, Alaska skin temperature, 1985–2024. Here it is from scratch, using the app's own pipeline and statistics on a fresh download. Save as utq.ts in the repo root:
utq.ts (click to expand)
import { readFileSync } from 'node:fs';
import { parseNasaPowerMonthly, cleanTimeSeries } from './src/utils/dataPipeline.ts';
import { analyzeTimeSeries } from './src/utils/statistics.ts';
const raw = JSON.parse(readFileSync(process.argv[2], 'utf8'));
const { points, stats } = parseNasaPowerMonthly(raw.properties.parameter.TS);
const clean = cleanTimeSeries(points);
for (const deseason of [false, true]) {
const r = analyzeTimeSeries(clean.points, { resolution: 'monthly', deseasonalize: deseason,
variableName: 'skin temperature', unit: '°C', regionName: 'Utqiagvik' })!;
console.log(`deseasonalize=${deseason} n=${r.ols.n}`);
console.log(` OLS ${r.ols.slopePerDecade.toFixed(3)} °C/decade 95% CI [${r.ols.ci95LowerPerDecade.toFixed(2)}, ${r.ols.ci95UpperPerDecade.toFixed(2)}] p=${r.ols.pValue.toExponential(2)} R²=${r.ols.rSquared.toFixed(3)}`);
console.log(` Mann-Kendall tau=${r.mannKendall.tau.toFixed(3)} z=${r.mannKendall.zScore.toFixed(2)} p=${r.mannKendall.pValue.toExponential(2)} Sen ${r.mannKendall.sensSlopePerDecade.toFixed(3)} °C/decade`);
console.log(` verdict: ${r.verdictTitle}`);
}
const a = analyzeTimeSeries(clean.points, { resolution: 'annual', deseasonalize: false,
variableName: 'skin temperature', unit: '°C', regionName: 'Utqiagvik' })!;
console.log(`annual n=${a.ols.n} OLS ${a.ols.slopePerDecade.toFixed(3)} °C/decade CI [${a.ols.ci95LowerPerDecade.toFixed(2)}, ${a.ols.ci95UpperPerDecade.toFixed(2)}] p=${a.ols.pValue.toExponential(2)} | Sen ${a.mannKendall.sensSlopePerDecade.toFixed(3)} MK p=${a.mannKendall.pValue.toExponential(2)}`);
console.log('parse stats', JSON.stringify(stats));
git clone https://github.com/Christian3788/Earth-Science-Trend-Observatory
cd Earth-Science-Trend-Observatory
curl -s "https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=TS&community=RE&longitude=-156.79&latitude=71.29&start=1985&end=2024&format=JSON" -o utq.json
node utq.ts utq.json # Node 22+ runs TypeScript directly
Our run (Node 24.19, data downloaded 19 November 2026):
deseasonalize=false n=480
OLS 0.660 °C/decade 95% CI [-0.04, 1.37] p=6.63e-2 R²=0.007
Mann-Kendall tau=0.071 z=2.32 p=2.01e-2 Sen 0.573 °C/decade
verdict: Statistically Significant Increase (Single Test)
deseasonalize=true n=480
OLS 0.580 °C/decade 95% CI [0.40, 0.76] p=1.37e-9 R²=0.074
Mann-Kendall tau=0.179 z=5.85 p=4.89e-9 Sen 0.471 °C/decade
verdict: Statistically Significant Increasing Trend
annual n=40 OLS 0.581 °C/decade CI [0.32, 0.84] p=5.76e-5 | Sen 0.549 MK p=2.43e-4
parse stats {"kept":480,"droppedSentinel":0,"droppedInvalid":40}
Three lessons are in those lines:
- The seasons hide the trend. On raw monthly data, OLS can't even call it (p = 0.066, interval crossing zero) and R² is 0.007. Remove the seasonal cycle and the same data gives p ≈ 10⁻⁹. The warming did not change; the noise did.
- The result matches the live app: +0.58 °C per decade, 95% CI 0.40 to 0.76, Sen's slope +0.47. Same code, same data, same answer.
- R² of 0.074 does not mean "no trend". It means month-to-month weather is much bigger than the decade-scale drift. The app's plain-words panel says this explicitly, because it is the most common misreading of a trend chart.
Where the maths can fool you: autocorrelation
Look at the annual line again: the same +0.58 °C per decade, but a 95% interval of [0.32, 0.84], much wider than the monthly [0.40, 0.76]. Which one is right?
Both OLS and Mann-Kendall assume each data point is independent. Monthly climate anomalies are not: a warm March tends to follow a warm February. Measuring that on the deseasonalized residuals:
lag-1 autocorrelation of residuals r1=0.303 effective n≈257 of 480 CI half-width x1.37 -> [0.33, 0.83]
With a lag-1 autocorrelation of 0.30, the 480 months carry about as much independent information as 257 months would, using the standard approximation n_eff = n(1 − r₁)/(1 + r₁). Widening the interval accordingly gives [0.33, 0.83], almost exactly the annual result.
So the honest summary is: Utqiaġvik's skin temperature rose by roughly 0.6 °C per decade, with a 95% interval of roughly 0.3 to 0.8. The trend is real by any test here, but the monthly interval shown in the app is too narrow, because the app does not yet correct for autocorrelation. For a weaker trend, that could turn "not significant" into "significant". This is the first thing we would fix (see below).
Testing statistics without trusting yourself
The trap in testing your own statistics is copying the function's output into the test. Then the test only proves the code agrees with itself. The suite's header states the rule:
/**
* Every numeric expectation below is hand-computed (see comments), NOT copied
* from the implementation's output, so the suite can actually catch regressions.
*/
So the OLS test uses the classic textbook dataset, with the arithmetic in the comments:
// x = 1..5, y = 2,4,5,4,5 => meanX=3, meanY=4, sxx=10, sxy=6,
// slope=0.6, sse=2.4, syy=6, R^2=0.6; ...
// se_slope=sqrt(0.8/10)=0.28284, t=2.12132, df=3, two-tailed p ~= 0.124
The Student-t function is checked against printed t-tables (t = 2.306 with df = 8 must give p = 0.05; t = 3.355 must give p = 0.01). Mann-Kendall is checked on a strictly increasing series and on a series with ties ([1, 2, 2, 3]) to exercise the tie correction. There are tests for the parsers (sentinels, month 13, impossible dates), for fetchWithRetry (retry on 500, fail fast on 404, abort a hanging request), and an end-to-end test that plants a known +0.04 per year trend in noisy monthly data with gaps, and checks the pipeline recovers it.
The suite needs no dependencies, just Node's built-in test runner:
node --test tests/science.test.ts
ℹ tests 28
ℹ suites 14
ℹ pass 28
ℹ fail 0
ℹ duration_ms 195.257375
Surviving a NASA outage during judging
A hackathon demo dies if the upstream API is down when the judges click. So the server has a last line of defence: recorded real responses. A script captures actual NASA POWER and geocoding answers for the showcase locations, and server/fixtures.ts serves them if the live call fails, flagged offlineDemo: true:
// When NASA POWER or Open-Meteo is unreachable, server.ts serves these
// pre-recorded *real* responses (flagged `offlineDemo: true`) instead of
// generated reference series or empty results.
The important word is real. It would have been easy to fall back to a synthetic series that "looks like climate data". We refused: every number the app ever shows comes from NASA, and when it is a recording, the source label on screen says so.
What was hard, and what we would do next
What was hard. The hackathon weekend overlapped with Kisumu Market Day, where I was also taking part, so a lot of my coding happened late at night. We also had to cut scope. The repo has a 3D globe, region comparison and a satellite image wipe, but we shipped a simpler dashboard so the deployed app would be reliable before the deadline.
What we would do next:
- Correct for autocorrelation. Use the effective sample size for the OLS interval, and a modified Mann-Kendall (Hamed–Rao variance correction, or pre-whitening) for the p-value. The Utqiaġvik example shows why.
- Seasonal Mann-Kendall for monthly data, which tests each calendar month separately and is designed for exactly this kind of series.
- Field significance. If users scan many places, some will look "significant" by chance. A false-discovery-rate correction would make region scans honest.
- Faster Sen's slope. The O(n²) pair loop is fine at 480 points; long daily series would need an O(n log n) algorithm instead of downsampling.
Honest limits
Every result shows its source label. NASA POWER gives gridded reanalysis and satellite-derived estimates for a point, not a ground-station reading. Significance is evidence under the tests used, not proof of a cause, and as shown above, the monthly intervals are currently optimistic.
Team and thanks
Built by Team GreenGen: Victor Ouma (team owner), Stanley Chege Thuita, Hellen Onyango, Jack Omosh, Chepkorir Miriam Chemeres and Christian Amos Otieno. Thank you to NASA Space Apps Challenge, and a shout-out to the Kisumu tech community at Zone01 Kisumu and LakeHub.
I also received my participant certificate: Galactic Problem Solver. 🌍
Some of the original post and the demo slide text were drafted with AI assistance; every number here comes from the code and data shown, and the commands to reproduce them are above.
Top comments (0)