generated from simonw/python-lib-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.qmd
488 lines (444 loc) · 11.5 KB
/
index.qmd
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# Apple Health Exploration with ClickHouse (chDB), Altair and Quarto
### Install libs
```{python}
!pip install chdb
!pip install altair
!pip install polars
!pip install pyarrow
```
### Parquet path
```{python}
apple_health_parquet = "ah.parquet"
```
### Imports
```{python}
import altair as alt
import pyarrow as pa
import chdb
from chdb.session import Session
```
### Create Database
```{python}
db = Session()
db.query("CREATE DATABASE db")
db.query("USE db")
```
### Drop Table (if exists)
```{python}
db.query("drop table if exists db.ah")
```
### Create Table from Parquet
```{python}
create_table = f"""
CREATE TABLE ah
ENGINE = MergeTree
ORDER BY tuple() AS
SELECT *
FROM file('{apple_health_parquet}', Parquet)
"""
db.query(create_table)
```
### Describe Table
```{python}
q = "desc table ah"
r = db.query(q, "PrettyCompactNoEscapes")
print(r)
```
### Types
```{python}
r = db.query("select distinct(type) from ah")
print(r)
```
### Distance (Walking and Running)
```{python}
q = """
from ah
select sum(toFloat64(value)) as val,
toString(date(end)) as cdate
where type == 'DistanceWalkingRunning'
group by cdate
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="distance over time")
.mark_point()
.encode(
alt.X("cdate:T").axis(format="%Y", labelAngle=-45).title("days"),
alt.Y("val").axis(format=".2s").title("distance"),
tooltip=["cdate:T", "val"],
)
)
c = c + c.transform_regression("cdate", "val", method="poly").mark_line(color="black")
c.configure_mark(color="coral").properties(width=500).interactive()
```
### VO2 Max
```{python}
q = """
from ah
select toFloat64(value) as vo2max,
toString(date(end)) as cdate
where type == 'VO2Max'
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="V̇O2 max over time")
.mark_point()
.encode(
alt.X("cdate:T").axis(format="%Y %b", labelAngle=-45).title("days"),
alt.Y("vo2max").axis(format=".2s").title("vo2max").scale(zero=False),
tooltip=["cdate:T", "vo2max"],
)
)
c = c + c.transform_regression("cdate", "vo2max", method="poly").mark_line(
color="black"
)
c.configure_mark(color="purple").properties(width=500).interactive()
```
### Body Mass
```{python}
q = """
from ah
select sum(toFloat64(value)) as weight,
toString(date(end)) as cdate
where type == 'BodyMass'
group by cdate
having weight < 80
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="weight over time")
.mark_line(point=True) # increased point size
.encode(
alt.X("cdate:T").axis(format="%Y %b", labelAngle=-45).title("days"),
alt.Y("weight").axis(format=".2s").title("weight (kg)").scale(zero=False),
tooltip=["cdate:T", "weight"],
)
)
c.configure_mark(color="black").properties(width=500).configure_point(
size=80
).interactive()
```
### Cycling
```{python}
q = """
from ah
select sum(toFloat64(value)) as distance,
toString(toStartOfDay(end)) as cdate
where type == 'DistanceCycling'
and created is not null
group by cdate
order by cdate
"""
s = db.query(q, "dataframe")
alt.Chart(s, title="cycling distance over time").mark_point().encode(
alt.X("cdate:T").axis(format="%Y %b", labelAngle=-45).title("days"),
alt.Y("distance").axis(format=".2s").title("distance"),
tooltip=["cdate:T", "distance"],
).configure_mark(color="coral").properties(width=500).interactive()
```
### Wrist Temperature during Sleep
```{python}
q = """
from ah
select toFloat64(value) as temp,
end as cdate
where type == 'AppleSleepingWristTemperature'
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="wrist temperature over time")
.mark_point()
.encode(
alt.X("yearmonthdate(cdate):T")
.axis(format="%Y %b", labelAngle=-45)
.title("days"),
alt.Y(
"temp",
)
.axis(format=".4s")
.title("temperature")
.scale(zero=False),
tooltip=["cdate:T", "temp"],
)
)
c = c + c.transform_regression("cdate", "temp", method="poly").mark_line(color="black")
c.configure_mark(color="green").properties(width=500).interactive()
```
### Sleep Duration and State
```{python}
import polars as pl
q = """
from ah
select toString(value) as val,
start,
end
where type == 'SleepAnalysis'
and toYearWeek(end) = toYearWeek(now())-5
order by end desc
"""
s = chdb.to_df(db.query(q, "Arrow"))
df = pl.from_pandas(s)
# duration is end - start
df = df.with_columns(
pl.col("end").sub(pl.col("start")).dt.total_seconds().alias("duration")
)
# add date column based on truncated end
df = df.with_columns(pl.col("end").dt.date().alias("date"))
# order by start desc
df = df.sort("start", descending=True)
category_names = {
"HKCategoryValueSleepAnalysisAwake": "Awake",
"HKCategoryValueSleepAnalysisAsleepCore": "Light Sleep",
"HKCategoryValueSleepAnalysisAsleepDeep": "Deep Sleep",
"HKCategoryValueSleepAnalysisAsleepREM": "REM Sleep",
}
category_colors = {
"HKCategoryValueSleepAnalysisAwake": "#FFA500", # Orange
"HKCategoryValueSleepAnalysisAsleepCore": "#AEC7E8", # Light Blue
"HKCategoryValueSleepAnalysisAsleepDeep": "#4169E1", # Dark Blue
"HKCategoryValueSleepAnalysisAsleepREM": "#00008B", # Navy Blue
}
c = (
alt.Chart(df.to_pandas(), title="sleep duration over time")
.mark_bar(size=16)
.encode(
alt.X("date:T").axis(format="%Y %b %d", labelAngle=-45).title("days"),
alt.Y(
"duration:Q",
)
.axis(format=".2s")
.title("duration (s)")
.scale(domain=[0, 35000]),
color=alt.Color(
"val:N",
scale=alt.Scale(
domain=list(category_colors.keys()),
range=list(category_colors.values()),
),
legend=alt.Legend(
title="Sleep State",
labelExpr="{'HKCategoryValueSleepAnalysisAwake': 'Awake', 'HKCategoryValueSleepAnalysisAsleepCore': 'Light Sleep', 'HKCategoryValueSleepAnalysisAsleepDeep': 'Deep Sleep', 'HKCategoryValueSleepAnalysisAsleepREM': 'REM Sleep'}[datum.label]",
values=list(category_names.keys()),
symbolFillColor="black",
symbolSize=200,
),
),
order=alt.Order("val", sort="ascending"),
tooltip=[
"date:T",
alt.Tooltip("val:N", title="Sleep State"),
alt.Tooltip("duration:Q", title="Duration"),
],
)
)
c
```
## Environmental Audio Exposure
```{python}
q = """
from ah
select toString(toStartOfDay(end)) as cdate,
toFloat64(value) as audio
where type == 'EnvironmentalAudioExposure'
and toYear(end) = 2024
order by cdate
limit 5000
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
(
alt.Chart(s, title="🚜 Environmental Audio Exposure")
.mark_point(color="orange")
.encode(
alt.X(
"cdate:T",
axis=alt.Axis(format="%Y %b", labelAngle=-45),
title="days",
),
alt.Y("audio:Q").axis(title="Audio Exposure (dB)"),
tooltip=[
alt.Tooltip("cdate:T", title="date"),
alt.Tooltip("audio:Q", title="audio exposure (dB)"),
],
)
)
.properties(width=500)
.interactive()
)
c = c + alt.Chart().mark_rule(color="red", size=2).encode(y=alt.datum(75))
c
```
## Calories Burned
```{python}
q = """
from ah
select type,
sum(toFloat64(value)) as calories,
toString(date(end)) as cdate
where type in ('ActiveEnergyBurned', 'BasalEnergyBurned')
and toYear(end) = 2021
and toMonth(end) in (10)
group by cdate, type
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="🔥 Calories Burned")
.mark_bar(size=8)
.encode(
alt.X("cdate:T").axis(format="%Y %b %d", labelAngle=-45).title("days"),
alt.Y("calories:Q").axis(format=".2s").title("kcal"),
color=alt.condition(
alt.datum.type == "ActiveEnergyBurned", alt.value("red"), alt.value("blue")
),
order=alt.Order("type", sort="descending"),
tooltip=["cdate:T", "calories"],
)
)
c = c.properties(width=500).interactive()
c
```
## Caffeine
```{python}
q = """
from ah
select toString(toStartOfDay(end)) as cdate,
sum(toFloat64(value)) as caffeine
where type == 'DietaryCaffeine'
and toYear(end) = 2023 and toMonth(end) in (1, 2)
group by cdate
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
(
alt.Chart(s, title="☕️ Caffeine")
.mark_bar()
.encode(
alt.X("cdate:T").axis(format="%Y %b %d", labelAngle=-45).title("days"),
alt.Y("caffeine:Q").axis(title="caffeine (mg)"),
tooltip=[
alt.Tooltip("cdate:T", title="date"),
alt.Tooltip("caffeine:Q", title="caffeine (mg)"),
],
color=alt.value("black"),
)
)
.properties(width=500)
.interactive()
)
c
```
### Caffeine Heatmap
```{python}
q = """
from ah
select toString(toStartOfDay(end)) as cdate,
sum(toFloat64(value)) as caffeine
where type == 'DietaryCaffeine'
and toYear(end) = 2023
and toMonth(end) in (1, 2)
group by cdate
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="☕️ Coffee Heatmap (2023 Jan-Feb)")
.mark_rect()
.encode(
alt.X("date(cdate):O").axis(format="%d", labelAngle=-45).title("days"),
alt.Y("month(cdate):O").title("month"),
color=alt.Color("max(caffeine):Q", scale=alt.Scale(scheme="greys")).title(
"Caffeine (mg)"
),
tooltip=[alt.Tooltip("date(cdate):T", title="date")],
)
.properties(width=500) # added padding for whitespace
.interactive()
)
c
```
### Caffeine after 17:00
```{python}
q = """
from ah
select toString(toStartOfDay(end)) as cdate,
sum(toFloat64(value)) as caffeine,
toHour(max(end)) > 17 as late
where type == 'DietaryCaffeine'
and toYear(end) = 2023
and toMonth(end) in (1, 2)
group by cdate
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="☕️ Coffee after 17:00 (2023 Jan-Feb)")
.mark_rect()
.encode(
alt.X("date(cdate):O").axis(format="%d", labelAngle=-45).title("days"),
alt.Y("month(cdate):O").title("month"),
color=alt.Color(
"late:N", scale=alt.Scale(domain=[0, 1], range=["lightgrey", "red"])
).title("Late?"),
tooltip=[alt.Tooltip("date(cdate):T", title="date")],
)
.properties(width=500)
.interactive()
)
c
```
### Step Count Heatmap
```{python}
q = """
from ah
select toString(toStartOfDay(end)) as cdate,
sum(toFloat64(value)) as steps
where type == 'StepCount' and toYear(end) = 2023
group by cdate
order by cdate
"""
s = chdb.to_df(db.query(q, "Arrow"))
c = (
alt.Chart(s, title="👣 Step Count (2023)")
.mark_rect()
.encode(
alt.X("date(cdate):O").axis(format="%d", labelAngle=-45).title("days"),
alt.Y("month(cdate):O").title("month"),
color=alt.Color("sum(steps):Q", scale=alt.Scale(scheme="greens")).title(
"Steps"
),
tooltip=[alt.Tooltip("date(cdate):T", title="date")],
)
.properties(width=500)
.interactive()
)
c
```
### Last Swimming Workout
```{python}
q = """
from ah
select max(start)
where type = 'DistanceSwimming';
"""
s = db.query(q, "PrettyCompactNoEscapes")
print(s)
```
### Swimming Workouts
```{python}
q = """
from ah
select toString(toStartOfWeek(end)) as week,
count(type) > 0 as had_swimming_workout
where type = 'DistanceSwimming'
group by week
order by week
"""
s = db.query(q, "PrettyCompactNoEscapes")
print(s)
```