1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
|
package ride
import (
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
"time"
"github.com/jftuga/geodist"
"github.com/martinlehoux/kagamigo/kcore"
"github.com/tkrajina/gpxgo/gpx"
)
const garminTrackPointExtensionNamespace = "http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
type Ride struct {
distances []float64
elevations []float64
coords []geodist.Coord
timestamps []time.Time
heartRates []float64
cadences []float64
powers []float64
}
func (r *Ride) check() {
kcore.Assert(r.Len() > 0, "no points in ride")
kcore.Assert(len(r.distances) == len(r.elevations), "ride columns have different lengths")
kcore.Assert(len(r.distances) == len(r.coords), "ride columns have different lengths")
kcore.Assert(len(r.distances) == len(r.timestamps), "ride columns have different lengths")
for _, column := range [][]float64{r.heartRates, r.cadences, r.powers} {
if len(column) > 0 {
kcore.Assert(len(r.distances) == len(column), "ride columns have different lengths")
}
}
}
func (r Ride) Len() int {
return len(r.distances)
}
func (r Ride) DistanceM(i int) float64 { return r.distances[i] }
func (r Ride) ElevationM(i int) float64 { return r.elevations[i] }
func (r Ride) Coord(i int) geodist.Coord { return r.coords[i] }
func (r Ride) Timestamp(i int) time.Time { return r.timestamps[i] }
func (r Ride) HeartRateBpm(i int) (float64, bool) {
return optionalMetric(r.heartRates, i)
}
func (r Ride) CadenceRpm(i int) (float64, bool) {
return optionalMetric(r.cadences, i)
}
func (r Ride) PowerW(i int) (float64, bool) {
return optionalMetric(r.powers, i)
}
func optionalMetric(column []float64, i int) (float64, bool) {
if len(column) == 0 {
return 0, false
}
return column[i], true
}
type RideParser interface {
Parse(reader io.Reader) (Ride, error)
}
func ParseFile(parser RideParser, filename string) (Ride, error) {
f, err := os.Open(filename)
if err != nil {
return Ride{}, err
}
defer f.Close()
return parser.Parse(f)
}
type GPXRideParser struct{}
func (p GPXRideParser) Parse(reader io.Reader) (Ride, error) {
content, err := gpx.Parse(reader)
if err != nil {
return Ride{}, err
}
if len(content.Tracks) == 0 || len(content.Tracks[0].Segments) == 0 {
return Ride{}, errors.New("ride has no track segment")
}
segment := content.Tracks[0].Segments[0]
if len(segment.Points) == 0 {
return Ride{}, errors.New("ride has no track points")
}
distances := make([]float64, 0, len(segment.Points))
elevations := make([]float64, 0, len(segment.Points))
coords := make([]geodist.Coord, 0, len(segment.Points))
timestamps := make([]time.Time, 0, len(segment.Points))
heartRates := make([]float64, 0, len(segment.Points))
cadences := make([]float64, 0, len(segment.Points))
powers := make([]float64, 0, len(segment.Points))
heartRateComplete := true
cadenceComplete := true
powerComplete := true
distance := 0.0
previous := segment.Points[0]
if previous.Elevation.Null() {
return Ride{}, errors.New("points without elevation")
}
distances = append(distances, 0)
elevations = append(elevations, previous.Elevation.Value())
coords = append(coords, geodist.Coord{Lat: previous.Latitude, Lon: previous.Longitude})
timestamps = append(timestamps, previous.Timestamp)
sample, err := metricSampleForPoint(previous)
if err != nil {
return Ride{}, err
}
appendMetric(&heartRates, &heartRateComplete, sample.heartRate)
appendMetric(&cadences, &cadenceComplete, sample.cadence)
appendMetric(&powers, &powerComplete, sample.power)
for i := 1; i < len(segment.Points); i++ {
p := segment.Points[i]
distance += p.Distance2D(&previous)
previous = p
if distance == 0 {
continue
}
if p.Elevation.Null() {
return Ride{}, errors.New("points without elevation")
}
distances = append(distances, distance)
elevations = append(elevations, p.Elevation.Value())
coords = append(coords, geodist.Coord{Lat: p.Latitude, Lon: p.Longitude})
timestamps = append(timestamps, p.Timestamp)
sample, err = metricSampleForPoint(p)
if err != nil {
return Ride{}, err
}
appendMetric(&heartRates, &heartRateComplete, sample.heartRate)
appendMetric(&cadences, &cadenceComplete, sample.cadence)
appendMetric(&powers, &powerComplete, sample.power)
}
if len(distances) < 2 {
return Ride{}, errors.New("zero distance")
}
var heartRatesColumn, cadencesColumn, powersColumn []float64
if heartRateComplete {
heartRatesColumn = heartRates
}
if cadenceComplete {
cadencesColumn = cadences
}
if powerComplete {
powersColumn = powers
}
return fromColumns(distances, elevations, coords, timestamps, heartRatesColumn, cadencesColumn, powersColumn), nil
}
func FromColumns(distances []float64, elevations []float64, coords []geodist.Coord, timestamps []time.Time) Ride {
return fromColumns(distances, elevations, coords, timestamps, nil, nil, nil)
}
func fromColumns(distances []float64, elevations []float64, coords []geodist.Coord, timestamps []time.Time, heartRates, cadences, powers []float64) Ride {
ride := Ride{
distances: distances,
elevations: elevations,
coords: coords,
timestamps: timestamps,
heartRates: heartRates,
cadences: cadences,
powers: powers,
}
ride.check()
return ride
}
type metricSample struct {
heartRate *float64
cadence *float64
power *float64
}
func metricSampleForPoint(point gpx.GPXPoint) (metricSample, error) {
heartRate, err := metricValue(point, "hr")
if err != nil {
return metricSample{}, err
}
cadence, err := metricValue(point, "cad")
if err != nil {
return metricSample{}, err
}
power, err := metricValue(point, "watts")
if err != nil {
return metricSample{}, err
}
return metricSample{heartRate: heartRate, cadence: cadence, power: power}, nil
}
func appendMetric(column *[]float64, complete *bool, value *float64) {
if value == nil {
*complete = false
*column = append(*column, 0)
return
}
*column = append(*column, *value)
}
func metricValue(point gpx.GPXPoint, name string) (*float64, error) {
trackPointExtension, found := point.Extensions.GetNode(gpx.NamespaceURL(garminTrackPointExtensionNamespace), "TrackPointExtension")
if !found {
return nil, nil
}
node, found := trackPointExtension.GetNode(name)
if !found {
return nil, nil
}
value, err := strconv.ParseFloat(strings.TrimSpace(node.Data), 64)
if err != nil {
return nil, fmt.Errorf("invalid Garmin %s value %q: %w", name, node.Data, err)
}
return &value, nil
}
const CotacolAlgorithmVersion = "v1"
func Cotacol(ride Ride) float64 {
return difficultyScore(ride, 0, ride.Len()-1)
}
func difficultyScore(r Ride, startIndex, endIndex int) float64 {
if endIndex-startIndex < 1 {
return 0
}
startDistance := r.DistanceM(startIndex)
lastDistance := r.DistanceM(endIndex)
if lastDistance <= startDistance {
return 0
}
cotacol := 0.0
i := startIndex
for start := startDistance; start < lastDistance; start += 100 {
end := math.Min(start+100, lastDistance)
for i < endIndex && r.DistanceM(i+1) <= start {
i++
}
startElevation := interpolateElevation(r, i, start)
for i < endIndex && r.DistanceM(i+1) < end {
i++
}
endElevation := interpolateElevation(r, i, end)
slope := (endElevation - startElevation) / (end - start)
if slope > 0 {
cotacol += (end - start) / 1000 * (slope * 100) * (slope * 100)
}
}
return cotacol
}
func interpolateElevation(r Ride, i int, distance float64) float64 {
if i+1 >= r.Len() {
return r.ElevationM(i)
}
startDistance := r.DistanceM(i)
endDistance := r.DistanceM(i + 1)
t := (distance - startDistance) / (endDistance - startDistance)
return r.ElevationM(i) + t*(r.ElevationM(i+1)-r.ElevationM(i))
}
func (r *Ride) ClimbFromDist(startDist, endDist float64) Climb {
start, end := 0, 0
for i, distance := range r.distances {
if start == 0 && distance >= startDist {
start = i
}
if end == 0 && distance >= endDist {
end = i
break
}
}
return Climb{ride: *r, rideStart: start, rideEnd: end}
}
func (r *Ride) ClimbFromIndexes(startIndex, endIndex int) Climb {
kcore.Assert(startIndex >= 0 && endIndex < r.Len() && startIndex < endIndex, "invalid climb indexes")
return Climb{ride: *r, rideStart: startIndex, rideEnd: endIndex}
}
|