Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add energy calculation sanity check

Roland Geidere5309a710954
diff --git a/wger/nutrition/consts.py b/wger/nutrition/consts.py
index c2da2929a..581b4eb2d 100644
--- a/wger/nutrition/consts.py
+++ b/wger/nutrition/consts.py
@@ -34,9 +34,25 @@ ENERGY_FACTOR = {
'protein': {'kg': 4, 'lb': 113},
'carbohydrates': {'kg': 4, 'lb': 113},
'fat': {'kg': 9, 'lb': 225},
+ 'fiber': {'kg': 2, 'lb': 57},
}
"""
Simple approximation of energy (kcal) provided per gram or ounce
+
+The values are the conversion factors from EU Regulation 1169/2011, Annex XIV
+"""
+
+ENERGY_CHECK_MIN_KCAL = 13
+ENERGY_CHECK_TOLERANCE_RELATIVE = 0.3
+ENERGY_CHECK_TOLERANCE_ABSOLUTE_KCAL = 5
+"""
+Thresholds for comparing the declared energy of an ingredient with the energy
+computed from its macronutrients. These match the ones Open Food Facts uses for
+its "energy-value-in-kcal-does-not-match-value-computed-from-other-nutrients"
+data quality check: values of up to 13 kcal are not checked at all (too many
+false positives) and larger ones may deviate by 30% plus a flat 5 kcal, since
+nutrients we do not track (polyols, organic acids, alcohol) also contribute to
+the declared energy.
"""
KJ_PER_KCAL = 4.184
diff --git a/wger/nutrition/dataclasses.py b/wger/nutrition/dataclasses.py
index 0a1171e35..80df909f0 100644
--- a/wger/nutrition/dataclasses.py
+++ b/wger/nutrition/dataclasses.py
@@ -20,6 +20,12 @@ from dataclasses import (
from typing import Optional
# wger
+from wger.nutrition.consts import (
+ ENERGY_CHECK_MIN_KCAL,
+ ENERGY_CHECK_TOLERANCE_ABSOLUTE_KCAL,
+ ENERGY_CHECK_TOLERANCE_RELATIVE,
+ ENERGY_FACTOR,
+)
from wger.nutrition.helpers import (
change_html_entities_to_human_readable,
remove_problematic_characters,
@@ -109,6 +115,31 @@ class IngredientData:
if self.nutriscore is not None and self.nutriscore not in ('a', 'b', 'c', 'd', 'e'):
raise ValueError(f'Invalid nutriscore value: {self.nutriscore}')
+ # Energy plausibility: the declared energy must roughly match the energy
+ # computed from the macronutrients. Fiber counts with 2 kcal/g since it is
+ # usually not included in the carbohydrate value. See the comments on the
+ # threshold constants in consts.py for the tolerances used.
+ energy_computed = (
+ self.protein * ENERGY_FACTOR['protein']['kg']
+ + self.carbohydrates * ENERGY_FACTOR['carbohydrates']['kg']
+ + self.fat * ENERGY_FACTOR['fat']['kg']
+ + (self.fiber or 0) * ENERGY_FACTOR['fiber']['kg']
+ )
+ if self.energy > ENERGY_CHECK_MIN_KCAL or energy_computed > ENERGY_CHECK_MIN_KCAL:
+ energy_lower = (
+ self.energy * (1 - ENERGY_CHECK_TOLERANCE_RELATIVE)
+ - ENERGY_CHECK_TOLERANCE_ABSOLUTE_KCAL
+ )
+ energy_upper = (
+ self.energy * (1 + ENERGY_CHECK_TOLERANCE_RELATIVE)
+ + ENERGY_CHECK_TOLERANCE_ABSOLUTE_KCAL
+ )
+ if not (energy_lower <= energy_computed <= energy_upper):
+ raise ValueError(
+ f'Energy computed from the macronutrients ({energy_computed:.0f} kcal) '
+ f'does not match the declared energy ({self.energy:.0f} kcal)'
+ )
+
def dict(self):
data = asdict(self)
data.pop('serving_size_gram', None)
diff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.py
index 6e02f1655..f42bfd3f0 100644
--- a/wger/nutrition/models/ingredient.py
+++ b/wger/nutrition/models/ingredient.py
@@ -102,12 +102,6 @@ class Ingredient(AbstractLicenseModel, models.Model):
),
)
- ENERGY_APPROXIMATION = 15
- """
- How much the calculated energy from protein, etc. can deviate from the
- energy amount given (in percent).
- """
-
objects = ApproximateCountManager()
language = models.ForeignKey(
diff --git a/wger/nutrition/tests/test_dataclass.py b/wger/nutrition/tests/test_dataclass.py
index 37c5363f3..edcc0def4 100644
--- a/wger/nutrition/tests/test_dataclass.py
+++ b/wger/nutrition/tests/test_dataclass.py
@@ -70,6 +70,7 @@ class IngredientDataclassTestCase(SimpleTestCase):
self.ingredient_data.protein = 12
self.ingredient_data.carbohydrates = 45
self.ingredient_data.fat = 47
+ self.ingredient_data.energy = 604
self.assertEqual(self.ingredient_data.sanity_checks(), None)
def test_validation_macro_sum_over_tolerance(self):
@@ -97,6 +98,42 @@ class IngredientDataclassTestCase(SimpleTestCase):
self.ingredient_data.carbohydrates_sugar = 30
self.assertRaises(ValueError, self.ingredient_data.sanity_checks)
+ def test_validation_energy_mismatch(self):
+ """
+ Test that a declared energy far off the computed one is rejected
+ """
+ self.ingredient_data.energy = 700
+ self.assertRaises(ValueError, self.ingredient_data.sanity_checks)
+
+ def test_validation_energy_within_tolerance(self):
+ """
+ Test that a declared energy within the tolerance is accepted
+ """
+ # Computed energy is 32.1*4 + 3.24*9 = 157.56 kcal
+ self.ingredient_data.energy = 200
+ self.assertEqual(self.ingredient_data.sanity_checks(), None)
+
+ def test_validation_energy_fiber_counts(self):
+ """
+ Test that fiber contributes 2 kcal/g to the computed energy
+ """
+ self.ingredient_data.protein = 0
+ self.ingredient_data.carbohydrates = 0
+ self.ingredient_data.fat = 0
+ self.ingredient_data.fiber = 50
+ self.ingredient_data.energy = 100
+ self.assertEqual(self.ingredient_data.sanity_checks(), None)
+
+ def test_validation_energy_low_values_skipped(self):
+ """
+ Test that very low energy values are not checked at all
+ """
+ self.ingredient_data.protein = 0
+ self.ingredient_data.carbohydrates = 0
+ self.ingredient_data.fat = 0
+ self.ingredient_data.energy = 13
+ self.assertEqual(self.ingredient_data.sanity_checks(), None)
+
def test_validation_nutriscore_valid(self):
"""
Test that valid nutriscore values are accepted