-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbp_tracker.py
More file actions
executable file
·320 lines (274 loc) · 8.61 KB
/
bp_tracker.py
File metadata and controls
executable file
·320 lines (274 loc) · 8.61 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
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
#!/usr/bin/env python3
# name: bp_tracker.py
# version: 0.0.1
# date: 20220509
# authors: Leam Hall, Alex Kleider
# desc: Track and report on blood pressure numbers.
# Notes:
# Datafile expects three ints and one float, in order.
# TODO
# Add statistical analysis for standard deviation.
# Report based on time of day (early, midmorning, afternoon, evening)
# (?) Add current distance from goal?
# Add more tests.
import argparse
from datetime import datetime
from operator import attrgetter
import os
import sys
data_file = "data/bp_numbers.txt"
systolic_labels = (
(0, 0, "dead"),
(1, 49, "low: medication required"),
(50, 69, "low: at risk"),
(70, 85, "low"),
(86, 120, "good"),
(121, 129, "elevated"),
(130, 139, "high: stage 1"),
(140, 179, "high: stage 2"),
(180, 300, "high: crisis"),
)
diastolic_labels = (
(0, 0, "dead"),
(1, 45, "low: medication required"),
(46, 55, "low: at risk"),
(56, 65, "low"),
(66, 79, "good"),
(80, 89, "high: stage 1"),
(90, 119, "high: stage 2"),
(120, 300, "high: crisis"),
)
class Result:
def __init__(self, line=""):
line_data = line.strip().split()
self.systolic = int(line_data[0])
self.diastolic = int(line_data[1])
self.pulse = int(line_data[2])
if len(line_data) == 3:
self.timestamp = datetime.now().strftime("%Y%m%d.%H%M")
else:
self.timestamp = line_data[3]
def before_date(self, date):
""" Returns bool if day given is <= timestamp date. """
day = int(self.timestamp.split(".")[0])
return day <= date
def after_date(self, date):
""" Returns bool if day given is >= timestamp date. """
day = int(self.timestamp.split(".")[0])
return day >= date
def in_date_range(self, begin, end):
""" Returns bool if day given is within date range. """
return self.after_date(begin) and self.before_date(end)
def add(args):
"""Append arguments to datafile"""
if check_file(args.file, "w"):
timestamp = datetime.now().strftime("%Y%m%d.%H%M")
this_report = args.add
this_report.append(timestamp)
with open(args.file, "a") as file:
file.write("{} {} {} {}\n".format(*this_report))
else:
print("Unable to write to", args.file)
sys.exit(1)
def results_from_file(report_file):
"""
Input is the report file: four (string) values per line.
Output is [int, int, int, str], systolic, diastolic, pulse, time stamp.
[1] Each of the 4 strings represents a number: first three are integers,
last (the fourth) is a YYYYmmdd.hhmm string representation of a timestamp
"""
res = []
with open(report_file, "r") as f:
for line in useful_lines(f):
res.append(Result(line))
return res
def average(lst):
"""Takes a list of numerics and returns an integer average"""
return sum(lst) // len(lst)
def check_file(file, mode):
"""
Mode (must be 'r' or 'w') specifies if we need to
r)ead or w)rite to the file.
"""
if mode == "r" and os.access(file, os.R_OK):
return True
if mode == "w":
if os.access(file, os.W_OK):
return True
if not os.path.exists(file) and os.access(
os.path.dirname(file), os.W_OK
):
return True
return False
def format_report(systolics, diastolics):
"""
Takes the numeric lists of systolics, diastolics, and pulses, and
return a string for printing.
"""
systolic = get_last(systolics)
sys_low, sys_upper, sys_label = get_labels(systolic, systolic_labels)
diastolic = get_last(diastolics)
dia_low, dia_upper, dia_label = get_labels(diastolic, diastolic_labels)
result = "Systolic {} ({} [{}-{}])\n".format(
systolic,
sys_label,
sys_low,
sys_upper,
)
result += "Diastolic {} ({} [{}-{}])\n".format(
diastolic,
dia_label,
dia_low,
dia_upper,
)
sys_avg = average(systolics)
sys_avg_low, sys_avg_upper, sys_avg_label = get_labels(
sys_avg, systolic_labels
)
result += "Systolic Average {} ({} [{}-{}])\n".format(
sys_avg,
sys_avg_label,
sys_avg_low,
sys_avg_upper,
)
dia_avg = average(diastolics)
dia_avg_low, dia_avg_upper, dia_avg_label = get_labels(
dia_avg, diastolic_labels
)
result += "Diastolic Average {} ({} [{}-{}])\n".format(
dia_avg,
dia_avg_label,
dia_avg_low,
dia_avg_upper,
)
return result
def get_args():
"""Gets args"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--file",
help="Report FILE (default bp_numbers.txt)",
default=data_file,
)
parser.add_argument(
"-a",
"--add",
nargs=3,
help="Add in the order of systolic, diastolic, pulse",
)
# parser.add_argument(
# "-t",
# "--times",
# nargs=2,
# type=int,
# help="Only consider readings within TIMES span",
# )
parser.add_argument(
"-r",
"--range",
nargs="+",
type=int,
help="""Begin and end dates are in YYYYMMDD format.
Default today for end. For example:
20230809 20230824
or
20230809""",
)
# parser.add_argument(
# "-n",
# "--number",
# nargs=1,
# type=int,
# help="Only consider the last NUMBER valid readings",
# )
return parser.parse_args()
def get_data(filename):
"""Returns data from args.file if present, else None."""
try:
data = results_from_file(filename)
except FileNotFoundError:
print("Unable to find {}, exiting.".format(filename))
return None
return data
def get_label(num, scale):
"""
Takes a number and a tuple of (min, max, lable) tuples,
returns the label for the range the number falls into.
"""
for group in scale:
lower, upper, label = group
if num in range(lower, upper + 1):
# The 'upper + 1' is required because range doesn't include upper
return label
return None
def get_labels(num, scale):
"""
Takes a number and a tuple of (min, max, lable) tuples,
returns the min, max, and label for the range the number falls into.
"""
for group in scale:
lower, upper, label = group
if num in range(lower, upper + 1):
# The 'upper + 1' is required because range doesn't include upper
return lower, upper, label
return None
def get_last(val):
"""Returns last element of a list."""
return val[-1]
def list_of_attr(data, attr):
"""Takes a list of results and returns a list of the specific attribute"""
result = []
for element in data:
result.append(getattr(element, attr))
return result
def sort_by_attr(data, _attr):
"""Sorts lists of lists by specified index in sub-lists."""
get_on_attr = attrgetter(_attr)
return sorted(data, key=get_on_attr)
def time_of_day_filter(datum, begin, end):
""" Returns True if time given is within the filter range. """
time = datum[3].split(".")[-1]
if time >= begin and time <= end:
return True
return False
def useful_lines(stream, comment="#"):
"""
Blank lines and leading and/or trailing white space are ignored.
If <comment> resolves to true, lines beginning with <comment>
(after being stripped of leading spaces) are also ignored.
<comment> can be set to <None> if don't want this functionality.
Other lines are returned ("yield"ed) stripped of leading and
trailing white space.
"""
for line in stream:
line = line.strip()
if comment and line.startswith(comment):
continue
if line:
yield line
if __name__ == "__main__":
args = get_args()
data = get_data(args.file)
if not data:
sys.exit(1, "Cannot find {}".format(args.file))
if args.add:
add(args)
results = get_data(args.file)
elif args.range:
begin = args.range[0]
if len(args.range) > 1:
end = args.range[1]
else:
end = int(datetime.now().strftime("%Y%m%d"))
if begin > end:
print("The begin date is greater than the end date")
sys.exit(1)
results = [
result for result in data if result.in_date_range(begin, end)
]
else:
results = data
sys_list = list_of_attr(results, "systolic")
dia_list = list_of_attr(results, "diastolic")
print(format_report(sys_list, dia_list))