-
Notifications
You must be signed in to change notification settings - Fork 0
/
strava.py
303 lines (256 loc) · 9.3 KB
/
strava.py
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
292
293
294
295
296
297
298
299
300
301
302
303
# main strava script
from typing import Optional
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm, colors
from matplotlib.animation import FuncAnimation, PillowWriter
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from auth import refresh_strava
from database_test import read_data, write_data
from endpoints import (
get_activities,
get_altitude,
get_distance,
get_latlong,
get_time,
list_activities,
)
from loguru import logger
class NoActivityError(Exception):
"""Raised when the activity_id is not found in the database."""
pass
def calc_speed(time_dict: dict, dist_dict: dict) -> dict:
"""Calculate speed between time and distance points."""
speed = []
time_delta = []
dist_delta = []
for i in range(len(time_dict) - 1):
time_delta.append(time_dict[i + 1] - time_dict[i])
for i in range(len(dist_dict) - 1):
dist_delta.append(dist_dict[i + 1] - dist_dict[i])
for t, d in zip(time_delta, dist_delta):
speed.append((d / max(t, 1)) * 2.23694) # m/s to mph
speed.append(0) # to handle the length change from calculating the deltas
return speed
def latlng_to_feet(latlng: float) -> float:
"""Convert latitude or longitude to feet."""
return latlng * 364488
def feet_to_latlng(feet: float) -> float:
"""Convert feet to decimal latitude / longitude."""
return feet / 364488
def plotter(
data: tuple[list[float], list[float], list[float]], speed: list, id_number: str
) -> None:
"""Function for plotting data in 3D"""
logger.debug(f"Plotter starting for : {id_number}")
X, Y, Z = data
speed = speed
x_lim = min(X), max(X)
y_lim = min(Y), max(Y)
z_lim = min(Z), max(Z)
colormap_list = [ # noqa: F841
"winter",
"summer",
"spring",
"autumn",
"viridis",
"plasma",
"hot",
"gnuplot2",
"cool",
"bwr",
]
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection="3d")
scaled_max = np.average(speed) + 2 * np.std(speed) # max speed to be 2*std from average
norm = colors.Normalize(vmin=0, vmax=scaled_max)
ax.scatter(X, Y, Z, norm=norm, cmap="gnuplot2", c=speed, s=0.5)
ax.set_zlim3d(z_lim)
ax.set_box_aspect((1, 1, feet_to_latlng(1) * 100000))
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_zlabel("Altitude")
ax.set_xticks(list(x_lim))
ax.set_yticks(list(y_lim))
ax.ticklabel_format(useOffset=False)
# to hide lat, lon and altitude info, un-comment the line below
# plt.tick_params(left=False, right=False, labelleft = False, labelbottom = False, bottom = False)
fig.colorbar(
cm.ScalarMappable(norm=norm, cmap="gnuplot2"),
ax=ax,
label="Speed in MPH",
location="bottom",
shrink=0.5,
)
# plt.show()
ax.view_init(elev=90, azim=0)
plt.savefig(f"{id_number}.png", dpi=300)
ax.clear()
plt.clf()
plt.close()
logger.debug("Plotter finished")
def animator(
data: tuple[list[float], list[float], list[float]], speed: list, id_number: str
) -> None:
"""Animate a 3D plot based on the input data and save with the id_number."""
logger.debug(f"Animator starting for : {id_number}")
speed = speed
X, Y, Z = data
x_lim = min(X), max(X)
y_lim = min(Y), max(Y)
z_lim = min(Z), max(Z)
colormap_list = [ # noqa: F841
"winter",
"summer",
"spring",
"autumn",
"viridis",
"plasma",
"hot",
"gnuplot2",
"cool",
"bwr",
]
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection="3d")
scaled_max = np.average(speed) + 2 * np.std(speed) # max speed to be 2*std from average
norm = colors.Normalize(vmin=0, vmax=scaled_max)
ax.scatter(X, Y, Z, norm=norm, cmap="gnuplot2", c=speed, s=0.5)
ax.set_zlim3d(z_lim)
ax.set_box_aspect((1, 1, feet_to_latlng(1) * 100000))
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_zlabel("Altitude")
ax.set_xticks(list(x_lim))
ax.set_yticks(list(y_lim))
ax.ticklabel_format(useOffset=False)
# to hide lat, lon and altitude info, un-comment the line below
# plt.tick_params(left=False, right=False, labelleft = False, labelbottom = False, bottom = False)
fig.colorbar(
cm.ScalarMappable(norm=norm, cmap="gnuplot2"),
ax=ax,
label="Speed in MPH",
location="bottom",
shrink=0.5,
)
def init():
ax.plot(X, Y, Z)
return (fig,)
def animate(i):
ax.view_init(elev=30.0, azim=i)
return (fig,)
anim = FuncAnimation(
fig, animate, init_func=init, frames=360, interval=20, blit=True
)
save_name = f"strava_vis_{id_number}.gif"
anim.save(save_name, writer=PillowWriter(fps=30))
# anim.save(save_name, writer=FFMpegWriter(fps=30))
ax.clear()
plt.clf()
plt.close()
logger.debug("Animator finished")
def main() -> None:
"""Command line interaction for listing activity, then plotting in 3D."""
logger.debug("`main` starting")
list_activities()
activity = input("Enter target activity id: ")
try:
activity_data = read_data(activity)
if len(activity_data[activity]) == 0:
raise NoActivityError(f"No activity with id: {activity}")
else:
logger.debug("Activity exists in local database, reading data.")
dist_data = []
time_data = []
alt_data = []
lat_long_data = []
for i in range(len(activity_data[activity])):
dist_data.append(activity_data[activity][i][1])
time_data.append(activity_data[activity][i][2])
alt_data.append(activity_data[activity][i][3])
lat, lon = (
activity_data[activity][i][4].strip("[").strip("]").split(",")
)
lat_long_data.append([float(lat), float(lon)])
altitude = {"altitude": alt_data}
distance = {"distance": dist_data}
time = {"time": time_data}
lat_long = {"lat_long": lat_long_data}
speed = calc_speed(time_data, dist_data)
except NoActivityError:
altitude = {"altitude": get_altitude(activity)}
lat_long = {"lat_long": get_latlong(activity)}
distance = {"distance": get_distance(activity)}
time = {"time": get_time(activity)}
speed = calc_speed(time["time"], distance["distance"])
write_data(activity, distance, time, altitude, lat_long)
X = [x[1] for x in lat_long["lat_long"]]
Y = [y[0] for y in lat_long["lat_long"]]
Z = [z for z in altitude["altitude"]]
animator((X, Y, Z), speed, activity)
plotter((X, Y, Z), speed, activity)
logger.debug("`main` finished")
def testing(debug_option: Optional[bool] = False) -> None:
"""Test `main` with a static activity ID."""
logger.debug("Running test mode")
activity_id = "6492923259"
altitude = {"altitude": get_altitude(6492923259)}
lat_long = {"lat_long": get_latlong(6492923259)}
distance = {"distance": get_distance(6492923259)}
time = {"time": get_time(6492923259)}
speed_map = calc_speed(time["time"], distance["distance"])
X = [x[1] for x in lat_long["lat_long"]]
Y = [y[0] for y in lat_long["lat_long"]]
Z = [z for z in altitude["altitude"]]
if debug_option:
x_lim = min(X), max(X)
y_lim = min(Y), max(Y)
z_lim = min(Z), max(Z)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot(X, Y, Z)
ax.set_zlim3d(z_lim)
ax.set_box_aspect((1, 1, feet_to_latlng(1) * 100000))
ax.scatter(X, Y, Z, cmap="rainbow", c=speed_map)
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_zlabel("Altitude")
ax.set_xticks(list(x_lim))
ax.set_yticks(list(y_lim))
ax.ticklabel_format(useOffset=False)
plt.show()
x_lim = min(X), max(X)
y_lim = min(Y), max(Y)
z_lim = min(Z), max(Z)
print(f"{X[:11] = }")
print(f"{Y[:11] = }")
print(f"{Z[:11] = }")
print(f"{x_lim = }: {y_lim = }")
print(f"x_range= {max(X) - min(X)}, y_range= {max(Y) - min(Y)}")
print(f"{z_lim = }")
print(f"z_range= {max(Z) - min(Z)}")
print(f"{len(X) = }\n{len(Y) = }\n{len(Z) = }")
write_data(activity_id, distance, time, altitude, lat_long)
animator((X, Y, Z), "test", activity_id)
plotter((X, Y, Z), "test", activity_id)
logger.debug("`testing` finished")
def all_rides() -> None:
"""Plot all of the rides."""
logger.debug("`all_rides` starting")
all_activities = get_activities()
for i in range(len(all_activities)):
name = all_activities[i]["name"].replace(" ", "_")
logger.debug(f"Making vis for {name}")
activity = all_activities[i]["id"]
altitude = {"altitude": get_altitude(activity)}
lat_long = {"lat_long": get_latlong(activity)}
X = [x[1] for x in lat_long["lat_long"]]
Y = [y[0] for y in lat_long["lat_long"]]
Z = [z for z in altitude["altitude"]]
animator((X, Y, Z), name)
logger.debug("`all_rides` finished")
if __name__ == "__main__":
refresh_strava()
main()
# testing(debug_option=False)
# all_rides()