-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcgv.py
268 lines (223 loc) · 8.15 KB
/
cgv.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
"""
cgv.py
continuous glucose measurement
.. versionadded:: 0.1.0
visualize your glucose data measured by hand or
by a glucose measurement system (CGM)
"""
from pathlib import Path
import pandas as pd
import matplotlib as mpl
import subprocess
# Use the pgf backend (must be set before pyplot imported)
mpl.use("pgf")
mpl.rcParams.update(
{
"pgf.texsystem": "pdflatex",
"font.family": "serif",
"text.usetex": True,
"pgf.rcfonts": False,
}
)
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from datetime import timedelta, date
from dataclasses import dataclass
@dataclass
class Week:
"""
Representation of a week
.. versionadded:: 0.1.0
"""
first_day: date
week_number: int
@property
def last_day(self) -> date:
"""last day of the week"""
return self.first_day + timedelta(days=6)
def calender_week(self) -> int:
return self.first_day.isocalendar().week
def year(self) -> int:
return self.first_day.isocalendar().year
def inside_week(self, day: date) -> bool:
"""check if given ``day`` is inside week"""
if self.first_day <= day <= self.last_day:
return True
else:
return False
def time_span(self) -> str:
"""print the time-span of the week"""
return (
self.first_day.strftime(self.dateformat())
+ " - "
+ self.last_day.strftime(self.dateformat())
)
def dateformat(self) -> str:
return "%d.%m.%Y"
class CGV:
"""
Continous Glucose Visualization
.. versionadded:: 0.1.0
"""
def __init__(
self,
csv_path: str,
date_column: str = "Gerätezeitstempel",
glucose_column: str = "Glukosewert-Verlauf mmol/L",
):
self.csv_path = Path(csv_path)
self.data = pd.read_csv(self.csv_path, sep=",", header=1)
if date_column in self.data.columns:
self.date_column = date_column
else:
ValueError(
f"Column-Name {date_column} is not given in the provided csv-file"
)
if glucose_column in self.data.columns:
self.glucose_column = glucose_column
else:
ValueError(
f"Column-Name {glucose_column} is not given in the provided csv-file"
)
self.data = self.data[
self.data[self.date_column].notna() & self.data[self.glucose_column].notna()
]
self.data[self.date_column] = pd.to_datetime(
self.data[self.date_column], format="%m-%d-%Y %H:%M"
)
self.data.sort_values(by=self.date_column, inplace=True)
self.weeks = self.segmenting_time_period()
self.data[self.glucose_column] = self.convert_glucose_data()
self._add_figure_folder()
@property
def dates(self) -> pd.Series:
"""dates in the data"""
return self.data[self.date_column]
@property
def glucose(self) -> pd.Series:
"""glucose-values in the data"""
return self.data[self.glucose_column]
def _add_figure_folder(self) -> None:
"""adds figure-folder"""
if not Path("./figures/").exists():
Path("./figures/").mkdir()
def segmenting_time_period(self, days_per_segment=7) -> list[Week]:
"""
partitioning the full period into segements
"""
first_day = self.dates.min().date()
if first_day.weekday() > 0:
first_day = first_day - timedelta(first_day.weekday())
last_day = self.dates.max().date()
first_week_day = first_day
weeks = []
week = 0
while first_week_day < last_day:
first_week_day = first_week_day + timedelta(days_per_segment)
week += 1
weeks.append(Week(first_week_day, week))
return weeks
def convert_glucose_data(self) -> pd.Series:
"""
convert glucose-data saved as string with comma as decimal
to numeric values
"""
glucose_data = self.data[self.glucose_column]
glucose_data = glucose_data.str.replace(pat=",", repl=".")
return pd.to_numeric(glucose_data)
def plot_week(self, week: int | Week) -> str:
"""plot the data within the given ``week_number``"""
if isinstance(week, int):
week = list(filter(lambda x: x.week_number == week, self.weeks))[0]
filter_week = (week.first_day <= self.data[self.date_column].dt.date) & (
self.data[self.date_column].dt.date <= week.last_day
)
week_data = self.data[filter_week]
if len(week_data) == 0:
print(f"In week {week} does no data exist")
return
fig, ax = plt.subplots(figsize=(18 * 0.39, 5.0 * 0.39))
ax.plot(week_data[self.date_column], week_data[self.glucose_column])
ax.set_ylabel("Glukose [mmol/L]")
date_form = DateFormatter("%a")
ax.xaxis.set_major_formatter(date_form)
ax.grid("major")
ax.set_title(
f"Kalenderwoche {week.calender_week()}/{week.year()}: {week.time_span()}"
)
ax.set_xlim(week.first_day, week.last_day + timedelta(days=1))
ax.set_ylim(0, 25)
ax.fill_between(
x=[week.first_day, week.last_day + timedelta(days=1)],
y1=10.0,
y2=3.9,
color="lightgray",
)
path = self.plot_path(week)
fig.savefig(path, format="pgf")
return path
def plot_path(self, week: Week):
return f"./figures/Week{week.week_number}-{week.time_span()}.pgf"
def plot_last_week(self) -> list[str]:
last_week = max(self.weeks.keys())
return [self.plot_week(last_week)]
def plot_all_weeks(self) -> list[str]:
first_week = min(self.weeks.keys())
last_week = max(self.weeks.keys())
return self.plot_week_range(first_week, last_week)
def plot_week_range(self, first_week: int, last_week: int) -> list[str]:
paths = []
for week in range(first_week, last_week):
paths.append(self.plot_week(week))
return paths
def plot_since_three_month(self) -> list[str]:
starting_date = date.today() - timedelta(weeks=3 * 4)
for week in self.weeks:
if week.inside_week(starting_date):
starting_week = week.week_number
return self.plot_week_range(starting_week, len(self.weeks))
def date_format(self) -> str:
return "%d-%m-%Y"
class PDF:
"""create a pdf from the given pgf's using LaTeX"""
def __init__(self, pgf_paths: list[str], file_name: str, name: str = None):
self.pgf_paths = [Path(pgf) for pgf in pgf_paths if Path(pgf).exists()]
self._name = name
self._file_name = file_name
self.build_tex_file()
self.compile_latex()
def preamble(self) -> list[str]:
"""get the preamble of the LaTeX-document"""
lines = [
"\\documentclass[DIV=15]{scrreprt}",
"\\usepackage[T1]{fontenc}",
"\\usepackage[utf8]{inputenc}",
"\\usepackage[ngerman]{babel}",
"\\usepackage{txfonts}%",
"\\usepackage{pgfplots}",
"\\usepackage{scrlayer-scrpage}",
f"\\ihead{{{self._name}}}",
"\\ohead{Glukose-Werte}",
]
return lines
def document(self) -> list[str]:
"""build the document"""
lines = ["\\begin{document}", ""]
for path in self.pgf_paths:
lines.append("\\begin{center}")
lines.append(f"\t\\input{{{str(path)}}}")
lines.append("\\end{center}")
lines.append("")
lines.append("\\end{document}")
return lines
def build_tex_file(self) -> None:
"""buils the tex-file"""
lines = self.preamble() + self.document()
with open(self._file_name + ".tex", "w") as tex:
tex.write("\n".join(lines))
def compile_latex(self) -> None:
"""compiles the LaTeX-document"""
subprocess.call(["pdflatex", self._file_name + ".tex"])
if __name__ == "__main__":
c_g_v = CGV(csv_path="./data/20230725.csv")
PDF(c_g_v.plot_since_three_month(), name="Johannes Schorr")