-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutil.py
More file actions
233 lines (167 loc) · 6.63 KB
/
util.py
File metadata and controls
233 lines (167 loc) · 6.63 KB
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
__author__ = "Cameron Summers"
import datetime as dt
import re
import logging
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import os
THIS_DIR = os.path.dirname(__file__)
PHI_DATA_DIR = os.path.join("./PHI/")
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
logger = get_logger(__name__)
class TidepoolAPIDateParsingException(Exception):
pass
DATESTAMP_FORMAT = "%Y-%m-%d"
API_DATA_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
def parse_tidepool_api_date_str(date_str):
"""
Parse date strings in formats common to Tidepool API
Args:
date_str (str): date string
Returns:
dt.DateTime
"""
common_timestamp_formats = [
API_DATA_TIMESTAMP_FORMAT,
"%Y-%m-%dT%H:%M:%SZ",
DATESTAMP_FORMAT
]
datetime_obj = None
# Some devices have 7 zeros instead of six, which datetime can't handle.
if len(date_str) == len('2021-03-24T14:05:29.0000000Z'):
date_str = re.sub("\d{7}Z", "000000Z", date_str)
elif len(date_str) == len('2021-03-24T14:05:29.00000000Z'):
date_str = re.sub("\d{8}Z", "000000Z", date_str)
elif len(date_str) == len('2021-03-24T14:05:29.000000000Z'):
date_str = re.sub("\d{9}Z", "000000Z", date_str)
try:
datetime_obj = dt.datetime.fromisoformat(date_str)
except ValueError:
for format in common_timestamp_formats:
try:
datetime_obj = dt.datetime.strptime(date_str, format)
except:
pass
if datetime_obj is None:
raise TidepoolAPIDateParsingException("String '{}' could not be parsed.".format(date_str))
# Notes have
if datetime_obj.tzinfo is not None:
offset = datetime_obj.utcoffset()
datetime_obj = datetime_obj + offset
datetime_obj = datetime_obj.replace(tzinfo=None)
return datetime_obj
def get_user_group_data_dir(user_group_name):
return os.path.join(PHI_DATA_DIR, "tidepool_user_groups", user_group_name)
def create_user_dir(user_id, start_date, end_date, user_group_name=""):
"""
Create
Args:
start_date dt.DateTime: start date of data for user_obj
end_date dt.DateTime: end date of data for user_obj
user_id (str): user_obj id for user_obj
Returns:
str: dir_path for saving data
"""
if not os.path.isdir(PHI_DATA_DIR):
raise Exception("You are not saving to PHI folder. Check your path.")
user_group_dir = get_user_group_data_dir(user_group_name)
user_dir_name = "{}_{}_{}".format(user_id, start_date.strftime(DATESTAMP_FORMAT), end_date.strftime(DATESTAMP_FORMAT))
user_dir_path = os.path.join(user_group_dir, user_dir_name)
if not os.path.isdir(user_dir_path):
os.makedirs(user_dir_path)
return user_dir_path
def get_recursively(search_dict, keyword):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided or field in .
ref: https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary
"""
fields_found = []
for key, value in search_dict.items():
if key == keyword:
fields_found.append(value)
if isinstance(search_dict[key], str) and keyword in search_dict[key]:
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, keyword)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, keyword)
for another_result in more_results:
fields_found.append(another_result)
return fields_found
def logger_describe_distribution(description, distribution):
distribution = np.array(distribution)
nan_mask = np.isnan(distribution)
num_before = len(distribution)
distribution = distribution[~nan_mask]
num_after = len(distribution)
logger.info("{} Before NanMask. {} After.".format(num_before, num_after))
logger.info("{}: mean={:.2f}. min={:.2f}. q1={:.2f}. median={:.2f}. q3={:.2f}. max={:.2f}".format(
description,
np.nanmean(distribution),
np.nanmin(distribution),
np.nanpercentile(distribution, 25),
np.nanmedian(distribution),
np.nanpercentile(distribution, 75),
np.nanmax(distribution),
))
def get_years_since_date(reference_date):
years_since = (dt.datetime.today() - reference_date).total_seconds() / 60 / 60 / 24 / 365
return years_since
def create_synthetic_dataset(num_days):
data = []
cir = 10
target = 100
br_total = 10
np.random.seed(1234)
for i in range(num_days):
carb_trend = 1.0 #+ 0.2*np.cos(2*np.pi * i / num_days)
total_carbs_true = np.random.normal(150, 30) * carb_trend
# carb_estimation_std = total_carbs_true * 0.01
carb_estimation_std = 20
total_carbs = np.random.normal(total_carbs_true, carb_estimation_std)
carb_diff = (total_carbs_true - total_carbs)
insulin_sensitivity = 1.0 #+ 0.2*np.sin(2*np.pi * i / num_days)
total_insulin = br_total + total_carbs_true / cir * insulin_sensitivity
tir = 1.0 - abs(carb_diff) / 100
day = {
"date": dt.datetime(2021, 1, 1, 0, 0, 0) + dt.timedelta(days=i),
"total_carbs_true": total_carbs_true,
"total_carbs": total_carbs,
"total_insulin": total_insulin,
"cgm_geo_mean": target * insulin_sensitivity,
"cgm_mean": target * insulin_sensitivity,
"cgm_percent_below_54": 0,
"cgm_percent_tir": tir,
"carb_diff": carb_diff
}
data.append(day)
df = pd.DataFrame(data)
window_size_days = 60
indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=window_size_days)
# df_agg = df.rolling(window=indexer, min_periods=1).mean()
# df_agg = df_agg.iloc[:-window_size_days]
# df_agg["date"] = df["date"].iloc[:-window_size_days]
# df = df_agg
g = sns.pairplot(df[["total_carbs_true", "total_carbs", "total_insulin", "cgm_percent_tir"]])
df.to_csv("synthetic_aggregated_dataset.csv")
plt.title('Fake Dataset')
plt.show()
return df
if __name__ == "__main__":
create_synthetic_dataset(60)