|
2 | 2 | import numpy as np |
3 | 3 | import pandas as pd |
4 | 4 |
|
5 | | -from .utils import CGMS2DayByDay, check_data_columns, gd2d_to_df |
| 5 | +from .utils import CGMS2DayByDay, check_data_columns, gd2d_to_df, IGLU_R_COMPATIBLE |
6 | 6 |
|
7 | 7 |
|
8 | 8 | def auc(data: pd.DataFrame, tz: str = "") -> pd.DataFrame: |
@@ -64,25 +64,41 @@ def auc_single(subject_data: pd.DataFrame) -> float: |
64 | 64 | gd2d, actual_dates, dt0 = CGMS2DayByDay(subject_data, tz=tz) |
65 | 65 |
|
66 | 66 | # Convert gd2d to DataFrame |
67 | | - hourly_data = gd2d_to_df(gd2d, actual_dates, dt0) |
68 | | - # Add hour column by rounding time to nearest hour |
69 | | - hourly_data['hour'] = hourly_data['time'].dt.floor('h') |
70 | | - |
71 | | - hourly_data['gl_next'] = hourly_data['gl'].shift(-1) |
72 | | - |
73 | | - # Calculate AUC for each hour using trapezoidal rule (mg*min/dL) |
74 | | - hourly_auc = hourly_data.groupby("hour").apply( |
75 | | - lambda x: np.nansum( |
76 | | - (dt0/60)*(x["gl"].values + x["gl_next"].values) / 2 |
77 | | - ), |
78 | | - include_groups=False |
79 | | - ) |
80 | | - # 0 mean no data in this hour, replace with nan |
81 | | - hourly_auc = hourly_auc.replace(0, np.nan) |
82 | | - |
83 | | - hourly_avg = hourly_auc.mean(skipna=True) |
84 | | - # Return mean of daily hourly averages |
85 | | - return hourly_avg |
| 67 | + input_data = gd2d_to_df(gd2d, actual_dates, dt0) |
| 68 | + if IGLU_R_COMPATIBLE: |
| 69 | + input_data['day'] = input_data['time'].dt.floor('d') |
| 70 | + input_data['gl_next'] = input_data['gl'].shift(-1) |
| 71 | + each_day_area = input_data.groupby("day").apply( |
| 72 | + lambda x: np.nansum( |
| 73 | + (dt0/60)*(x["gl"].values + x["gl_next"].values) / 2 |
| 74 | + ), |
| 75 | + include_groups=False |
| 76 | + ) |
| 77 | + # calculate number of not nan trapezoids in total (number of not nan gl and gl_next) |
| 78 | + n_trapezoids = (~np.isnan(input_data["gl"]) & ~np.isnan(input_data["gl_next"])).sum() |
| 79 | + hours = dt0/60 * n_trapezoids |
| 80 | + daily_area = each_day_area.sum() |
| 81 | + hourly_avg = daily_area/hours |
| 82 | + return hourly_avg |
| 83 | + else: |
| 84 | + # Add hour column by rounding time to nearest hour |
| 85 | + input_data['hour'] = input_data['time'].dt.floor('h') |
| 86 | + |
| 87 | + input_data['gl_next'] = input_data['gl'].shift(-1) |
| 88 | + |
| 89 | + # Calculate AUC for each hour using trapezoidal rule (mg*min/dL) |
| 90 | + hourly_auc = input_data.groupby("hour").apply( |
| 91 | + lambda x: np.nansum( |
| 92 | + (dt0/60)*(x["gl"].values + x["gl_next"].values) / 2 |
| 93 | + ), |
| 94 | + include_groups=False |
| 95 | + ) |
| 96 | + # 0 mean no data in this hour, replace with nan |
| 97 | + hourly_auc = hourly_auc.replace(0, np.nan) |
| 98 | + |
| 99 | + hourly_avg = hourly_auc.mean(skipna=True) |
| 100 | + # Return mean of daily hourly averages |
| 101 | + return hourly_avg |
86 | 102 |
|
87 | 103 | # Process each subject |
88 | 104 | result = [] |
|
0 commit comments