|
7 | 7 | import time |
8 | 8 | from lxml import objectify |
9 | 9 |
|
| 10 | +from .exceptions import NoHeartRateDataError |
| 11 | + |
10 | 12 | namespace = 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2' |
11 | 13 |
|
12 | 14 |
|
@@ -98,6 +100,44 @@ def hr_min(self): |
98 | 100 | """Minimum heart rate of the workout""" |
99 | 101 | return min(self.hr_values()) |
100 | 102 |
|
| 103 | + def hr_percent_in_zones(self, zones): |
| 104 | + """Percentage of workout spent in each heart rate zone. |
| 105 | +
|
| 106 | + Given these user's heart rate zones: |
| 107 | + zones = { |
| 108 | + "Z0": (0, 119), |
| 109 | + "Z1": (120, 199), |
| 110 | + "Z2": (200, 240), |
| 111 | + } |
| 112 | +
|
| 113 | + Then `self.hr_percent_in_zones(zones)` would return something like: |
| 114 | + { |
| 115 | + "Z0": 5, |
| 116 | + "Z1": 95, |
| 117 | + "Z2": 0, |
| 118 | + } |
| 119 | +
|
| 120 | + Correct calculation relies on evenly spaced measurement times. |
| 121 | + """ |
| 122 | + hr_values = self.hr_values() |
| 123 | + if not hr_values: |
| 124 | + raise NoHeartRateDataError |
| 125 | + |
| 126 | + # Initialize a dictionary with one item for each zone |
| 127 | + per_zone = dict.fromkeys(zones.keys(), 0) |
| 128 | + |
| 129 | + # count number of HR measurements per zone |
| 130 | + for hr in hr_values: |
| 131 | + for zone_name, zone_boundaries in zones.items(): |
| 132 | + if hr >= zone_boundaries[0] and hr <= zone_boundaries[1]: |
| 133 | + per_zone[zone_name] += 1 |
| 134 | + |
| 135 | + # convert counts to percentages |
| 136 | + nr_hr_values = len(hr_values) |
| 137 | + for name, count in per_zone.items(): |
| 138 | + per_zone[name] = round(100 * count / nr_hr_values) |
| 139 | + return per_zone |
| 140 | + |
101 | 141 | @property |
102 | 142 | def pace(self): |
103 | 143 | """Average pace (mm:ss/km for the workout""" |
|
0 commit comments