### Import Python Libraries and Setup Paths Source: https://github.com/ai4healthurjc/glucostats/blob/main/examples/run_examples.ipynb Imports essential Python libraries and configures project paths for accessing examples and modules. Ensure these libraries are installed in your environment. ```python import os import sys import numpy as np import pandas as pd from pathlib import Path # Set path for examples folder and define paths PATH_PROJECT_DIR = Path(__file__).resolve().parents[1] PATH_PROJECT_EXAMPLES = Path.joinpath(PATH_PROJECT_DIR, 'examples') sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from glucostats.extract_statistics import ExtractGlucoStats ``` -------------------------------- ### Install Glucostats using pip Source: https://github.com/ai4healthurjc/glucostats/blob/main/README.md Install the Glucostats library using pip for quick setup. ```console pip install glucostats ``` -------------------------------- ### Install Dependencies from Requirements Source: https://github.com/ai4healthurjc/glucostats/blob/main/README.md Install Python dependencies required for Glucostats when installing from source. ```console pip install -r requirements.txt ``` -------------------------------- ### Basic Glucostats Usage Example Source: https://github.com/ai4healthurjc/glucostats/blob/main/README.md Demonstrates loading glucose data, configuring statistics extraction with windowing, and transforming the data to compute statistics. Ensure 'id', 'time', and 'glucose' columns are present in the DataFrame. ```python import pandas as pd from glucostats.datasets import load_glucodata from glucostats.extract_statistics import ExtractGlucoStats # Load example of glucose data df_data = load_glucodata() # Change datetime format and set index for multiple signals df_data.index = df_data['id'] df_data = df_data[['time', 'glucose']] df_data["time"] = pd.to_datetime(df_data["time"], errors="coerce") # Define list of statistics to compute list_statistics = ['hypo_index', 'max_lbgi', 'mean'] # Define parameters for creating windows windowing = True windowing_method = 'number' windowing_param = 4 windowing_start = 'tail' windowing_overlap = False # Instantiate ExtractGlucoStats class stats_extraction = ExtractGlucoStats( list_statistics, windowing, windowing_method, windowing_param, windowing_start, windowing_overlap, batch_size=20, n_workers=4 ) # Configuration of intervals for hypoglycemia, euglycemia, hyperglycemia in_range_interval = [70, 180] # Class configuration and statistics extraction stats_extraction.configuration(in_range_interval=in_range_interval) df_cgm_stats = stats_extraction.transform(df_data) ``` -------------------------------- ### Windowing Methods: Static Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Configures ExtractGlucoStats for static windowing, using fixed duration windows (e.g., 4 hours). Starts from the head of the signal with no overlap. ```python from glucostats.extract_statistics import ExtractGlucoStats # Method 2: Static windowing (fixed window duration) extractor_static = ExtractGlucoStats( list_statistics=['mean', 'std', 'cv'], windowing=True, windowing_method='static', windowing_param=[0, 4, 0, 0], # [days, hours, minutes, seconds] = 4 hours windowing_start='head', windowing_overlap=False ) ``` -------------------------------- ### Windowing Methods: Personalized Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Configures ExtractGlucoStats for personalized windowing, using specific timestamps to define window boundaries. Starts from the head of the signal with no overlap. ```python from datetime import datetime from glucostats.extract_statistics import ExtractGlucoStats # Method 4: Personalized windowing (specific timestamps) extractor_personalized = ExtractGlucoStats( list_statistics=['mean', 'std', 'cv'], windowing=True, windowing_method='personalized', windowing_param=[ datetime(2024, 1, 1, 6, 0, 0), # Cut at 6 AM datetime(2024, 1, 1, 12, 0, 0), # Cut at noon datetime(2024, 1, 1, 18, 0, 0) # Cut at 6 PM ], windowing_start='head', windowing_overlap=False ) # Transform with any method df_stats = extractor_static.transform(df_glucose) # Output columns: 'mean|0', 'mean|1', 'std|0', 'std|1', etc. (per window) ``` -------------------------------- ### Windowing Methods: Dynamic Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Configures ExtractGlucoStats for dynamic windowing, allowing variable window sizes defined by a list of durations. Starts from the tail of the signal with no overlap. ```python from glucostats.extract_statistics import ExtractGlucoStats # Method 3: Dynamic windowing (variable window sizes) extractor_dynamic = ExtractGlucoStats( list_statistics=['mean', 'std', 'cv'], windowing=True, windowing_method='dynamic', windowing_param=[ [0, 2, 0, 0], # First window: 2 hours [0, 4, 0, 0], # Second window: 4 hours [0, 6, 0, 0] # Third window: 6 hours ], windowing_start='tail', windowing_overlap=False ) ``` -------------------------------- ### Extract Glucose Statistics with Windowing and Parallel Processing Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Load example glucose data, prepare it into the required MultiIndex DataFrame format, and then initialize the ExtractGlucoStats class. Configure windowing, batch processing, and parallel computation parameters before transforming the data to extract specified statistics. Ensure data is correctly formatted with 'id', 'time', and 'glucose' columns. ```python import pandas as pd from glucostats.datasets import load_glucodata from glucostats.extract_statistics import ExtractGlucoStats # Load example glucose data df_data = load_glucodata() # Prepare data format: MultiIndex DataFrame with id as index df_data.index = df_data['id'] df_data = df_data[['time', 'glucose']] df_data["time"] = pd.to_datetime(df_data["time"], errors="coerce") # Define statistics to compute (can be individual stats, subgroups, or groups) list_statistics = ['mean', 'std', 'cv', 'gmi', 'lbgi', 'hbgi'] # Initialize extractor with windowing and parallel processing stats_extraction = ExtractGlucoStats( list_statistics=list_statistics, windowing=True, windowing_method='number', # 'number', 'static', 'dynamic', or 'personalized' windowing_param=4, # Number of windows to create windowing_start='tail', # Start from 'tail' or 'head' windowing_overlap=False, # Non-overlapping windows batch_size=20, # Process 20 signals per batch n_workers=4 # Use 4 CPU cores ) # Configure glucose range intervals and parameters stats_extraction.configuration( in_range_interval=[70, 180], # mg/dL range for normal glucose time_units='m', # Time in minutes ddof=1, # Degrees of freedom for std ideal_bg=120 # Ideal blood glucose for m-value ) # Extract statistics df_stats = stats_extraction.transform(df_data) print(df_stats.head()) # Output: DataFrame with computed statistics for each signal/window ``` -------------------------------- ### Windowing Methods: Number Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Configures ExtractGlucoStats for number-based windowing, dividing glucose signals into a fixed number of equal windows. Starts from the tail of the signal with no overlap. ```python import pandas as pd from glucostats.extract_statistics import ExtractGlucoStats # Method 1: Number-based windowing (divide into N equal windows) extractor_number = ExtractGlucoStats( list_statistics=['mean', 'std', 'cv'], windowing=True, windowing_method='number', windowing_param=6, # Create 6 equal windows windowing_start='tail', # Start from end of signal windowing_overlap=False ) ``` -------------------------------- ### Configure Glucose Statistics Calculation Parameters Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Initialize the ExtractGlucoStats extractor without windowing and then use the configuration method to set various parameters for statistics calculation. This includes glucose range intervals, time units, and specific statistical parameters like quartiles, thresholds, and exponents for index calculations. ```python from glucostats.extract_statistics import ExtractGlucoStats # Initialize extractor extractor = ExtractGlucoStats( list_statistics=['distribution', 'control_indexes', 'a1c', 'qgc'], windowing=False ) # Configure all available parameters extractor.configuration( in_range_interval=[70, 180], # [lower, upper] glucose range in mg/dL time_units='m', # 'h' (hours), 'm' (minutes), 's' (seconds) ddof=1, # Delta degrees of freedom for std quartiles=[0.25, 0.5, 0.75], # Quartile values to compute threshold=100, # AUC reference threshold where='above', # AUC calculation: 'above' or 'below' threshold a=1.1, # Hyperglycemic Index exponent (1.0-2.0) b=2.0, # Hypoglycemic Index exponent (1.0-2.0) c=30, # Hyperglycemia scaling factor d=30, # Hypoglycemia scaling factor ideal_bg=120 # Ideal blood glucose for m-value ) # Extract statistics with custom configuration df_stats = extractor.transform(df_data) ``` -------------------------------- ### Request Entire Subgroups with ExtractGlucoStats Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Instantiate ExtractGlucoStats to request entire subgroups such as 'distribution', 'g_indexes', and 'variability'. ```python # Request entire subgroups extractor = ExtractGlucoStats( list_statistics=['distribution', 'g_indexes', 'variability'] ) ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/ai4healthurjc/glucostats/blob/main/README.md Execute all unit tests for the Glucostats library using the pytest command. ```shell pytest -v ``` -------------------------------- ### Mix Individual Stats and Subgroups with ExtractGlucoStats Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Combine requests for individual statistics and entire subgroups within a single ExtractGlucoStats instantiation. This allows for flexible data extraction based on specific analysis needs. ```python # Mix individual stats and subgroups extractor = ExtractGlucoStats( list_statistics=['mean', 'g_indexes', 'variability', 'eA1C'] ) ``` -------------------------------- ### Request Individual Statistics with ExtractGlucoStats Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Instantiate ExtractGlucoStats to request specific individual statistics like mean, std, cv, lbgi, hbgi, and gmi. ```python from glucostats.extract_statistics import ExtractGlucoStats # Request individual statistics extractor = ExtractGlucoStats( list_statistics=['mean', 'std', 'cv', 'lbgi', 'hbgi', 'gmi'] ) ``` -------------------------------- ### Clone Glucostats from GitHub Source: https://github.com/ai4healthurjc/glucostats/blob/main/README.md Clone the Glucostats source code from its GitHub repository. ```console git clone git@github.com:ai4healthurjc/GlucoStats.git ``` -------------------------------- ### Calculate Quality of Glycemic Control Indexes Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Computes the M value and J index, which are quality of glycemic control metrics. The ideal blood glucose level (ideal_bg) can be specified. ```python import pandas as pd from glucostats.stats.control_stats import qgc_index # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [110, 125, 140, 155, 145, 130, 115, 105, 100, 95, 90, 100] * 24 }) df_glucose.index = ['patient_qgc'] * len(df_glucose) # Calculate quality of glycemic control indexes qgc_df = qgc_index(df_glucose, ideal_bg=120) print(qgc_df) ``` -------------------------------- ### Calculate Glycemia Risk Metrics Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculates glycemia risk metrics based on clinical thresholds, including percentage of time in very low, low, high, and very high glucose ranges, as well as the Glycemia Risk Index (GRI). Requires pandas and the glycemia_risk function. ```python import pandas as pd from glucostats.stats.risks_stats import glycemia_risk # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [85, 95, 120, 150, 180, 200, 175, 140, 100, 70, 55, 65] * 24 }) df_glucose.index = ['patient_risk'] * len(df_glucose) # Calculate glycemia risk metrics gri_df = glycemia_risk(df_glucose) print(gri_df) ``` -------------------------------- ### Calculate Glucose Risk Indexes Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Computes various glucose risk indexes including Low Blood Glucose Index (LBGI), High Blood Glucose Index (HBGI), their maximum values, and the overall Blood Glucose Risk Index (BGRI). Requires pandas and the glucose_indexes function. ```python import pandas as pd from glucostats.stats.risks_stats import glucose_indexes # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [85, 95, 120, 150, 180, 200, 175, 140, 100, 70, 55, 65] * 24 }) df_glucose.index = ['patient_risk'] * len(df_glucose) # Calculate glucose indexes gi_df = glucose_indexes(df_glucose) print(gi_df) ``` -------------------------------- ### Calculate Glycemic Control Indexes Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculates Hypoglycemic Index (hypo_index), Hyperglycemic Index (hyper_index), and Index of Glycemic Control (igc). Requires specifying the in-range interval and exponents for hyperglycemia and hypoglycemia. ```python import pandas as pd from glucostats.stats.control_stats import g_control # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [65, 80, 100, 130, 170, 210, 190, 150, 110, 75, 60, 90] * 24 }) df_glucose.index = ['patient_ctrl'] * len(df_glucose) # Calculate glycemic control indexes control_df = g_control( df_glucose, in_range_interval=[70, 180], a=1.1, # Hyperglycemia exponent b=2.0, # Hypoglycemia exponent c=30, # Scaling factor d=30 # Scaling factor ) print(control_df) ``` -------------------------------- ### Calculate Glucose Signal Complexity Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Computes signal complexity metrics, specifically sample entropy and Detrended Fluctuation Analysis (DFA), using the neurokit2 library. Requires pandas and the complexity function. ```python import pandas as pd from glucostats.stats.descriptive_stats import complexity # Prepare glucose time series data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=500, freq='5min'), 'glucose': [120 + 30 * (i % 10 - 5) / 5 + (i % 7) * 3 for i in range(500)] }) df_glucose.index = ['patient_1'] * len(df_glucose) # Calculate complexity metrics complexity_df = complexity(df_glucose) print(complexity_df) ``` -------------------------------- ### Calculate Glucose Distribution Statistics Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Computes descriptive statistics for glucose data, including max, min, mean, std, quartiles, and IQR. Allows custom quartiles and sample standard deviation calculation (ddof=1). ```python import pandas as pd from glucostats.stats.descriptive_stats import distribution # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=200, freq='5min'), 'glucose': [100 + i % 50 + (i * 0.5) % 30 for i in range(200)] }) df_glucose.index = ['patient_X'] * len(df_glucose) # Calculate distribution statistics dist_df = distribution( df_glucose, ddof=1, # Sample standard deviation qs=[0.10, 0.25, 0.5, 0.75, 0.90] # Custom quartiles ) print(dist_df) ``` -------------------------------- ### Plot Glucose Time Series Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Generates a time series plot of glucose levels, with colored backgrounds indicating hypoglycemia, normoglycemia, and hyperglycemia. Requires pandas DataFrame with 'time' and 'glucose' columns. ```python import pandas as pd from glucostats.visualization.signal_visualization import plot_glucose_time_series # Prepare glucose data for multiple patients df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min').tolist() * 2, 'glucose': [120 + i % 80 for i in range(288)] + [100 + i % 60 for i in range(288)] }) df_glucose.index = ['patient_A'] * 288 + ['patient_B'] * 288 # Plot glucose time series for selected patients plot_glucose_time_series( df_signals=df_glucose, signals_ids=['patient_A', 'patient_B'], # Can be single ID or list hypo_1_threshold=70, # Type 1 hypoglycemia threshold hypo_2_threshold=54, # Type 2 hypoglycemia (severe) hyper_threshold=180, # Hyperglycemia threshold saving_path='glucose_plot.png' # Optional: save to file ) # Output: Matplotlib figure showing glucose traces with colored range backgrounds ``` -------------------------------- ### Estimate HbA1c Values Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Estimates HbA1c using the Glucose Management Indicator (gmi) and Estimated A1C (eA1C) methods. Requires glucose data, typically over a 14-day period for accurate estimation. ```python import pandas as pd from glucostats.stats.control_stats import a1c_estimation # Prepare glucose data (14 days of CGM readings) df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=4032, freq='5min'), # 14 days 'glucose': [135 + (i % 50) - 25 for i in range(4032)] # Mean ~135 mg/dL }) df_glucose.index = ['patient_a1c'] * len(df_glucose) # Estimate A1C values a1c_df = a1c_estimation(df_glucose) print(a1c_df) ``` -------------------------------- ### Calculate Percentage of Observations in Ranges Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculates the percentage of glucose observations within specified ranges. Requires pandas and the percentage_observations_in_ranges function. ```python import pandas as pd from glucostats.stats.observations_stats import percentage_observations_in_ranges # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=100, freq='5min'), 'glucose': [85, 110, 150, 190, 220, 65, 50, 130, 175, 95] * 10 }) df_glucose.index = ['signal_A'] * len(df_glucose) # Calculate percentage of observations pct_obs_df = percentage_observations_in_ranges(df_glucose, in_range_interval=[70, 180]) print(pct_obs_df) ``` -------------------------------- ### Calculate Glycemia Risk Statistics Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Use this function to calculate glycemia risk statistics, including percentages in different glucose level categories and the overall glycemia risk index (gri). ```python import pandas as pd from glucostats.stats.risks_stats import glycemia_risk # Prepare glucose data with various glucose levels df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [50, 60, 80, 120, 160, 200, 260, 180, 140, 100, 75, 55] * 24 }) df_glucose.index = ['patient_gri'] * len(df_glucose) # Calculate glycemia risk gr_df = glycemia_risk(df_glucose) print(gr_df) ``` -------------------------------- ### Plot Intrapatient Heatmap Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Generates an intrapatient heatmap visualizing a statistic across time windows and days for a single patient. Useful for identifying temporal patterns. Requires statistics and time ranges data. ```python from datetime import date from glucostats.visualization.heatmaps import plot_intrapatient_heatmap # Assuming df_stats and time_ranges from ExtractGlucoStats # extractor.statistics and extractor.signals_time_ranges # Plot intrapatient heatmap plot_intrapatient_heatmap( df_stats=extractor.statistics, # Statistics DataFrame signals_time_ranges=extractor.signals_time_ranges, # Time ranges patient='patient_001', # Patient ID prefix stat='mean', # Statistic to visualize days=[date(2024, 1, 1), date(2024, 1, 15)], # Date range (max 31 days) saving_path='heatmap_patient.pdf' # Optional: save to PDF ) # Output: Heatmap with dates on x-axis, time of day on y-axis, colored by stat value ``` -------------------------------- ### Calculate Percentage Time in Ranges Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculates the percentage of time glucose levels spent within specified ranges. Requires the pandas library and the percentage_time_in_ranges function. ```python import pandas as pd from glucostats.stats.observations_stats import percentage_time_in_ranges # Assuming df_glucose is a pandas DataFrame with glucose data # Example DataFrame structure: # df_glucose = pd.DataFrame({ # 'time': pd.to_datetime(['2024-01-01 00:00', '2024-01-01 00:05', ...]), # 'glucose': [70, 80, 90, ...] # }) # df_glucose.index = ['patient_001'] * len(df_glucose) # Placeholder for df_glucose for demonstration df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=10, freq='5min'), 'glucose': [70, 80, 90, 100, 110, 120, 130, 140, 150, 160] }) df_glucose.index = ['patient_001'] * len(df_glucose) # Calculate percentage time in ranges pct_time_df = percentage_time_in_ranges(df_glucose, in_range_interval=[70, 180]) print(pct_time_df) ``` -------------------------------- ### Calculate GRADE Statistics Source: https://context7.com/ai4healthurjc/glucostats/llms.txt This function computes the Glycemic Risk Assessment Diabetes Equation (GRADE) and its components, including total GRADE, and percentages in hypoglycemia, euglycemia, and hyperglycemia. ```python import pandas as pd from glucostats.stats.risks_stats import grade # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [70, 90, 110, 130, 150, 170, 190, 160, 120, 85, 65, 95] * 24 }) df_glucose.index = ['patient_grade'] * len(df_glucose) # Calculate GRADE statistics grade_df = grade(df_glucose) print(grade_df) ``` -------------------------------- ### Plot Interpatient Heatmap Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Generates an interpatient heatmap comparing a statistic across multiple patients over a time period. Useful for cohort-level analysis. Requires statistics and time ranges data. ```python from datetime import date from glucostats.visualization.heatmaps import plot_interpatient_heatmap # Plot interpatient heatmap for multiple patients plot_interpatient_heatmap( df_stats=extractor.statistics, signals_time_ranges=extractor.signals_time_ranges, patients=['patient_001', 'patient_002', 'patient_003'], # List of patient IDs stat='cv', # Coefficient of variation days=[date(2024, 1, 1), date(2024, 1, 7)], # Date range (max 31 days) saving_path='heatmap_cohort.pdf' ) # Output: Heatmap with patients on y-axis, time on x-axis, colored by stat value ``` -------------------------------- ### Calculate Glycemic Excursion Statistics Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Computes Mean Amplitude of Glycemic Excursions (mage) and Excursion Frequency (ef). This function is useful for analyzing the frequency and magnitude of glucose level changes. ```python import pandas as pd from glucostats.stats.variability_stats import signal_excursions # Prepare glucose data with excursions df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [100, 110, 130, 180, 200, 190, 150, 100, 80, 70, 85, 120] * 24 }) df_glucose.index = ['patient_exc'] * len(df_glucose) # Calculate excursion statistics exc_df = signal_excursions(df_glucose) print(exc_df) ``` -------------------------------- ### Calculate Glucose Variability Statistics Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculates glucose variability metrics including Distance Travelled (dt), Mean Absolute Glucose (mag), Glycemic Variability Percentage (gvp), and Coefficient of Variation (cv). ```python import pandas as pd from glucostats.stats.variability_stats import glucose_variability # Prepare glucose data with variable readings df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [100, 130, 90, 150, 80, 170, 95, 140, 85, 160, 110, 125] * 24 }) df_glucose.index = ['patient_var'] * len(df_glucose) # Calculate variability statistics var_df = glucose_variability(df_glucose) print(var_df) ``` -------------------------------- ### Calculate Area Under the Curve (AUC) Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculates the Area Under the Curve (AUC) using the trapezoidal rule, either above or below a specified threshold. Useful for quantifying hyperglycemia or hypoglycemia burden. Requires pandas and the auc function. ```python import pandas as pd from glucostats.stats.descriptive_stats import auc # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [150, 180, 200, 175, 160, 140, 120, 100, 90, 85, 95, 110] * 24 }) df_glucose.index = ['patient_A'] * len(df_glucose) # Calculate AUC above threshold (hyperglycemia burden) auc_above = auc(df_glucose, threshold=180, where='above') print(auc_above) # Calculate AUC below threshold (hypoglycemia burden) auc_below = auc(df_glucose, threshold=70, where='below') print(auc_below) ``` -------------------------------- ### Count Observations in Glucose Ranges Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Counts the number of glucose observations falling into specified ranges (in range, above range, below range, out of range). Requires pandas and the observations_in_ranges function. ```python import pandas as pd from glucostats.stats.observations_stats import observations_in_ranges # Prepare glucose data df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=100, freq='5min'), 'glucose': [85, 110, 150, 190, 220, 65, 50, 130, 175, 95] * 10 }) df_glucose.index = ['signal_A'] * len(df_glucose) # Count observations in each range obs_df = observations_in_ranges(df_glucose, in_range_interval=[70, 180]) print(obs_df) ``` -------------------------------- ### Calculate Time Spent in Glucose Ranges Source: https://context7.com/ai4healthurjc/glucostats/llms.txt Calculate the absolute time spent in, above, below, and out of specified glucose ranges using the time_in_ranges function. The function requires a pandas DataFrame with a MultiIndex and 'time' and 'glucose' columns. Results are returned in minutes by default. ```python import pandas as pd from glucostats.stats.time_stats import time_in_ranges, percentage_time_in_ranges # Prepare glucose data as MultiIndex DataFrame # Index: signal ID, Columns: ['time', 'glucose'] df_glucose = pd.DataFrame({ 'time': pd.date_range('2024-01-01', periods=288, freq='5min'), 'glucose': [120, 145, 180, 200, 165, 90, 75, 68, 55, 85] * 28 + [120] * 8 }) df_glucose.index = ['patient_001'] * len(df_glucose) # Calculate time in ranges (default: 70-180 mg/dL) time_df = time_in_ranges( df_glucose, in_range_interval=[70, 180], time_units='m' # Results in minutes ) print(time_df) # Output: ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.