calcpace 1.18.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -128,15 +128,20 @@ module RacePredictor
128
128
  # @param from_race [Numeric, String, Symbol] known distance in kilometers or race name
129
129
  # @param from_time [String, Numeric] time achieved at known distance
130
130
  # @param to_race [Numeric, String, Symbol] target distance in kilometers or race name
131
- # @param options [Hash] environmental options:
131
+ # @param options [Hash] environmental options, forwarded to
132
+ # EnvironmentalAdjuster#calculate_penalty:
132
133
  # - :temperature [Numeric]
133
134
  # - :temperature_unit [Symbol, String] :c or :f
134
135
  # - :altitude [Numeric]
136
+ # - :humidity [Numeric] relative humidity, 0–100 % (optional)
137
+ # - :dew_point [Numeric] dew point in temperature_unit (optional, instead of :humidity)
135
138
  # @return [Hash] hash with adjusted prediction and penalty details
136
139
  #
137
140
  # @example Predict marathon time from 5K adjusted for heat (25C)
138
141
  # predict_time_adjusted('5k', '00:20:00', 'marathon', temperature: 25)
139
- # #=> { adjusted_time: 13140.19, penalty_percent: 14.17, ... }
142
+ # #=> { adjusted_time: 12483.01, penalty_percent: 8.46, ... }
143
+ # calc.predict_time_adjusted('5k', '00:20:00', 'marathon', temperature: 25)[:penalty_percent] #=> 8.46
144
+ # calc.predict_time_adjusted('5k', '00:20:00', '10k', temperature: 25, humidity: 80)[:penalty_percent] #=> 4.87
140
145
  def predict_time_adjusted(from_race, from_time, to_race, **)
141
146
  predicted_seconds = predict_time(from_race, from_time, to_race)
142
147
  adjust_time(predicted_seconds, **)
@@ -22,7 +22,7 @@ module RaceSplits
22
22
  #
23
23
  # @example Negative splits (second half faster)
24
24
  # race_splits('10k', target_time: '00:40:00', split_distance: '5k', strategy: :negative)
25
- # #=> ["00:20:48", "00:40:00"] (first 5k slower, second 5k faster)
25
+ # #=> ["00:20:12", "00:40:00"] (first 5k 1% slower, second 5k 1% faster)
26
26
  def race_splits(race, target_time:, split_distance:, strategy: :even)
27
27
  total_distance = race_distance(race)
28
28
  target_seconds = target_time.is_a?(String) ? convert_to_seconds(target_time) : target_time
@@ -133,25 +133,27 @@ module RaceSplits
133
133
  end
134
134
 
135
135
  # Calculates negative splits (second half faster than first half)
136
- # First half is ~4% slower, second half is ~4% faster
136
+ # First half is run at a pace 1% slower than average, second half 1% faster
137
+ # (e.g. a 3:00:00 marathon goes through halfway in 1:30:54, then 1:29:06)
137
138
  #
138
139
  # @param total_distance [Float] total race distance in kilometers
139
140
  # @param target_seconds [Float] target finish time in seconds
140
141
  # @param split_km [Float] split distance in kilometers
141
142
  # @return [Array<String>] array of cumulative split times
142
143
  def calculate_negative_splits(total_distance, target_seconds, split_km)
143
- calculate_variable_splits(total_distance, target_seconds, split_km, first_factor: 1.04, second_factor: 0.96)
144
+ calculate_variable_splits(total_distance, target_seconds, split_km, first_factor: 1.01, second_factor: 0.99)
144
145
  end
145
146
 
146
147
  # Calculates positive splits (first half faster than second half)
147
- # First half is ~4% faster, second half is ~4% slower
148
+ # First half is run at a pace 1% faster than average, second half 1% slower
149
+ # (e.g. a 3:00:00 marathon goes through halfway in 1:29:06, then 1:30:54)
148
150
  #
149
151
  # @param total_distance [Float] total race distance in kilometers
150
152
  # @param target_seconds [Float] target finish time in seconds
151
153
  # @param split_km [Float] split distance in kilometers
152
154
  # @return [Array<String>] array of cumulative split times
153
155
  def calculate_positive_splits(total_distance, target_seconds, split_km)
