Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add the Waist-to-height ratio and per-exercise 1RM calculated types
Roland Geider6f6ef36c8c88
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex f1fb0b3e2..5cfcdefee 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -186,6 +186,11 @@ class CategorySerializer(serializers.ModelSerializer):except jsonschema.exceptions.ValidationError as e:raise serializers.ValidationError({'dynamic_params': e.message})+ try:+ calc.validate_params(self._get_user_id(), dynamic_params)+ except ValueError as e:+ raise serializers.ValidationError({'dynamic_params': str(e)})+def _validate_unique_metric_type(self, metric_type):"""Only one category per metric type and user.diff --git a/wger/measurements/dynamic/base.py b/wger/measurements/dynamic/base.pyindex 7a410c099..e0a2b9f4c 100644--- a/wger/measurements/dynamic/base.py+++ b/wger/measurements/dynamic/base.py@@ -78,6 +78,13 @@ class DynamicMeasurementType:"""raise NotImplementedError+ def validate_params(self, user_id: int, params: dict) -> None:+ """+ Semantic checks beyond the shape of the params, e.g. that a referenced+ row exists and belongs to the user. Raises ValueError with the message+ to show.+ """+_registry: dict[str, DynamicMeasurementType] = {}diff --git a/wger/measurements/dynamic/engine.py b/wger/measurements/dynamic/engine.pyindex 5cccca571..381d64856 100644--- a/wger/measurements/dynamic/engine.py+++ b/wger/measurements/dynamic/engine.py@@ -95,20 +95,29 @@ def reconcile_by_id(category_id) -> None:def schedule_reconcile(category_id) -> None:"""- Queues a reconcile for after the current transaction, deduplicated so a- batch of source writes triggers one recompute rather than one per row+ Queues a reconcile for after the current transaction.++ Every call registers a callback, the deduplication happens when they run:+ the first one of a flush does the work and marks the category, the+ duplicates of the same batch see the mark and return. Marking on+ execution rather than on registration keeps a rolled-back transaction+ (whose callbacks Django discards) from blocking later reconciles."""- ids = getattr(_pending, 'ids', None)- if ids is None:- ids = _pending.ids = set()- if category_id in ids:- return- ids.add(category_id)+ done = getattr(_pending, 'done', None)+ if done:+ # A new write batch begins, the marks of the previous flush are stale+ done.clear()transaction.on_commit(lambda: _run_scheduled(category_id))def _run_scheduled(category_id) -> None:- getattr(_pending, 'ids', set()).discard(category_id)+ done = getattr(_pending, 'done', None)+ if done is None:+ done = _pending.done = set()+ if category_id in done:+ return+ done.add(category_id)+if settings.WGER_SETTINGS['USE_CELERY']:# wgerfrom wger.measurements.tasks import reconcile_dynamic_category_taskdiff --git a/wger/measurements/dynamic/types.py b/wger/measurements/dynamic/types.pyindex 387788dae..1e90d2705 100644--- a/wger/measurements/dynamic/types.py+++ b/wger/measurements/dynamic/types.py@@ -13,8 +13,23 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+# Standard Library+import uuid+from decimal import Decimal++# Django+from django.core.exceptions import ValidationError as DjangoValidationError+# wgerfrom wger.core.models import UserProfile+from wger.exercises.models import Exercise+from wger.manager.consts import (+ REP_UNIT_REPETITIONS,+ WEIGHT_UNIT_KG,+ WEIGHT_UNIT_LB,+)+from wger.manager.helpers import brzycki_one_rm+from wger.manager.models import WorkoutLogfrom wger.measurements.dynamic.base import (Dependency,DesiredRow,@@ -26,7 +41,10 @@ from wger.measurements.models import (Measurement,)from wger.measurements.models.category import MetricType+from wger.measurements.models.measurement import MeasurementSourcefrom wger.measurements.utils.bmi import calculate_bmi+from wger.utils.constants import TWOPLACES+from wger.utils.units import AbstractWeight@register@@ -58,3 +76,131 @@ class Bmi(DynamicMeasurementType):)for row in calculate_bmi(category.user)]+++@register+class WaistToHeightRatio(DynamicMeasurementType):+ """+ One ratio entry per entry of the configured source category, divided by+ the height of the profile. Both are read as centimeters.+ """++ slug = Category.DynamicType.WHTR+ label = 'Waist-to-height ratio'+ params_schema = {+ 'type': 'object',+ 'properties': {'category_id': {'type': 'string'}},+ 'required': ['category_id'],+ 'additionalProperties': False,+ }+ depends_on = [+ Dependency(Measurement, user_id=lambda entry: entry.category.user_id),+ Dependency(UserProfile, user_id=lambda profile: profile.user_id),+ ]++ def validate_params(self, user_id, params):+ source = self._source_category(user_id, params)+ if source is None:+ raise ValueError('The source category does not exist')+ if source.dynamic_type != Category.DynamicType.NONE:+ raise ValueError('A calculated category cannot be the source of another one')++ @staticmethod+ def _source_category(user_id, params) -> Category | None:+ """+ The category the ratio reads from; the user filter is the ownership+ boundary+ """+ try:+ return Category.objects.get(pk=params.get('category_id'), user_id=user_id)+ except (Category.DoesNotExist, DjangoValidationError, ValueError, TypeError):+ return None++ def compute(self, category: Category) -> list[DesiredRow]:+ profile = category.user.userprofile+ if not profile.height or profile.height <= 0:+ return []++ source = self._source_category(category.user_id, category.dynamic_params)+ if source is None or source.pk == category.pk:+ return []++ height = Decimal(profile.height)+ entries = Measurement.objects.filter(category=source).exclude(+ source=MeasurementSource.CALCULATED+ )+ return [+ DesiredRow(+ external_id=entry.pk,+ date=entry.date,+ value=round(entry.value / height, 2),+ )+ for entry in entries+ ]+++@register+class OneRepMax(DynamicMeasurementType):+ """+ One entry per calendar day (UTC) with qualifying logs of the configured+ exercise: the highest Brzycki estimate of that day, in kg. Only sets of+ at most max_reps repetitions count, both because low-rep sets are what a+ 1RM estimate is about and because the formula degrades at high counts.+ """++ DEFAULT_MAX_REPS = 5++ slug = Category.DynamicType.ONE_REP_MAX+ label = '1RM'+ params_schema = {+ 'type': 'object',+ 'properties': {+ 'exercise_id': {'type': 'integer', 'minimum': 1},+ 'max_reps': {'type': 'integer', 'minimum': 1, 'maximum': 10},+ },+ 'required': ['exercise_id'],+ 'additionalProperties': False,+ }+ depends_on = [+ Dependency(WorkoutLog, user_id=lambda log: log.user_id),+ ]++ def validate_params(self, user_id, params):+ if not Exercise.objects.filter(pk=params.get('exercise_id')).exists():+ raise ValueError('The exercise does not exist')++ def compute(self, category: Category) -> list[DesiredRow]:+ params = category.dynamic_params+ max_reps = params.get('max_reps', self.DEFAULT_MAX_REPS)++ logs = WorkoutLog.objects.filter(+ user_id=category.user_id,+ exercise_id=params.get('exercise_id'),+ repetitions__gte=1,+ repetitions__lte=max_reps,+ repetitions_unit_id=REP_UNIT_REPETITIONS,+ weight__gt=0,+ weight_unit_id__in=(WEIGHT_UNIT_KG, WEIGHT_UNIT_LB),+ )++ # Per day the set with the highest estimate; the datetime breaks ties+ best = {}+ for log in logs:+ weight = (+ log.weight+ if log.weight_unit_id == WEIGHT_UNIT_KG+ else AbstractWeight(log.weight, 'lb').kg+ )+ one_rm = brzycki_one_rm(weight, log.repetitions).quantize(TWOPLACES)+ day = log.date.date()+ if day not in best or (one_rm, log.date) > best[day]:+ best[day] = (one_rm, log.date)++ return [+ DesiredRow(+ external_id=uuid.uuid5(category.pk, day.isoformat()),+ date=date,+ value=value,+ )+ for day, (value, date) in best.items()+ ]diff --git a/wger/measurements/migrations/0008_dynamic_type.py b/wger/measurements/migrations/0008_dynamic_type.pyindex da45e0a4b..51098146c 100644--- a/wger/measurements/migrations/0008_dynamic_type.py+++ b/wger/measurements/migrations/0008_dynamic_type.py@@ -22,7 +22,12 @@ class Migration(migrations.Migration):model_name='category',name='dynamic_type',field=models.CharField(- choices=[('NONE', 'None'), ('BMI', 'BMI')],+ choices=[+ ('NONE', 'None'),+ ('BMI', 'BMI'),+ ('WHTR', 'Waist-to-height ratio'),+ ('ONE_REP_MAX', '1RM'),+ ],db_index=True,default='NONE',max_length=20,diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.pyindex f54789bae..30abbd888 100644--- a/wger/measurements/models/category.py+++ b/wger/measurements/models/category.py@@ -250,6 +250,8 @@ class Category(models.Model):class DynamicType(models.TextChoices):NONE = 'NONE', 'None'BMI = 'BMI', 'BMI'+ WHTR = 'WHTR', 'Waist-to-height ratio'+ ONE_REP_MAX = 'ONE_REP_MAX', '1RM'dynamic_type = models.CharField(max_length=20, choices=DynamicType.choices, default=DynamicType.NONE, db_index=Truediff --git a/wger/measurements/tests/test_dynamic.py b/wger/measurements/tests/test_dynamic.pyindex 1f25be87a..6e2cf5809 100644--- a/wger/measurements/tests/test_dynamic.py+++ b/wger/measurements/tests/test_dynamic.py@@ -27,6 +27,8 @@ from rest_framework import status# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.manager.consts import WEIGHT_UNIT_LB+from wger.manager.models import WorkoutLogfrom wger.measurements.models import (Category,Measurement,@@ -386,3 +388,289 @@ class DynamicCategoryApiTestCase(DynamicMeasurementTestCase):rows = self.calculated_rows(Category.objects.get(pk=response.data['id']))self.assertEqual(rows.count(), 1)self.assertEqual(rows[0].value, Decimal('25.00'))+++class WhtrTestCase(DynamicMeasurementTestCase):+ """+ The waist-to-height ratio derives from a user-chosen source category+ """++ def setUp(self):+ super().setUp()+ self.waist = Category.objects.create(user=self.user, name='Waist', unit='cm')++ def create_waist(self, value, days_ago: int = 0) -> Measurement:+ with self.captureOnCommitCallbacks(execute=True):+ entry = Measurement.objects.create(+ category=self.waist,+ date=timezone.now() - datetime.timedelta(days=days_ago),+ value=Decimal(value),+ )+ return entry++ def enable_whtr(self, source: Category = None) -> Category:+ with self.captureOnCommitCallbacks(execute=True):+ category = Category.objects.create(+ user=self.user,+ name='WHtR',+ unit='',+ dynamic_type=Category.DynamicType.WHTR,+ dynamic_params={'category_id': str((source or self.waist).pk)},+ )+ return category++ def test_backfill(self):+ """+ Enabling the ratio computes one row per source entry+ """+ self.create_waist('90.00', days_ago=10)+ self.create_waist('99.00')++ category = self.enable_whtr()+ rows = self.calculated_rows(category)++ # height 180: 90 / 180 = 0.50, 99 / 180 = 0.55+ self.assertEqual(rows.count(), 2)+ self.assertEqual(rows[0].value, Decimal('0.50'))+ self.assertEqual(rows[1].value, Decimal('0.55'))++ def test_source_entry_update_recomputes(self):+ """+ Editing a source entry updates its ratio row+ """+ entry = self.create_waist('90.00')+ category = self.enable_whtr()++ with self.captureOnCommitCallbacks(execute=True):+ entry.value = Decimal('81.00')+ entry.save()++ rows = self.calculated_rows(category)+ self.assertEqual(rows[0].value, Decimal('0.45'))++ def test_foreign_source_stays_empty(self):+ """+ Params pointing at another user's category yield no rows+ """+ admin = User.objects.get(username='admin')+ foreign = Category.objects.create(user=admin, name='Waist', unit='cm')+ Measurement.objects.create(+ category=foreign,+ date=timezone.now(),+ value=Decimal('90.00'),+ )++ category = self.enable_whtr(source=foreign)+ self.assertEqual(self.calculated_rows(category).count(), 0)++ def test_api_refuses_foreign_source(self):+ """+ Creating a ratio category over another user's category returns a 400+ """+ admin = User.objects.get(username='admin')+ foreign = Category.objects.create(user=admin, name='Waist', unit='cm')++ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'WHtR',+ 'unit': '',+ 'dynamic_type': 'WHTR',+ 'dynamic_params': {'category_id': str(foreign.pk)},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn('dynamic_params', response.data)++ def test_api_refuses_dynamic_source(self):+ """+ A calculated category cannot be the source of another one+ """+ bmi = self.enable_bmi()++ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'WHtR',+ 'unit': '',+ 'dynamic_type': 'WHTR',+ 'dynamic_params': {'category_id': str(bmi.pk)},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_api_requires_source(self):+ """+ The category_id param is mandatory+ """+ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {'name': 'WHtR', 'unit': '', 'dynamic_type': 'WHTR'},+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class OneRepMaxTestCase(DynamicMeasurementTestCase):+ """+ The 1RM type condenses the workout logs of one exercise into one+ estimate per day+ """++ def make_log(+ self,+ weight,+ reps,+ days_ago: int = 0,+ weight_unit: int = 1,+ exercise_id: int = 1,+ ) -> WorkoutLog:+ with self.captureOnCommitCallbacks(execute=True):+ log = WorkoutLog(+ user=self.user,+ exercise_id=exercise_id,+ weight=Decimal(weight),+ repetitions=Decimal(reps),+ weight_unit_id=weight_unit,+ date=timezone.now() - datetime.timedelta(days=days_ago),+ )+ log.save()+ return log++ def enable_one_rm(self, **params) -> Category:+ with self.captureOnCommitCallbacks(execute=True):+ category = Category.objects.create(+ user=self.user,+ name='1RM',+ unit='kg',+ dynamic_type=Category.DynamicType.ONE_REP_MAX,+ dynamic_params={'exercise_id': 1, **params},+ )+ return category++ def test_backfill_best_set_per_day(self):+ """+ Each day with logs gets one row holding its highest estimate+ """+ self.make_log('100', 5)+ self.make_log('90', 5)+ self.make_log('80', 3, days_ago=3)++ category = self.enable_one_rm()+ rows = self.calculated_rows(category)++ self.assertEqual(rows.count(), 2)+ # Brzycki: 80 / (1.0278 - 0.0278 * 3), 100 / (1.0278 - 0.0278 * 5)+ self.assertEqual(rows[0].value, Decimal('84.71'))+ self.assertEqual(rows[1].value, Decimal('112.51'))++ def test_high_rep_sets_are_ignored(self):+ """+ Sets over max_reps do not enter the estimate+ """+ self.make_log('120', 8)+ self.make_log('100', 5)++ category = self.enable_one_rm()+ rows = self.calculated_rows(category)++ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('112.51'))++ def test_max_reps_param(self):+ """+ The rep cap is configurable+ """+ self.make_log('120', 8)++ category = self.enable_one_rm(max_reps=8)+ rows = self.calculated_rows(category)++ self.assertEqual(rows.count(), 1)+ # 120 / (1.0278 - 0.0278 * 8)+ self.assertEqual(rows[0].value, Decimal('148.99'))++ def test_pound_logs_are_converted(self):+ """+ A log in lb is converted to kg before the formula+ """+ self.make_log('100', 1, weight_unit=WEIGHT_UNIT_LB)++ category = self.enable_one_rm()+ rows = self.calculated_rows(category)++ # 100 lb = 45.36 kg, at one rep the estimate is the weight itself+ self.assertEqual(rows[0].value, Decimal('45.36'))++ def test_other_exercises_are_ignored(self):+ """+ Only logs of the configured exercise count+ """+ self.make_log('100', 5, exercise_id=2)++ category = self.enable_one_rm()+ self.assertEqual(self.calculated_rows(category).count(), 0)++ def test_new_log_adds_row(self):+ """+ A log written after the category exists gets its day row+ """+ category = self.enable_one_rm()+ self.make_log('100', 5)++ rows = self.calculated_rows(category)+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('112.51'))++ def test_deleted_log_removes_day(self):+ """+ Deleting the only log of a day deletes the day's row+ """+ log = self.make_log('100', 5)+ category = self.enable_one_rm()+ self.assertEqual(self.calculated_rows(category).count(), 1)++ with self.captureOnCommitCallbacks(execute=True):+ log.delete()++ self.assertEqual(self.calculated_rows(category).count(), 0)++ def test_api_refuses_unknown_exercise(self):+ """+ An exercise id that does not exist returns a 400+ """+ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': '1RM',+ 'unit': 'kg',+ 'dynamic_type': 'ONE_REP_MAX',+ 'dynamic_params': {'exercise_id': 999999},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn('dynamic_params', response.data)++ def test_api_refuses_out_of_range_cap(self):+ """+ The rep cap is bounded by the validity of the formula+ """+ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': '1RM',+ 'unit': 'kg',+ 'dynamic_type': 'ONE_REP_MAX',+ 'dynamic_params': {'exercise_id': 1, 'max_reps': 15},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)