Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add the 1RM total calculated type
Roland Geider8dd631d5a49b
diff --git a/wger/measurements/dynamic/types.py b/wger/measurements/dynamic/types.pyindex 1e90d2705..af2deeb9e 100644--- a/wger/measurements/dynamic/types.py+++ b/wger/measurements/dynamic/types.py@@ -14,6 +14,7 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.# Standard Library+import datetimeimport uuidfrom decimal import Decimal@@ -139,24 +140,61 @@ class WaistToHeightRatio(DynamicMeasurementType):]+DEFAULT_MAX_REPS = 5+DEFAULT_WINDOW_DAYS = 30++MAX_REPS_SCHEMA = {'type': 'integer', 'minimum': 1, 'maximum': 10}+++def daily_best_estimates(user_id: int, exercise_id, max_reps) -> dict:+ """+ Per calendar day (UTC) the best Brzycki estimate among the qualifying+ sets of the exercise, as day -> (value in kg, datetime of the set).++ Qualifying means: 1 to max_reps repetitions counted in repetitions, a+ weight over zero in kg or lb. The rep cap exists both because low-rep+ sets are what a 1RM estimate is about and because the formula degrades+ at high counts.+ """+ logs = WorkoutLog.objects.filter(+ user_id=user_id,+ exercise_id=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 best++@registerclass 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.+ exercise: the highest Brzycki estimate of that day, in kg"""- DEFAULT_MAX_REPS = 5-slug = Category.DynamicType.ONE_REP_MAXlabel = '1RM'params_schema = {'type': 'object','properties': {'exercise_id': {'type': 'integer', 'minimum': 1},- 'max_reps': {'type': 'integer', 'minimum': 1, 'maximum': 10},+ 'max_reps': MAX_REPS_SCHEMA,},'required': ['exercise_id'],'additionalProperties': False,@@ -171,31 +209,12 @@ class OneRepMax(DynamicMeasurementType):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),+ best = daily_best_estimates(+ category.user_id,+ params.get('exercise_id'),+ params.get('max_reps', DEFAULT_MAX_REPS),)- # 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()),@@ -204,3 +223,82 @@ class OneRepMax(DynamicMeasurementType):)for day, (value, date) in best.items()]+++@register+class OneRmTotal(DynamicMeasurementType):+ """+ One entry per day any of the configured exercises was trained: the sum+ of the exercises' best estimates in the rolling window ending that day,+ in kg. The window says "what you can lift right now", so a lift whose+ last heavy set expired lowers the total at the next training day.++ A day only gets an entry when every exercise has a qualifying set in+ its window, a partial total would read as a drop.+ """++ slug = Category.DynamicType.ONE_RM_TOTAL+ label = '1RM total'+ params_schema = {+ 'type': 'object',+ 'properties': {+ 'exercise_ids': {+ 'type': 'array',+ 'items': {'type': 'integer', 'minimum': 1},+ 'minItems': 2,+ 'maxItems': 5,+ 'uniqueItems': True,+ },+ 'max_reps': MAX_REPS_SCHEMA,+ 'window_days': {'type': 'integer', 'minimum': 7, 'maximum': 120},+ },+ 'required': ['exercise_ids'],+ 'additionalProperties': False,+ }+ depends_on = [+ Dependency(WorkoutLog, user_id=lambda log: log.user_id),+ ]++ def validate_params(self, user_id, params):+ exercise_ids = params.get('exercise_ids') or []+ found = Exercise.objects.filter(pk__in=exercise_ids).count()+ if found != len(exercise_ids):+ raise ValueError('One or more of the exercises do not exist')++ def compute(self, category: Category) -> list[DesiredRow]:+ params = category.dynamic_params+ max_reps = params.get('max_reps', DEFAULT_MAX_REPS)+ window = datetime.timedelta(days=params.get('window_days', DEFAULT_WINDOW_DAYS))++ per_exercise = [+ daily_best_estimates(category.user_id, exercise_id, max_reps)+ for exercise_id in params.get('exercise_ids', [])+ ]+ if not per_exercise:+ return []++ rows = []+ training_days = sorted(set().union(*(days.keys() for days in per_exercise)))+ for day in training_days:+ floor = day - window++ total = Decimal(0)+ for days in per_exercise:+ in_window = [entry for d, entry in days.items() if floor < d <= day]+ if not in_window:+ total = None+ break+ total += max(in_window)[0]+ if total is None:+ continue++ # The entry sits at the set that produced the day's point+ row_datetime = max(days[day][1] for days in per_exercise if day in days)+ rows.append(+ DesiredRow(+ external_id=uuid.uuid5(category.pk, day.isoformat()),+ date=row_datetime,+ value=total,+ )+ )+ return rowsdiff --git a/wger/measurements/migrations/0008_dynamic_type.py b/wger/measurements/migrations/0008_dynamic_type.pyindex 51098146c..27f697262 100644--- a/wger/measurements/migrations/0008_dynamic_type.py+++ b/wger/measurements/migrations/0008_dynamic_type.py@@ -27,6 +27,7 @@ class Migration(migrations.Migration):('BMI', 'BMI'),('WHTR', 'Waist-to-height ratio'),('ONE_REP_MAX', '1RM'),+ ('ONE_RM_TOTAL', '1RM total'),],db_index=True,default='NONE',diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.pyindex 30abbd888..4dd39e815 100644--- a/wger/measurements/models/category.py+++ b/wger/measurements/models/category.py@@ -252,6 +252,7 @@ class Category(models.Model):BMI = 'BMI', 'BMI'WHTR = 'WHTR', 'Waist-to-height ratio'ONE_REP_MAX = 'ONE_REP_MAX', '1RM'+ ONE_RM_TOTAL = 'ONE_RM_TOTAL', '1RM total'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 6e2cf5809..81fda75a2 100644--- a/wger/measurements/tests/test_dynamic.py+++ b/wger/measurements/tests/test_dynamic.py@@ -75,6 +75,26 @@ class DynamicMeasurementTestCase(WgerTestCase):)return category+ 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 calculated_rows(self, category):return Measurement.objects.filter(category=category,@@ -522,26 +542,6 @@ class OneRepMaxTestCase(DynamicMeasurementTestCase):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(@@ -674,3 +674,144 @@ class OneRepMaxTestCase(DynamicMeasurementTestCase):content_type='application/json',)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class OneRmTotalTestCase(DynamicMeasurementTestCase):+ """+ The 1RM total sums the rolling-window maxima of several exercises+ """++ def enable_total(self, **params) -> Category:+ with self.captureOnCommitCallbacks(execute=True):+ category = Category.objects.create(+ user=self.user,+ name='Total',+ unit='kg',+ dynamic_type=Category.DynamicType.ONE_RM_TOTAL,+ dynamic_params={'exercise_ids': [1, 2], **params},+ )+ return category++ def test_sums_the_window_maxima(self):+ """+ A training day sums the best in-window estimate of every exercise+ """+ self.make_log('100', 5, exercise_id=1)+ self.make_log('80', 3, exercise_id=2)++ category = self.enable_total()+ rows = self.calculated_rows(category)++ # 112.51 + 84.71+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('197.22'))++ def test_window_max_beats_todays_set(self):+ """+ The best set of the window counts, not the most recent one+ """+ self.make_log('110', 5, days_ago=10, exercise_id=1)+ self.make_log('100', 5, exercise_id=1)+ self.make_log('80', 3, exercise_id=2)++ category = self.enable_total()+ rows = self.calculated_rows(category)++ # Today: brzycki(110, 5) + brzycki(80, 3) = 123.76 + 84.71. The day+ # ten days back has no second exercise in its window, so no entry.+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('208.47'))++ def test_no_entry_without_full_coverage(self):+ """+ A day where one exercise has nothing in its window gets no entry+ """+ self.make_log('100', 5, exercise_id=1)+ self.make_log('80', 3, days_ago=40, exercise_id=2)++ category = self.enable_total()++ self.assertEqual(self.calculated_rows(category).count(), 0)++ def test_window_days_param(self):+ """+ A wider window keeps older sets in the total+ """+ self.make_log('100', 5, exercise_id=1)+ self.make_log('80', 3, days_ago=40, exercise_id=2)++ category = self.enable_total(window_days=60)+ rows = self.calculated_rows(category)++ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('197.22'))++ def test_every_training_day_gets_a_point(self):+ """+ Each day one of the exercises was trained carries the total of its+ own window+ """+ self.make_log('80', 3, days_ago=10, exercise_id=2)+ self.make_log('100', 5, days_ago=5, exercise_id=1)+ self.make_log('110', 5, exercise_id=1)++ category = self.enable_total()+ rows = self.calculated_rows(category)++ # Day -10 has no exercise 1 in its window yet: no entry. Day -5 and+ # today pair their own squat best with the day -10 deadlift.+ self.assertEqual(rows.count(), 2)+ self.assertEqual(rows[0].value, Decimal('197.22'))+ self.assertEqual(rows[1].value, Decimal('208.47'))++ def test_api_refuses_single_exercise(self):+ """+ A total needs at least two exercises+ """+ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'Total',+ 'unit': 'kg',+ 'dynamic_type': 'ONE_RM_TOTAL',+ 'dynamic_params': {'exercise_ids': [1]},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_api_refuses_duplicate_exercises(self):+ """+ The same exercise cannot enter the total twice+ """+ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'Total',+ 'unit': 'kg',+ 'dynamic_type': 'ONE_RM_TOTAL',+ 'dynamic_params': {'exercise_ids': [1, 1]},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_api_refuses_unknown_exercises(self):+ """+ Every exercise of the list has to exist+ """+ self.user_login('test')+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'Total',+ 'unit': 'kg',+ 'dynamic_type': 'ONE_RM_TOTAL',+ 'dynamic_params': {'exercise_ids': [1, 999999]},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn('dynamic_params', response.data)