|
| 1 | +import os |
| 2 | +import logging |
| 3 | +from typing import Literal, TypeAlias |
| 4 | +from datetime import date, datetime, timedelta, timezone |
| 5 | + |
| 6 | +import pandas as pd |
| 7 | + |
1 | 8 | from aw_core import Event
|
2 |
| -from typing import Literal |
3 | 9 |
|
4 |
| -from .heartrate import load_heartrate_daily_df |
5 |
| -from .screentime import load_category_df |
| 10 | +from ..load.location import load_daily_df as load_location_daily_df |
| 11 | +from ..load.qslang import load_daily_df as load_drugs_df |
| 12 | + |
| 13 | +from .heartrate import load_heartrate_summary_df |
| 14 | +from .screentime import load_screentime_cached, load_category_df |
| 15 | +from .sleep import load_sleep_df |
| 16 | + |
| 17 | +Sources = Literal["screentime", "heartrate", "drugs", "location", "sleep"] |
6 | 18 |
|
7 |
| -Sources = Literal["activitywatch", "heartrate"] |
8 | 19 |
|
9 |
| -def load_all_df(events: list[Event], ignore: list[Sources] = []): |
10 |
| - df = load_category_df(events) |
| 20 | +def load_all_df( |
| 21 | + fast=True, screentime_events: list[Event] | None = None, ignore: list[Sources] = [] |
| 22 | +) -> pd.DataFrame: |
| 23 | + """ |
| 24 | + Loads a bunch of data into a single dataframe with one row per day. |
| 25 | + Serves as a useful starting point for further analysis. |
| 26 | + """ |
| 27 | + df = pd.DataFrame() |
| 28 | + since = datetime.now(tz=timezone.utc) - timedelta(days=30 if fast else 2 * 365) |
| 29 | + |
| 30 | + if "screentime" not in ignore: |
| 31 | + print("Adding screentime") |
| 32 | + if screentime_events is None: |
| 33 | + screentime_events = load_screentime_cached(fast=fast, since=since) |
| 34 | + df_time = load_category_df(screentime_events) |
| 35 | + df_time = df_time[["Work", "Media", "ActivityWatch"]] |
| 36 | + df = join(df, df_time.add_prefix("time:")) |
| 37 | + |
11 | 38 | if "heartrate" not in ignore:
|
12 |
| - df = df.join(load_heartrate_daily_df(events)) |
| 39 | + print("Adding heartrate") |
| 40 | + df_hr = load_heartrate_summary_df(freq="D") |
| 41 | + # translate daily datetime column to a date column |
| 42 | + df_hr.index = df_hr.index.date # type: ignore |
| 43 | + df = join(df, df_hr) |
| 44 | + |
| 45 | + if "drugs" not in ignore: |
| 46 | + print("Adding drugs") |
| 47 | + # keep only columns starting with "tag" |
| 48 | + df_drugs = load_drugs_df() |
| 49 | + df_drugs = df_drugs[df_drugs.columns[df_drugs.columns.str.startswith("tag")]] |
| 50 | + df = join(df, df_drugs) |
| 51 | + |
| 52 | + if "location" not in ignore: |
| 53 | + print("Adding location") |
| 54 | + # TODO: add boolean for if sleeping together |
| 55 | + df_location = load_location_daily_df() |
| 56 | + df_location.index = df_location.index.date # type: ignore |
| 57 | + df = join(df, df_location.add_prefix("loc:")) |
| 58 | + |
| 59 | + if "sleep" not in ignore: |
| 60 | + df_sleep = load_sleep_df() |
| 61 | + df = join(df, df_sleep.add_prefix("sleep:")) |
| 62 | + |
| 63 | + # look for all-na columns, emit a warning, and drop them |
| 64 | + na_cols = df.columns[df.isna().all()] |
| 65 | + if len(na_cols) > 0: |
| 66 | + print(f"Warning: dropping all-NA columns: {str(list(na_cols))}") |
| 67 | + df = df.drop(columns=na_cols) |
| 68 | + |
13 | 69 | return df
|
| 70 | + |
| 71 | + |
| 72 | +def join(df_target: pd.DataFrame, df_source: pd.DataFrame) -> pd.DataFrame: |
| 73 | + if not df_target.empty: |
| 74 | + check_new_data_in_range(df_source, df_target) |
| 75 | + print( |
| 76 | + f"Adding new columns: {str(list(df_source.columns.difference(df_target.columns)))}" |
| 77 | + ) |
| 78 | + return df_target.join(df_source) if not df_target.empty else df_source |
| 79 | + |
| 80 | + |
| 81 | +DateLike: TypeAlias = datetime | date | pd.Timestamp |
| 82 | + |
| 83 | + |
| 84 | +def datelike_to_date(d: DateLike) -> date: |
| 85 | + if isinstance(d, datetime) or isinstance(d, pd.Timestamp): |
| 86 | + return d.date() |
| 87 | + elif isinstance(d, date): |
| 88 | + return d |
| 89 | + else: |
| 90 | + raise ValueError(f"Invalid type for datelike: {type(d)}") |
| 91 | + |
| 92 | + |
| 93 | +def check_new_data_in_range(df_source: pd.DataFrame, df_target: pd.DataFrame) -> None: |
| 94 | + # check that source data covers target data, or emit warning |
| 95 | + source_start = datelike_to_date(df_source.index.min()) |
| 96 | + source_end = datelike_to_date(df_source.index.max()) |
| 97 | + target_start = datelike_to_date(df_target.index.min()) |
| 98 | + target_end = datelike_to_date(df_target.index.max()) |
| 99 | + |
| 100 | + # check the worst case |
| 101 | + if source_start > target_end or source_end < target_start: |
| 102 | + print( |
| 103 | + f"Warning: source data does not cover ANY of target data: ({source_start}/{source_end}) not in ({target_start}/{target_end})" |
| 104 | + ) |
| 105 | + elif source_start > target_start: |
| 106 | + print( |
| 107 | + f"Warning: source data starts after target data (partial): {source_start} > {target_start}" |
| 108 | + ) |
| 109 | + elif source_end < target_end: |
| 110 | + print( |
| 111 | + f"Warning: source data ends before target data (partial): {source_end} < {target_end}" |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +if __name__ == "__main__": |
| 116 | + logging.basicConfig(level=logging.INFO) |
| 117 | + |
| 118 | + # print a summary of all data |
| 119 | + df = load_all_df(fast=os.environ.get("FAST", "1") == "1") |
| 120 | + print(df) |
| 121 | + print(df.describe()) |
| 122 | + |
| 123 | + # check for missing data |
| 124 | + df_days_na = df.isna().sum() |
| 125 | + df_days_na = df_days_na[df_days_na > 0] |
| 126 | + if len(df_days_na) > 0: |
| 127 | + print(f"Missing data for {len(df_days_na)} out of {len(df.columns)} columns") |
| 128 | + print(df_days_na) |
| 129 | + print("Total days: ", len(df)) |
| 130 | + |
| 131 | + # keep days with full coverage |
| 132 | + df = df.dropna() |
| 133 | + print("Total days with full coverage: ", len(df)) |
| 134 | + |
| 135 | + print("Final dataframe:") |
| 136 | + print(df) |
0 commit comments