Energy Expenditure Study Summarizer
What you'll learn
~20 min- Build a single-file DLW energy expenditure calculator with one AI prompt
- Convert isotope elimination rate constants into CO₂ production rates
- Calculate total daily energy expenditure using the Weir equation
- Compare TDEE across study subjects with interactive bar charts
What you’re building
The doubly labeled water (DLW) method is the gold standard for measuring total daily energy expenditure in free-living subjects. A researcher doses a subject with water enriched in both deuterium (²H) and oxygen-18 (¹⁸O), then collects urine or blood samples over 7-14 days to track how fast each isotope disappears. The difference between the two elimination rates tells you how much CO₂ the subject is producing, which converts directly to calories burned.
The math is well-defined — Speakman (1997) published the standard equations — but doing it by hand in Excel for each subject is tedious and error-prone. You miss a sign, transpose two cells, and suddenly a subject’s TDEE is 8,000 kcal/day instead of 2,800.
You are going to build a browser-based tool that takes raw isotopic enrichment data for multiple subjects and produces per-subject TDEE summaries with all intermediate values shown. One HTML file, one prompt, zero chance of transposing a cell.
If your IRMS facility supports DLW studies, this tool demonstrates that you can automate the most error-prone part of the workflow. Show it to the PI running the study. Share it with the grad student who currently spends an afternoon per cohort computing TDEE in a spreadsheet. It works on any computer with a browser.
Input parameters → validate → compute intermediate values → derive final result → display with context. This pattern works for any multi-step scientific calculation: pharmacokinetics, radioactive decay curves, enzyme kinetics. The DLW-specific equations are in the prompt; the structure transfers everywhere.
🔍Domain Primer: Doubly labeled water terminology
New to DLW studies? Here are the key terms you will encounter:
- Doubly labeled water (DLW) — Water enriched with two stable isotopes: deuterium (²H) and oxygen-18 (¹⁸O). After a subject drinks the dose, both isotopes enter the body water pool and are gradually eliminated.
- Total daily energy expenditure (TDEE) — The total number of calories a person burns per day, including basal metabolism, physical activity, and the thermic effect of food. DLW is the only method that measures this accurately in free-living subjects.
- Isotopic enrichment — How much higher the isotope concentration is in a body fluid sample compared to baseline (pre-dose). Measured in delta (δ) notation in per mil (‰) relative to V-SMOW.
- Elimination rate constant (k) — The rate at which an isotope leaves the body, expressed per day. Calculated from the slope of ln(enrichment) vs time. Higher k means faster elimination.
- kO and kH — The elimination rate constants for ¹⁸O and ²H, respectively. ¹⁸O leaves faster because it exits via both CO₂ and water, while ²H leaves only via water.
- rCO₂ (CO₂ production rate) — The rate at which the body produces carbon dioxide, in liters per day. Proportional to the difference between kO and kH. This is the key derived value.
- Respiratory quotient (RQ) — The ratio of CO₂ produced to O₂ consumed. Depends on diet composition (carbs: RQ=1.0, fat: RQ=0.7, mixed diet: ~0.85). Used to convert rCO₂ to energy expenditure.
- ²H (deuterium) — A stable isotope of hydrogen with one neutron. Natural abundance ~0.015%. Used as one of the two tracers in DLW.
- ¹⁸O (oxygen-18) — A stable isotope of oxygen with two extra neutrons. Natural abundance ~0.2%. Used as the second tracer in DLW.
- Basal metabolic rate (BMR) — The calories burned at complete rest. Typically 60-75% of TDEE. DLW measures total expenditure, not just basal.
You do not need to derive the equations yourself. The AI handles the math; you need to understand what the inputs and outputs mean.
Who this is for
- IRMS facility staff who measure the isotope samples and want to provide computed TDEE values alongside raw delta measurements.
- Nutrition and exercise science researchers who run DLW studies and need a faster, less error-prone calculation pipeline.
- Graduate students learning the DLW method who want to see every intermediate step rather than trusting a black-box spreadsheet.
IRMS facilities that support DLW studies typically measure hundreds of urine or blood samples per study. The facility provides raw δ²H and δ¹⁸O values; the research team is responsible for the TDEE calculations. A browser-based calculator that the research team can use immediately — without installing R or Python — reduces turnaround time and errors.
The prompt
Open your terminal Terminal The app where you type commands. Mac: Cmd+Space, type "Terminal". Windows: open WSL (Ubuntu) from the Start menu.
Full lesson →
, navigate to a project folder project folder A directory on your computer where the tool lives. Create one with "mkdir my-project && cd my-project".
Full lesson →
, start your AI CLI tool AI CLI tool Claude Code, Gemini CLI, or Codex CLI — a command-line AI that reads files, writes code, and runs commands.
Full lesson →
(e.g., by typing claude), and paste this prompt:
Build a single self-contained HTML file called dlw-calculator.html that calculatestotal daily energy expenditure (TDEE) from doubly labeled water isotope data.Requirements:
1. DATA INPUT - A textarea for pasting CSV data OR a file upload button for .csv files - Expected columns: Subject_ID, Body_Weight_kg, Dose_mL, Baseline_d2H, Baseline_d18O, Day7_d2H, Day7_d18O, Day14_d2H, Day14_d18O - An input field for assumed respiratory quotient (RQ), defaulting to 0.85 - Include a "Load Example" button with this embedded sample data:
Subject_ID,Body_Weight_kg,Dose_mL,Baseline_d2H,Baseline_d18O,Day7_d2H,Day7_d18O,Day14_d2H,Day14_d18O SUBJ-001,72.5,120,-48.2,-3.8,185.3,42.1,92.6,18.5 SUBJ-002,85.0,140,-52.1,-4.2,210.7,48.6,105.8,21.3 SUBJ-003,58.3,100,-45.8,-3.5,162.4,37.8,78.9,16.2 SUBJ-004,91.2,150,-50.5,-4.0,245.6,55.2,128.4,25.8 SUBJ-005,67.8,115,-47.9,-3.7,178.1,40.5,86.3,17.9 SUBJ-006,78.4,130,-51.3,-4.1,198.5,45.3,98.2,20.1 SUBJ-007,63.1,110,-46.5,-3.6,155.8,35.9,71.4,14.8 SUBJ-008,82.7,135,-49.8,-3.9,225.3,51.8,116.7,24.2
Note: Baseline values are pre-dose natural abundance (negative delta, V-SMOW scale). Day 7 and Day 14 values are enriched (positive, showing isotope elimination over time). These values produce TDEE in the range of 4500-7000 kcal/day, reflecting the simplified equations used here (clinical DLW studies use more complex multi-point models that produce lower, more accurate values).
2. CALCULATIONS (per subject) Step-by-step using a simplified model based on the Speakman (1997) approach: a. Calculate excess enrichment above baseline for each timepoint: excess_d2H = measured_d2H - baseline_d2H excess_d18O = measured_d18O - baseline_d18O b. Calculate elimination rate constants (per day) using natural log regression: kH = (ln(excess_d2H_day7) - ln(excess_d2H_day14)) / (14 - 7) kO = (ln(excess_d18O_day7) - ln(excess_d18O_day14)) / (14 - 7) c. Estimate total body water (TBW) as 73% of body weight (in moles): TBW_mol = (0.73 * body_weight_kg * 1000) / 18.015 Note: In actual DLW studies, total body water is measured directly from the deuterium dilution space at the initial dose timepoint. The 73% estimate used here is a teaching simplification — the tool's customization section shows how to input measured TBW instead. d. Calculate CO2 production rate (mol/day) using a simplified form of the Speakman approach: rCO2 = (TBW_mol / 2) * (kO - kH) Note: This is a simplified equation that omits isotopic fractionation corrections. The full Speakman (1997) equation includes terms for water vapor fractionation and dilution space differences: rCO2 = (N/2.078)(kO - kH) - 0.0062*kH*N For publication-quality results, use the complete equation. The simplified form here is suitable for teaching and initial estimates. e. Convert rCO2 from mol/day to liters/day: rCO2_L = rCO2 * 22.414 f. Calculate TDEE using the modified Weir equation: TDEE_kcal = rCO2_L * (1.106 + 3.941 / RQ) (This gives kcal/day when rCO2 is in L/day)
3. OUTPUT - PER-SUBJECT CARDS For each subject, display a card showing: - Subject ID, body weight, dose volume - Excess enrichment values at Day 7 and Day 14 (both isotopes) - kH and kO values (per day, 6 decimal places) - kO/kH ratio (should be between 1.0 and 1.4 for valid data; flag if outside) - TBW estimate in liters and moles - rCO2 in mol/day and L/day - TDEE in kcal/day (large, prominent number) - A small validity indicator: green check if kO/kH is 1.0-1.4, yellow warning if 1.4-1.6, red flag if outside 1.0-1.6
4. COMPARISON CHART - Horizontal bar chart (Chart.js) showing TDEE for all subjects, sorted highest to lowest - Color bars by validity status (green/yellow/red matching the kO/kH check) - Show mean TDEE and SD as a vertical reference line with annotation - Second chart: grouped bar comparing kO and kH across subjects
5. SUMMARY TABLE - All subjects in a table with columns: Subject_ID, Weight, TBW, kH, kO, kO/kH, rCO2, TDEE, Status - Sortable by clicking column headers - Footer row with group mean and SD for TDEE - Export button that downloads the table as CSV
6. DESIGN - Dark theme: background #0f172a, cards #1e293b, text #e2e8f0, accent #10b981 - Clean sans-serif font (Inter from Google Fonts CDN) - Responsive single-column layout - "Load Example" and "Clear" buttons at the top - Section headers: "Subject Results", "Cohort Comparison", "Summary"
7. TECHNICAL - Pure HTML/CSS/JS in one file, no build step - Chart.js loaded from CDN (https://cdn.jsdelivr.net/npm/chart.js) - All calculations in plain JavaScript (no external libraries) - CSV parsing handles quoted fields and trailing newlines - Show all intermediate calculations (not just final TDEE) so researchers can verify each stepThat entire block is the prompt. Paste it as-is. The embedded sample data produces realistic TDEE values for adult humans. The kO/kH validity check is critical — it catches data entry errors and failed dosing before they produce nonsensical TDEE values.
What you get
After the LLM finishes (typically 60-90 seconds), you will have a single file: dlw-calculator.html. Open it in any browser.
Expected output structure
dlw-calculator.html (~600-800 lines)Click Load Example and you should see:
- Eight subject cards, each showing the full calculation pipeline from raw enrichment values through to TDEE. Subject TDEE values should range from approximately 2,000 to 3,500 kcal/day for these body weights.
- Validity indicators — all eight subjects should show green checks (kO/kH between 1.0 and 1.4 for well-behaved data).
- Comparison bar chart — horizontal bars sorted by TDEE, with a vertical line showing the cohort mean. The heavier subjects (SUBJ-004 at 91.2 kg) should generally have higher TDEE.
- Summary table — all eight subjects in a sortable table with a footer showing mean TDEE and standard deviation.
If something is off
| Problem | Follow-up prompt |
|---|---|
| TDEE values are astronomically high (>10,000 kcal/day) | The TDEE values are way too high. Check the rCO2 calculation -- make sure TBW is in moles (divide grams by 18.015) and that the Weir equation units are consistent. Print each intermediate value to the console. |
| All kO/kH ratios are below 1.0 | The kO/kH ratios are all below 1.0, which is physiologically impossible. Check that kO and kH are not swapped -- kO (oxygen-18) should always be larger than kH (deuterium) because 18O is eliminated via both CO2 and water. |
| Negative TDEE values | Some subjects show negative TDEE. This means rCO2 is negative, which means kH > kO. Check that the elimination rate constant formula uses the correct sign: k = (ln(excess_early) - ln(excess_late)) / days_elapsed. The excess values at Day 7 should be larger than Day 14. |
How it works (the 2-minute explanation)
- Excess enrichment is the measured delta value minus the pre-dose baseline. This tells you how much isotope the body still retains at each timepoint. Baseline subtraction removes the natural abundance background.
- Elimination rate constants (k) describe how fast each isotope leaves the body. You calculate them from the slope of the natural log of enrichment over time. A steeper slope means faster elimination.
- The key insight: ¹⁸O leaves the body two ways — as water (H₂¹⁸O) and as CO₂ (C¹⁸O₂). Deuterium leaves only as water (²H₂O). The difference between kO and kH is therefore proportional to CO₂ production alone. This is why the method uses two isotopes.
- The Weir equation converts CO₂ production rate to energy expenditure using the respiratory quotient (RQ). A mixed diet gives RQ ≈ 0.85. The relationship between CO₂ production and calories is well-established from decades of indirect calorimetry research.
The DLW method requires you to assume an RQ value because you measure CO₂ production but not O₂ consumption directly. For humans on a typical mixed diet, RQ = 0.85 introduces less than 3% error in TDEE. For studies involving extreme diets (ketogenic, high-carb athletic fueling), the RQ assumption becomes more important and should be adjusted. Some researchers use food diary data to estimate a subject-specific RQ. The tool lets you change the RQ input to test sensitivity.
When Things Go Wrong
Use the Symptom → Evidence → Request pattern: describe what you see, paste the error, then ask for a fix.
Customize it
Add a body composition adjustment
Replace the fixed 73% body water estimate with an option to enter actual TBWmeasured by deuterium dilution. Add a toggle: "Use estimated TBW (73% body weight)"vs "Enter measured TBW (liters)." When measured TBW is selected, show an inputfield for each subject. Recalculate TDEE using the measured values and show thepercentage difference from the estimated method.Add multi-timepoint support
Extend the calculator to accept more than two post-dose timepoints. Instead ofjust Day 7 and Day 14, allow any number of timepoints (e.g., Day 1, Day 3, Day 7,Day 10, Day 14). Calculate kH and kO using linear regression of ln(excess) vstime across all timepoints instead of the two-point method. Show the regressionplots with R-squared values for each subject and isotope.Add PAL (Physical Activity Level) classification
After calculating TDEE, estimate basal metabolic rate (BMR) using theSchofield equation based on body weight and an age/sex input. Calculate thePhysical Activity Level (PAL = TDEE / BMR) for each subject. Classify PAL as:sedentary (1.2-1.4), lightly active (1.4-1.6), moderately active (1.6-1.9),very active (1.9-2.5). Add PAL to the summary table and subject cards.Start with the core TDEE calculator, then add features based on your study design. Multi-timepoint regression is the most common upgrade because many DLW protocols collect samples on 4-6 days for better precision. PAL classification adds physiological context that makes the numbers interpretable for non-specialists.
Try it yourself
- Open your CLI tool in an empty folder.
- Paste the main prompt from above.
- Open
dlw-calculator.htmlin your browser. - Click Load Example to see TDEE calculations for eight subjects.
- Try changing the RQ value from 0.85 to 0.80 or 0.90 and observe how TDEE changes (it should shift by 2-4%).
If you have real DLW data from a study, format it to match the expected CSV columns and upload it. Check that the kO/kH ratios fall between 1.0 and 1.4 — if they do not, the isotope measurements may need to be re-examined.
Key takeaways
- The DLW method relies on the difference between two elimination rates — ¹⁸O leaves via both CO₂ and water, while ²H leaves only via water. The difference equals CO₂ production.
- Multi-step scientific calculations are perfect for single-file browser tools — showing every intermediate value lets researchers verify the pipeline and catch errors that spreadsheets hide.
- The kO/kH ratio is your built-in validity check — values outside 1.0-1.4 indicate measurement problems (sample contamination, dosing error, or analytical issues). The tool flags these automatically.
- Assumed RQ introduces small but real uncertainty — for most studies RQ = 0.85 is acceptable, but the tool lets you test sensitivity by adjusting the input.
The DLW method uses two isotopes (²H and ¹⁸O) instead of one. Why is a single isotope insufficient for measuring energy expenditure?
A subject's calculated kO/kH ratio is 0.85. What does this indicate?
You change the assumed RQ from 0.85 to 0.90 (slightly more carbohydrate-heavy diet). How does this affect the calculated TDEE?
What’s next
In the next lesson, you will build a Chain-of-Custody Case Tracker — a timestamped field excavation log with printable PDF custody receipts for forensic sample management. Same single-file HTML pattern, applied to evidence tracking instead of isotope calculations.