feat: Update nutrition metrics and energy balance calculations
- Introduced a single TDEE calculation based on current weight, replacing the fixed 2500 kcal value. - Updated `get_energy_balance_data` to use daily totals for intake calculations and improved energy balance logic. - Enhanced `get_nutrition_average_data` to calculate averages over calendar days instead of raw log entries. - Adjusted placeholder resolution to ensure consistent metadata usage across requests. - Fixed issues in the charts router to reflect the new energy balance logic and TDEE calculations. These changes improve the accuracy of nutritional assessments and streamline data handling in the application.
This commit is contained in:
1 parent
549c31431e
commit
61a5bb39ae
7 files changed
+305
-231
No files matched your search
+49
-29
@@ -35,7 +35,8 @@ from data_layer.nutrition_metrics import (
|
||||
get_nutrition_average_data,
|
||||
get_protein_targets_data,
|
||||
get_protein_adequacy_data,
|
||||
get_macro_consistency_data
|
||||
get_macro_consistency_data,
|
||||
get_energy_balance_data,
|
||||
)
|
||||
from data_layer.activity_metrics import (
|
||||
get_activity_summary_data,
|
||||
@@ -346,17 +347,20 @@ def get_energy_balance_chart(
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
|
||||
balance_meta = get_energy_balance_data(profile_id, days)
|
||||
|
||||
from db import get_db, get_cursor
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT date, kcal
|
||||
"""SELECT date, SUM(kcal)::float AS kcal
|
||||
FROM nutrition_log
|
||||
WHERE profile_id=%s AND date >= %s AND kcal IS NOT NULL
|
||||
GROUP BY date
|
||||
ORDER BY date""",
|
||||
(profile_id, cutoff)
|
||||
(profile_id, cutoff),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
@@ -374,7 +378,21 @@ def get_energy_balance_chart(
|
||||
}
|
||||
}
|
||||
|
||||
# Prepare data
|
||||
estimated_tdee = balance_meta.get("estimated_tdee") or 0
|
||||
if estimated_tdee <= 0:
|
||||
return {
|
||||
"chart_type": "line",
|
||||
"data": {
|
||||
"labels": [],
|
||||
"datasets": []
|
||||
},
|
||||
"metadata": {
|
||||
"confidence": "insufficient",
|
||||
"data_points": len(rows),
|
||||
"message": "Kein Gewicht für TDEE-Schätzung (weight_log erforderlich)"
|
||||
}
|
||||
}
|
||||
|
||||
labels = []
|
||||
daily_values = []
|
||||
avg_7d = []
|
||||
@@ -384,23 +402,19 @@ def get_energy_balance_chart(
|
||||
labels.append(row['date'].isoformat())
|
||||
daily_values.append(safe_float(row['kcal']))
|
||||
|
||||
# 7d rolling average
|
||||
start_7d = max(0, i - 6)
|
||||
window_7d = [safe_float(rows[j]['kcal']) for j in range(start_7d, i + 1)]
|
||||
avg_7d.append(round(sum(window_7d) / len(window_7d), 1) if window_7d else None)
|
||||
|
||||
# 14d rolling average
|
||||
start_14d = max(0, i - 13)
|
||||
window_14d = [safe_float(rows[j]['kcal']) for j in range(start_14d, i + 1)]
|
||||
avg_14d.append(round(sum(window_14d) / len(window_14d), 1) if window_14d else None)
|
||||
|
||||
# Calculate TDEE (estimated, should come from profile)
|
||||
# TODO: Calculate from profile (weight, height, age, activity level)
|
||||
estimated_tdee = 2500.0
|
||||
|
||||
# Calculate deficit/surplus
|
||||
avg_intake = sum(daily_values) / len(daily_values) if daily_values else 0
|
||||
energy_balance = avg_intake - estimated_tdee
|
||||
avg_intake = float(balance_meta.get("avg_intake") or (sum(daily_values) / len(daily_values) if daily_values else 0))
|
||||
energy_balance = float(balance_meta.get("energy_balance") or (avg_intake - estimated_tdee))
|
||||
balance_status = balance_meta.get("status") or (
|
||||
"deficit" if energy_balance < -200 else "surplus" if energy_balance > 200 else "maintenance"
|
||||
)
|
||||
|
||||
datasets = [
|
||||
{
|
||||
@@ -443,8 +457,7 @@ def get_energy_balance_chart(
|
||||
}
|
||||
]
|
||||
|
||||
from data_layer.utils import calculate_confidence
|
||||
confidence = calculate_confidence(len(rows), days, "general")
|
||||
confidence = balance_meta.get("confidence") or "low"
|
||||
|
||||
return {
|
||||
"chart_type": "line",
|
||||
@@ -458,7 +471,7 @@ def get_energy_balance_chart(
|
||||
"avg_kcal": round(avg_intake, 1),
|
||||
"estimated_tdee": estimated_tdee,
|
||||
"energy_balance": round(energy_balance, 1),
|
||||
"balance_status": "deficit" if energy_balance < -200 else "surplus" if energy_balance > 200 else "maintenance",
|
||||
"balance_status": balance_status,
|
||||
"first_date": rows[0]['date'],
|
||||
"last_date": rows[-1]['date']
|
||||
})
|
||||
@@ -587,11 +600,12 @@ def get_protein_adequacy_chart(
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT date, protein_g
|
||||
"""SELECT date, SUM(protein_g)::float AS protein_g
|
||||
FROM nutrition_log
|
||||
WHERE profile_id=%s AND date >= %s AND protein_g IS NOT NULL
|
||||
GROUP BY date
|
||||
ORDER BY date""",
|
||||
(profile_id, cutoff)
|
||||
(profile_id, cutoff),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
@@ -687,7 +701,6 @@ def get_protein_adequacy_chart(
|
||||
from data_layer.utils import calculate_confidence
|
||||
confidence = calculate_confidence(len(rows), days, "general")
|
||||
|
||||
# Count days in target
|
||||
days_in_target = sum(1 for v in daily_values if target_low <= v <= target_high)
|
||||
|
||||
return {
|
||||
@@ -978,16 +991,23 @@ def get_nutrition_adherence_score(
|
||||
|
||||
# Get nutrition data
|
||||
cur.execute(
|
||||
"""SELECT COUNT(*) as cnt,
|
||||
AVG(kcal) as avg_kcal,
|
||||
STDDEV(kcal) as std_kcal,
|
||||
AVG(protein_g) as avg_protein,
|
||||
AVG(carbs_g) as avg_carbs,
|
||||
AVG(fat_g) as avg_fat
|
||||
FROM nutrition_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
AND kcal IS NOT NULL""",
|
||||
(profile_id, cutoff)
|
||||
"""WITH daily AS (
|
||||
SELECT date,
|
||||
COALESCE(SUM(kcal), 0)::float AS dk,
|
||||
COALESCE(SUM(protein_g), 0)::float AS dp,
|
||||
COALESCE(SUM(carbs_g), 0)::float AS dc,
|
||||
COALESCE(SUM(fat_g), 0)::float AS df FROM nutrition_log
|
||||
WHERE profile_id=%s AND date >= %s AND kcal IS NOT NULL
|
||||
GROUP BY date
|
||||
)
|
||||
SELECT COUNT(*)::int AS cnt,
|
||||
AVG(dk) AS avg_kcal,
|
||||
STDDEV(dk) AS std_kcal,
|
||||
AVG(dp) AS avg_protein,
|
||||
AVG(dc) AS avg_carbs,
|
||||
AVG(df) AS avg_fat
|
||||
FROM daily""",
|
||||
(profile_id, cutoff),
|
||||
)
|
||||
stats = cur.fetchone()
|
||||
|
||||
|
||||
Reference in new issue
Block a user