154
- calculate_variable_splits(total_distance, target_seconds, split_km, first_factor: 0.96, second_factor: 1.04)
156
+ calculate_variable_splits(total_distance, target_seconds, split_km, first_factor: 0.99, second_factor: 1.01)
155
157
  end
156
158
 
157
159
  # Shared logic for variable pace split strategies
@@ -27,6 +27,19 @@ module TrackCalculator
27
27
  # Mean radius of the Earth in kilometers (IAU standard)
28
28
  EARTH_RADIUS_KM = 6371.0
29
29
 
30
+ # Shortest horizontal distance a grade is measured over in
31
+ # #track_grade_adjusted_splits. GPS elevation is noisy — a few metres between
32
+ # consecutive fixes even from a barometric altimeter — so a grade read
33
+ # between points 1 m apart can be ±300% on flat ground, and the grade factor's
34
+ # curvature turns that symmetric noise into a fake climb. Over 100 m, ±1–2 m
35
+ # of noise is ±1–2% of grade, while a hill longer than a track straight still
36
+ # shows up.
37
+ GRADE_SEGMENT_MIN_KM = 0.1
38
+
39
+ # Slack on GRADE_SEGMENT_MIN_KM so ten 10 m steps, which sum to a hair under
40
+ # 0.1 km in floating point, still close a 100 m grade segment (1 mm)
41
+ GRADE_SEGMENT_TOLERANCE_KM = 1e-6
42
+
30
43
  # Computes the great-circle distance between two GPS coordinates using
31
44
  # the Haversine formula.
32
45
  #
@@ -156,6 +169,49 @@ module TrackCalculator
156
169
  collect_splits(points, split_km, compact: compact)
157
170
  end
158
171
 
172
+ # Pace splits with a grade-adjusted pace (GAP) for each split.
173
+ #
174
+ # Each split is the hash #track_splits returns — same :km, :elapsed and :pace,
175
+ # split boundaries computed the same way — plus :gap, the flat-ground pace of
176
+ # equal effort for that split (Minetti et al., 2002; see GradeAdjustedPace).
177
+ # #track_splits itself is unchanged.
178
+ #
179
+ # How :gap is computed:
180
+ # - The track is cut into grade segments of at least GRADE_SEGMENT_MIN_KM
181
+ # (100 m) of horizontal distance, and each gets one grade: its net
182
+ # elevation change over its length. A leftover shorter than that at the end
183
+ # of a stretch is merged into the segment before it. Grades are clamped to
184
+ # ±45%, the range the model was measured on.
185
+ # - A stretch between points without :ele (or with a NaN/infinite one) is
186
+ # flat (factor 1.0), and a missing :ele ends the grade segment in progress.
187
+ # A stretch with elevation shorter than one grade segment and with no full
188
+ # segment before it to join — or a whole track that short — is flat too.
189
+ # - Distances are the horizontal (Haversine) ones; the factor is applied to
190
+ # them as is, without the √(1 + grade²) slope correction (0.5% at 10%).
191
+ # - Each split's distance is weighted by the grade factor of the segments it
192
+ # covers, and :gap is the split's time over that flat-equivalent distance.
193
+ # A split on flat ground, or with no elevation data, has :gap equal to :pace.
194
+ #
195
+ # @param points [Array<Hash>] points with :lat, :lon and :time keys, and
196
+ # optionally :ele (metres), as for #track_splits
197
+ # @param split_km [Numeric] split interval in kilometers (default: 1.0)
198
+ # @param compact [Boolean] when true, :pace and :gap use the compact display format
199
+ # @return [Array<Hash>] split hashes with :km, :elapsed, :pace and :gap
200
+ # (:gap formatted like :pace)
201
+ # @raise [ArgumentError] if split_km is not positive
202
+ # @raise [ArgumentError] if any point is missing a :time key
203
+ #
204
+ # @example a steady 5% climb at 5:00/km
205
+ # calc.track_grade_adjusted_splits(points, 1.0)
206
+ # #=> [{ km: 1.0, elapsed: 300, pace: "05:00", gap: "03:51" }, ...]
207
+ def track_grade_adjusted_splits(points, split_km = 1.0, compact: false)
208
+ raise ArgumentError, 'split_km must be positive' unless split_km.is_a?(Numeric) && split_km.positive?
209
+ return [] if points.nil? || points.size < 2
210
+
211
+ validate_points_have_time(points)
212
+ collect_splits(points, split_km, compact: compact, grade_factors: segment_grade_factors(points))
213
+ end
214
+
159
215
  private
160
216
 
161
217
  def haversine_km(lat1, lon1, lat2, lon2)
@@ -253,41 +309,56 @@ module TrackCalculator
253
309
  format('%<min>02d:%<sec>02d', min: pace_seconds / 60, sec: pace_seconds % 60)
254
310
  end
255
311
 
256
- def collect_splits(points, split_km, compact:)
312
+ # grade_factors, when given, holds one grade factor per segment (see
313
+ # #segment_grade_factors) and turns on the :gap field; without it the splits
314
+ # are exactly the ones #track_splits has always returned.
315
+ def collect_splits(points, split_km, compact:, grade_factors: nil)
257
316
  state = { splits: [], start_time: point_time(points.first),
258
317
  split_start_time: point_time(points.first),
259
- accumulated_km: 0.0, split_number: 1, compact: compact }
318
+ accumulated_km: 0.0, split_number: 1, compact: compact,
319
+ grade_factors: grade_factors, flat_equivalent_km: 0.0 }
260
320
 
261
- points.each_cons(2) { |a, b| process_segment(a, b, split_km, state) }
321
+ if grade_factors
322
+ points.each_cons(2).with_index { |(a, b), index| process_segment(a, b, split_km, state, index) }
323
+ else
324
+ points.each_cons(2) { |a, b| process_segment(a, b, split_km, state) }
325
+ end
262
326
  append_partial_split(points.last, split_km, state)
263
327
  state[:splits]
264
328
  end
265
329
 
266
- def process_segment(point_a, point_b, split_km, state)
267
- segment_km = haversine_distance(dig_key(point_a, :lat), dig_key(point_a, :lon),
268
- dig_key(point_b, :lat), dig_key(point_b, :lon))
330
+ # index is only given, and the segment only tracked, when computing :gap —
331
+ # track_splits keeps its original per-segment cost
332
+ def process_segment(point_a, point_b, split_km, state, index = nil)
333
+ segment_km = segment_distance_km(point_a, point_b)
269
334
  state[:accumulated_km] += segment_km
335
+ state[:segment] = { assigned_km: 0.0, factor: state[:grade_factors].fetch(index) } if index
270
336
 
271
337
  while state[:accumulated_km] >= split_km * state[:split_number]
272
338
  record_split(point_a, point_b, segment_km, split_km, state)
273
339
  end
340
+
341
+ accumulate_flat_equivalent(state, segment_km)
274
342
  end
275
343
 
276
344
  def record_split(point_a, point_b, segment_km, split_km, state)
277
345
  offset = (split_km * state[:split_number]) - (state[:accumulated_km] - segment_km)
346
+ accumulate_flat_equivalent(state, offset)
278
347
  boundary_time = interpolate_time(point_a, point_b, segment_km, offset)
279
348
  state[:splits] << build_split_entry(boundary_time, split_km, state)
280
349
  state[:split_start_time] = boundary_time
281
350
  state[:split_number] += 1
351
+ state[:flat_equivalent_km] = 0.0
282
352
  end
283
353
 
284
354
  def build_split_entry(boundary_time, split_km, state)
285
355
  split_elapsed = (boundary_time - state[:split_start_time]).round
286
- {
356
+ entry = {
287
357
  km: (split_km * state[:split_number]).round(2),
288
358
  elapsed: (boundary_time - state[:start_time]).round,
289
359
  pace: seconds_to_pace(split_elapsed, split_km, compact: state[:compact])
290
360
  }
361
+ with_gap(entry, split_elapsed, state)
291
362
  end
292
363
 
293
364
  def append_partial_split(last_point, split_km, state)
@@ -295,11 +366,113 @@ module TrackCalculator
295
366
  return unless remaining_km > 0.001
296
367
 
297
368
  last_time = point_time(last_point)
298
- state[:splits] << {
369
+ split_elapsed = (last_time - state[:split_start_time]).round
370
+ entry = {
299
371
  km: state[:accumulated_km].round(2),
300
372
  elapsed: (last_time - state[:start_time]).round,
301
- pace: seconds_to_pace((last_time - state[:split_start_time]).round, remaining_km,
302
- compact: state[:compact])
373
+ pace: seconds_to_pace(split_elapsed, remaining_km, compact: state[:compact])
303
374
  }
375
+ state[:splits] << with_gap(entry, split_elapsed, state)
376
+ end
377
+
378
+ def segment_distance_km(point_a, point_b)
379
+ haversine_distance(dig_key(point_a, :lat), dig_key(point_a, :lon),
380
+ dig_key(point_b, :lat), dig_key(point_b, :lon))
381
+ end
382
+
383
+ # Adds the flat-equivalent distance of the current segment up to
384
+ # distance_into_segment, for the part not yet credited to an earlier split
385
+ def accumulate_flat_equivalent(state, distance_into_segment)
386
+ return unless state[:grade_factors]
387
+
388
+ segment = state[:segment]
389
+
390
+ state[:flat_equivalent_km] += (distance_into_segment - segment[:assigned_km]) * segment[:factor]
391
+ segment[:assigned_km] = distance_into_segment
392
+ end
393
+
394
+ def with_gap(entry, split_elapsed, state)
395
+ return entry unless state[:grade_factors]
396
+
397
+ entry.merge(gap: seconds_to_pace(split_elapsed, state[:flat_equivalent_km], compact: state[:compact]))
398
+ end
399
+
400
+ # One grade factor per segment (consecutive point pair). Segments are grouped
401
+ # into grade segments of at least GRADE_SEGMENT_MIN_KM, each with one grade
402
+ # (net elevation change over horizontal distance); see
403
+ # #track_grade_adjusted_splits for the rules.
404
+ def segment_grade_factors(points)
405
+ factors = Array.new(points.size - 1, 1.0)
406
+ window = new_grade_window
407
+
408
+ points.each_cons(2).with_index do |(a, b), index|
409
+ window = extend_grade_window(window, factors, a, b, index)
410
+ end
411
+ close_grade_window(window, factors, final: true)
412
+ factors
413
+ end
414
+
415
+ def new_grade_window(previous = nil)
416
+ { indexes: [], km: 0.0, start_ele: nil, end_ele: nil, previous: previous }
417
+ end
418
+
419
+ def extend_grade_window(window, factors, point_a, point_b, index)
420
+ ele_a = finite_ele(point_a)
421
+ ele_b = finite_ele(point_b)
422
+ if ele_a.nil? || ele_b.nil?
423
+ close_grade_window(window, factors, final: true)
424
+ return new_grade_window
425
+ end
426
+
427
+ add_to_grade_window(window, index, segment_distance_km(point_a, point_b), ele_a, ele_b)
428
+ return window unless full_grade_window?(window)
429
+
430
+ close_grade_window(window, factors, final: false)
431
+ new_grade_window(window.except(:previous))
432
+ end
433
+
434
+ # Grade segments treat a NaN or infinite elevation like a missing one
435
+ def finite_ele(point)
436
+ ele = fetch_ele(point)
437
+ ele if ele&.finite?
438
+ end
439
+
440
+ def add_to_grade_window(window, index, segment_km, ele_a, ele_b)
441
+ window[:start_ele] ||= ele_a
442
+ window[:end_ele] = ele_b
443
+ window[:indexes] << index
444
+ window[:km] += segment_km
445
+ end
446
+
447
+ # A full window gets its own grade. A short leftover — the end of the track
448
+ # or of a stretch with elevation — is merged into the full window before it;
449
+ # with no full window before it (a stretch shorter than a grade segment
450
+ # between missing elevations, or a whole track that short) it stays flat
451
+ # rather than being graded over a few noisy metres.
452
+ def close_grade_window(window, factors, final:)
453
+ return if window[:indexes].empty?
454
+
455
+ unless full_grade_window?(window)
456
+ return unless final && window[:previous]
457
+
458
+ window = merge_grade_windows(window[:previous], window)
459
+ end
460
+ factor = grade_adjustment_factor(window_grade(window))
461
+ window[:indexes].each { |index| factors[index] = factor }
462
+ end
463
+
464
+ def full_grade_window?(window)
465
+ window[:km] >= GRADE_SEGMENT_MIN_KM - GRADE_SEGMENT_TOLERANCE_KM
466
+ end
467
+
468
+ def merge_grade_windows(previous, window)
469
+ { indexes: previous[:indexes] + window[:indexes], km: previous[:km] + window[:km],
470
+ start_ele: previous[:start_ele], end_ele: window[:end_ele] }
471
+ end
472
+
473
+ def window_grade(window)
474
+ return 0.0 unless window[:km].positive?
475
+
476
+ (window[:end_ele] - window[:start_ele]) / (window[:km] * 1000.0)
304
477
  end
305
478
  end
@@ -9,8 +9,15 @@
9
9
  #
10
10
  # Heart rate zones use the Karvonen method (Heart Rate Reserve):
11
11
  # target = hr_rest + pct * (hr_max - hr_rest)
12
+ #
13
+ # Not standalone: it is a part of Calcpace and calls into its siblings —
14
+ # Vo2maxEstimator (estimate_vo2max, vo2_at_velocity), FitnessPredictor
15
+ # (predict_time_from_vo2max, for the marathon band), PaceCalculator
16
+ # (race_distance), Converter and Checker.
12
17
  module TrainingZones
13
- # Training intensities as fraction of VO2max (Daniels' Running Formula)
18
+ # Training intensities as fraction of VO2max (Daniels' Running Formula).
19
+ # The marathon :high (0.84) is the nominal upper bound only: the band's fast
20
+ # end is the predicted race pace (see PREDICTED_RACE_PACE_ZONES).
14
21
  TRAINING_INTENSITIES = {
15
22
  easy: { low: 0.59, high: 0.74 },
16
23
  marathon: { low: 0.75, high: 0.84 },
@@ -19,6 +26,14 @@ module TrainingZones
19
26
  repetition: { low: 1.05, high: 1.10 }
20
27
  }.freeze
21
28
 
29
+ # Zones whose fast end is the VDOT-predicted race pace instead of
30
+ # TRAINING_INTENSITIES[zone][:high]. Daniels' M pace is the runner's
31
+ # predicted marathon race pace (FitnessPredictor#predict_time_from_vo2max),
32
+ # which is 0.800–0.849 of VO2max across VO2max 10–100 (0.805 at 30, 0.830
33
+ # at 70). That keeps the marathon band slower than the threshold band
34
+ # (from 0.83) below VO2max ~69.5.
35
+ PREDICTED_RACE_PACE_ZONES = %i[marathon].freeze
36
+
22
37
  # A pace band for one training zone (paces per kilometre or mile).
23
38
  # slow = lower-intensity end of the band, fast = higher-intensity end.
24
39
  PaceBand = Struct.new(:slow_seconds, :fast_seconds, :slow_clock, :fast_clock)
@@ -46,27 +61,27 @@ module TrainingZones
46
61
  # @param vo2max [Numeric] VO2max in ml/kg/min (must be > 0)
47
62
  # @param unit [Symbol] pace unit — :km (default) or :mi
48
63
  # @return [Hash{Symbol => PaceBand}] keys: :easy, :marathon, :threshold,
49
- # :interval, :repetition — paces per chosen unit
64
+ # :interval, :repetition — paces per chosen unit. The marathon band runs
65
+ # from 75% of VO2max to the VDOT-predicted marathon pace; the prediction
66
+ # covers VO2max 10–100, and outside that range the race-pace intensity of
67
+ # the nearest bound is used
50
68
  # @raise [Calcpace::NonPositiveInputError] if vo2max is not positive
51
69
  # @raise [Calcpace::UnsupportedUnitError] if unit is not :km or :mi
52
70
  #
53
71
  # @example
54
72
  # calc.training_paces(50.0)[:threshold].fast_clock #=> "00:04:15"
55
73
  # calc.training_paces(50.0, unit: :mi)[:threshold].fast_clock #=> "00:06:51"
74
+ # calc.training_paces(50.0)[:marathon].fast_clock #=> "00:04:31"
56
75
  def training_paces(vo2max, unit: :km)
57
76
  check_positive(vo2max.to_f, 'VO2max')
58
77
  meters = pace_unit_meters(unit)
59
78
 
60
- TRAINING_INTENSITIES.transform_values do |band|
79
+ TRAINING_INTENSITIES.to_h do |zone, band|
61
80
  slow = pace_seconds_at_pct(vo2max.to_f, band[:low], meters)
62
- fast = pace_seconds_at_pct(vo2max.to_f, band[:high], meters)
63
-
64
- PaceBand.new(
65
- slow_seconds: slow,
66
- fast_seconds: fast,
67
- slow_clock: convert_to_clocktime(slow),
68
- fast_clock: convert_to_clocktime(fast)
69
- )
81
+ fast = pace_seconds_at_pct(vo2max.to_f, fast_intensity(zone, band, vo2max.to_f), meters)
82
+
83
+ [zone, PaceBand.new(slow_seconds: slow, fast_seconds: fast,
84
+ slow_clock: convert_to_clocktime(slow), fast_clock: convert_to_clocktime(fast))]
70
85
  end
71
86
  end
72
87
 
@@ -336,6 +351,22 @@ module TrainingZones
336
351
  "Resting heart rate (#{hr_rest}) must be lower than maximum heart rate (#{hr_max})"
337
352
  end
338
353
 
354
+ def fast_intensity(zone, band, vo2max)
355
+ PREDICTED_RACE_PACE_ZONES.include?(zone) ? marathon_race_intensity(vo2max) : band[:high]
356
+ end
357
+
358
+ # Fraction of VO2max a runner holds at the VDOT-predicted marathon pace.
359
+ # The prediction only covers FitnessPredictor::SUPPORTED_VO2MAX_RANGE, so
360
+ # beyond it the fraction of the nearest bound is used (it barely moves
361
+ # there: 0.800 at VO2max 10, 0.849 at 100).
362
+ def marathon_race_intensity(vo2max)
363
+ range = FitnessPredictor::SUPPORTED_VO2MAX_RANGE
364
+ vo2 = vo2max.clamp(range.min, range.max)
365
+ seconds = predict_time_from_vo2max(vo2, 'marathon')
366
+
367
+ vo2_at_velocity(race_distance('marathon') * Converter::Distance::KM_TO_METERS * 60.0 / seconds) / vo2
368
+ end
369
+
339
370
  # Inverts Daniels & Gilbert: velocity (m/min) that demands a given VO2
340
371
  def velocity_at_vo2(vo2)
341
372
  a = 0.000104
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Calcpace
4
- VERSION = '1.18.1'
4
+ VERSION = '2.1.0'
5
5
  end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ # How hard the runner says an effort was, for Vo2maxEstimator#estimate_detailed_vo2max
4
+ #
5
+ # Daniels & Gilbert assume an all-out effort, and the estimator can only guess
6
+ # that from duration and heart rate. A declared effort answers it directly. It
7
+ # never changes the VO2max value — only its confidence, sub_maximal and basis.
8
+ module Vo2maxEffort
9
+ # From easiest. :easy and :moderate are training (talk test: a full
10
+ # conversation / short sentences), :hard is a few words at a time, :max is
11
+ # everything the runner had — a race or a test.
12
+ EFFORT_LEVELS = %i[easy moderate hard max].freeze
13
+
14
+ private
15
+
16
+ def normalize_effort(effort)
17
+ return if effort.nil?
18
+
19
+ level = effort.to_s.downcase.to_sym
20
+ return level if EFFORT_LEVELS.include?(level)
21
+
22
+ raise Calcpace::InvalidEffortError,
23
+ "Invalid effort: #{effort.inspect}. Valid efforts: #{EFFORT_LEVELS.map(&:inspect).join(', ')}"
24
+ end
25
+
26
+ # A declared easy or moderate effort wins over everything: the runner knows
27
+ # they held back, whatever the watch says. Heart rate wins over a declared
28
+ # max, as it did over the duration rule. A max shorter than five minutes stays
29
+ # with the duration rule: there the formula itself is unreliable.
30
+ #
31
+ # duration_confidence is the estimator's verdict from duration alone.
32
+ def effort_verdict(effort, time_min, duration_confidence:, hr_sub_maximal:)
33
+ if %i[easy moderate].include?(effort)
34
+ { confidence: :low, sub_maximal: true, basis: :declared }
35
+ elsif hr_sub_maximal
36
+ { confidence: :low, sub_maximal: true, basis: :heart_rate }
37
+ elsif effort == :max && time_min >= 5
38
+ { confidence: :high, sub_maximal: false, basis: :declared }
39
+ else
40
+ { confidence: duration_confidence, sub_maximal: false, basis: :duration }
41
+ end
42
+ end
43
+ end
@@ -14,6 +14,8 @@
14
14
  # Accuracy: ±3–5 ml/kg/min vs laboratory testing. Best results with efforts
15
15
  # between 5 and 60 minutes at race pace (i.e. near-maximal effort).
16
16
  module Vo2maxEstimator
17
+ include Vo2maxEffort
18
+
17
19
  # Classification thresholds based on:
18
20
  # Daniels, J. (2014). Daniels' Running Formula (3rd ed.). Human Kinetics.
19
21
  # General ranges are consistent with ACSM guidelines and widely cited in
@@ -28,7 +30,11 @@ module Vo2maxEstimator
28
30
  ].freeze
29
31
 
30
32
  # Represents a contextualized VO2max estimation result
31
- Vo2maxResult = Struct.new(:value, :confidence, :sub_maximal, :adjusted_distance_km)
33
+ #
34
+ # basis names what set confidence and sub_maximal: :declared (the effort
35
+ # given), :heart_rate (average HR under 85 % of max) or :duration (the
36
+ # Daniels & Gilbert window alone)
37
+ Vo2maxResult = Struct.new(:value, :confidence, :sub_maximal, :adjusted_distance_km, :basis)
32
38
 
33
39
  # Estimates VO2max from a race performance using Daniels & Gilbert formula
34
40
  #
@@ -59,8 +65,19 @@ module Vo2maxEstimator
59
65
  (vo2 / pct_vo2max).round(1)
60
66
  end
61
67
 
68
+ # The public signature: every input is a keyword a caller already passes, and
69
+ # bundling them into an options object would break the 2.x API.
70
+ # rubocop:disable Metrics/ParameterLists
71
+
62
72
  # Estimates a detailed and contextualized VO2max
63
73
  #
74
+ # Elevation is folded in with a flat heuristic — every 100 m of gain adds
75
+ # 600 m of equivalent flat distance — that ignores where the climbing is and
76
+ # gives nothing back for descents. It is kept as is so results stay
77
+ # comparable across versions. For a profile-aware view of a GPS track, see
78
+ # GradeAdjustedPace#grade_adjusted_pace and
79
+ # TrackCalculator#track_grade_adjusted_splits (Minetti et al., 2002).
80
+ #
64
81
  # @param distance [Numeric] race distance, in kilometres by default or in
65
82
  # the unit given by distance_unit
66
83
  # @param time [String, Integer] finish time
@@ -68,11 +85,25 @@ module Vo2maxEstimator
68
85
  # @param hr_avg [Numeric] average heart rate during the effort
69
86
  # @param hr_max [Numeric] athlete's maximum heart rate
70
87
  # @param distance_unit [Symbol] unit of the distance input — :km (default) or :mi
88
+ # @param effort [Symbol, String, nil] how hard the runner says it was, one of
89
+ # Vo2maxEffort::EFFORT_LEVELS. It never changes the value, only how far it can be
90
+ # trusted: :easy and :moderate make it sub-maximal and low confidence
91
+ # whatever the duration or heart rate; :max makes it high confidence from
92
+ # five minutes on, however long it took, unless heart rate says
93
+ # sub-maximal; :hard and nil leave the duration and heart-rate rules as
94
+ # they are.
71
95
  # @return [Vo2maxResult] structured result with value and metadata
72
96
  # (adjusted_distance_km is always in kilometres)
73
97
  # @raise [Calcpace::NonPositiveInputError] if distance or time are not positive
74
98
  # @raise [Calcpace::UnsupportedUnitError] if distance_unit is not :km or :mi
75
- def estimate_detailed_vo2max(distance, time, elevation_gain_m: 0, hr_avg: nil, hr_max: nil, distance_unit: :km)
99
+ # @raise [Calcpace::InvalidEffortError] if effort is not one of Vo2maxEffort::EFFORT_LEVELS
100
+ #
101
+ # @example a marathon run all-out
102
+ # calc.estimate_detailed_vo2max(42.195, '03:30:00').confidence #=> :low
103
+ # calc.estimate_detailed_vo2max(42.195, '03:30:00', effort: :max).confidence #=> :high
104
+ def estimate_detailed_vo2max(distance, time, elevation_gain_m: 0, hr_avg: nil, hr_max: nil, distance_unit: :km,
105
+ effort: nil)
106
+ effort = normalize_effort(effort)
76
107
  distance_km = normalize_distance_km(distance, distance_unit)
77
108
  # Validated before the elevation adjustment, which would otherwise turn a
78
109
  # negative distance into a positive equivalent-flat one
@@ -80,31 +111,45 @@ module Vo2maxEstimator
80
111
 
81
112
  adj_dist_km = adjusted_distance_for_vo2(distance_km, elevation_gain_m)
82
113
  vo2max_val = estimate_vo2max(adj_dist_km, time)
83
- confidence = calculate_time_confidence(parse_time_minutes(time))
84
-
85
- hr_data = validate_and_analyze_hr(hr_avg, hr_max)
86
- confidence = :low if hr_data[:sub_maximal]
114
+ time_min = parse_time_minutes(time)
115
+ hr_data = validate_and_analyze_hr(hr_avg, hr_max)
116
+ verdict = effort_verdict(effort, time_min, duration_confidence: calculate_time_confidence(time_min),
117
+ hr_sub_maximal: hr_data[:sub_maximal])
87
118
 
88
- Vo2maxResult.new(
89
- value: vo2max_val,
90
- confidence: confidence,
91
- sub_maximal: hr_data[:sub_maximal],
92
- adjusted_distance_km: adj_dist_km.round(2)
93
- )
119
+ Vo2maxResult.new(value: vo2max_val, adjusted_distance_km: adj_dist_km.round(2), **verdict)
94
120
  end
121
+ # rubocop:enable Metrics/ParameterLists
95
122
 
96
123
  # Returns a descriptive label for a given VO2max value
97
124
  #
125
+ # Without age and sex, the label comes from fixed thresholds that are the same
126
+ # for everyone (see VO2MAX_LABELS) — exactly as it always has. With both, it
127
+ # comes from where the value sits among people of the same sex and age
128
+ # decade, measured on a treadmill in the FRIEND registry (see
129
+ # Vo2maxNorms#vo2max_percentile and Vo2maxNorms::VO2MAX_PERCENTILE_LABELS):
130
+ # the same 45 ml/kg/min is "Fair" for a 25-year-old man and "Elite" for a
131
+ # 60-year-old woman.
132
+ #
98
133
  # @param value [Numeric] VO2max in ml/kg/min
134
+ # @param age [Integer, nil] age in years (18 or over, a fractional age is
135
+ # truncated); give it with sex
136
+ # @param sex [String, Symbol, nil] male or female; give it with age
99
137
  # @return [String] label: "Beginner", "Fair", "Good", "Very Good", "Excellent", or "Elite"
100
- # @raise [ArgumentError] if value is not positive
138
+ # @raise [Calcpace::NonPositiveInputError] if value is not positive
139
+ # @raise [ArgumentError] if only one of age and sex is given, or either is invalid
101
140
  #
102
141
  # @example
103
- # calc.vo2max_label(51.9) #=> "Very Good"
104
- def vo2max_label(value)
142
+ # calc.vo2max_label(51.9) #=> "Very Good"
143
+ # calc.vo2max_label(45) #=> "Good"
144
+ # calc.vo2max_label(45, age: 25, sex: :male) #=> "Fair"
145
+ # calc.vo2max_label(45, age: 60, sex: :female) #=> "Elite"
146
+ def vo2max_label(value, age: nil, sex: nil)
105
147
  check_positive(value.to_f, 'VO2max value')
148
+ return VO2MAX_LABELS.find { |entry| value.to_f >= entry[:min] }[:label] if age.nil? && sex.nil?
149
+ raise ArgumentError, 'Age and sex must be provided together' if age.nil? || sex.nil?
106
150
 
107
- VO2MAX_LABELS.find { |entry| value.to_f >= entry[:min] }[:label]
151
+ percentile = raw_vo2max_percentile(value.to_f, age, sex)
152
+ Vo2maxNorms::VO2MAX_PERCENTILE_LABELS.find { |entry| percentile >= entry[:min] }[:label]
108
153
  end
109
154
 
110
155
  private