Spaces:
Sleeping
Sleeping
File size: 19,989 Bytes
9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 286eea9 9e0d992 afba4df 9e0d992 286eea9 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 286eea9 9e0d992 286eea9 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 286eea9 9e0d992 286eea9 9e0d992 afba4df 286eea9 afba4df 286eea9 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 afba4df 9e0d992 286eea9 9e0d992 286eea9 9e0d992 286eea9 9e0d992 286eea9 afba4df 286eea9 afba4df 286eea9 afba4df 286eea9 9e0d992 286eea9 9e0d992 286eea9 9e0d992 286eea9 9e0d992 286eea9 9e0d992 afba4df 9e0d992 |
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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
from __future__ import annotations
"""Sundew Diabetes Commons – holistic, open Streamlit experience.
This app demonstrates a lightweight gating pipeline with an optional native
Sundew integration, feature engineering over CGM-like time series, a simple
logistic baseline, and a compact UI for overview, treatment, lifestyle, and
telemetry.
⚠️ Medical disclaimer: This software is for research & educational purposes only
and does *not* provide medical advice. Always consult qualified clinicians.
Copyright (c) 2025 The Sundew Diabetes Commons authors
SPDX-License-Identifier: Apache-2.0
"""
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple
import json
import logging
import math
import numpy as np
import pandas as pd
import streamlit as st
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# -----------------------------------------------------------------------------
# Optional Sundew dependency (kept import-safe for open source distribution)
# -----------------------------------------------------------------------------
try:
from sundew import SundewAlgorithm # type: ignore[attr-defined]
from sundew.config import SundewConfig
from sundew.config_presets import get_preset
_HAS_SUNDEW = True
except Exception: # pragma: no cover - fallback when package is unavailable
SundewAlgorithm = None # type: ignore
SundewConfig = object # type: ignore
def get_preset(_: str) -> Any: # type: ignore
return None
_HAS_SUNDEW = False
LOGGER = logging.getLogger("sundew.diabetes.commons")
if not LOGGER.handlers:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
# -----------------------------------------------------------------------------
# Config & Gate
# -----------------------------------------------------------------------------
@dataclass
class SundewGateConfig:
target_activation: float = 0.22
temperature: float = 0.08
mode: str = "tuned_v2"
use_native: bool = True
rng_seed: Optional[int] = 17
def _build_sundew_runtime(config: SundewGateConfig) -> Optional["SundewAlgorithm"]:
"""Try multiple Sundew constructor forms; fall back to None if unavailable."""
if not (config.use_native and _HAS_SUNDEW and SundewAlgorithm is not None):
return None
try:
preset = get_preset(config.mode)
except Exception:
LOGGER.warning("Could not load preset %s; using bare SundewConfig", config.mode)
preset = SundewConfig() # type: ignore
# best-effort attribute binding
for attr, value in (
("target_activation_rate", config.target_activation),
("gate_temperature", config.temperature),
):
try:
setattr(preset, attr, value)
except Exception:
LOGGER.debug("Preset missing attribute %s", attr)
# try common constructor signatures
for constructor in (
lambda: SundewAlgorithm(preset), # type: ignore[arg-type]
lambda: SundewAlgorithm(config=preset), # type: ignore[arg-type]
lambda: SundewAlgorithm(),
):
try:
return constructor()
except Exception as exc:
LOGGER.debug("Sundew constructor failed: %s", exc)
continue
return None
class AdaptiveGate:
"""Adapter that hides Sundew/Fallback branching.
If native Sundew is not present, uses a simple logistic gate whose threshold
self-adjusts via a moving target activation rate.
"""
def __init__(self, config: SundewGateConfig) -> None:
self.config = config
self._ema = 0.0
self._tau = float(np.clip(config.target_activation, 0.05, 0.95))
self._alpha = 0.05
self._rng = np.random.default_rng(config.rng_seed)
self.sundew: Optional["SundewAlgorithm"] = _build_sundew_runtime(config)
def decide(self, score: float) -> bool:
if self.sundew is not None:
for attr in ("decide", "step", "open"):
fn = getattr(self.sundew, attr, None)
if callable(fn):
try:
return bool(fn(score))
except Exception as exc:
LOGGER.debug("Sundew.%s failed: %s", attr, exc)
continue
# Fallback: temperatured logistic on a normalized score
normalized = float(np.clip(score / 1.4, 0.0, 1.0))
temperature = max(self.config.temperature, 0.02)
probability = 1.0 / (1.0 + math.exp(-(normalized - self._tau) / temperature))
fired = bool(self._rng.random() < probability)
# EMA of activations and threshold nudging toward target rate
self._ema = (1 - self._alpha) * self._ema + self._alpha * (1.0 if fired else 0.0)
self._tau += 0.05 * (self.config.target_activation - self._ema)
self._tau = float(np.clip(self._tau, 0.05, 0.95))
return fired
# -----------------------------------------------------------------------------
# Data utilities
# -----------------------------------------------------------------------------
def load_example_dataset(n_rows: int = 720) -> pd.DataFrame:
rng = np.random.default_rng(17)
t0 = pd.Timestamp.utcnow().floor("5min") - pd.Timedelta(minutes=5 * n_rows)
timestamps = [t0 + pd.Timedelta(minutes=5 * i) for i in range(n_rows)]
base = 118 + 28 * np.sin(np.linspace(0, 7 * math.pi, n_rows))
noise = rng.normal(0, 12, n_rows)
meals = (rng.random(n_rows) < 0.05).astype(float) * rng.normal(50, 18, n_rows).clip(0, 150)
insulin = (rng.random(n_rows) < 0.03).astype(float) * rng.normal(4.2, 1.5, n_rows).clip(0, 10)
steps = rng.integers(0, 200, size=n_rows)
heart_rate = 68 + (steps > 90) * rng.integers(20, 45, size=n_rows)
sleep_flag = (rng.random(n_rows) < 0.12).astype(float)
stress_index = rng.uniform(0, 1, n_rows)
glucose = base + noise
for i in range(n_rows):
if i >= 6:
glucose[i] += 0.4 * meals[i - 6 : i].sum() / 6
if i >= 4:
glucose[i] -= 1.2 * insulin[i - 4 : i].sum() / 4
if steps[i] > 100:
glucose[i] -= 15
glucose[180:200] = rng.normal(62, 5, 20)
glucose[350:365] = rng.normal(210, 10, 15)
return pd.DataFrame(
{
"timestamp": timestamps,
"glucose_mgdl": np.round(np.clip(glucose, 40, 350), 1),
"carbs_g": np.round(meals, 1),
"insulin_units": np.round(insulin, 1),
"steps": steps.astype(int),
"hr": (heart_rate + rng.normal(0, 5, n_rows)).round().astype(int),
"sleep_flag": sleep_flag,
"stress_index": stress_index,
}
)
def compute_features(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy().sort_values("timestamp").reset_index(drop=True)
df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
# Time delta in minutes (robust vs. dtype casting)
dt_min = df["timestamp"].diff().dt.total_seconds().div(60).fillna(5.0)
# Rate of change and smoothed baseline deviation
glucose_prev = df["glucose_mgdl"].shift(1)
df["roc_mgdl_min"] = (df["glucose_mgdl"] - glucose_prev).div(dt_min)
df["roc_mgdl_min"] = df["roc_mgdl_min"].replace([np.inf, -np.inf], 0.0).fillna(0.0)
ema = df["glucose_mgdl"].ewm(span=48, adjust=False).mean()
df["deviation"] = (df["glucose_mgdl"] - ema).fillna(0.0)
df["iob_proxy"] = df["insulin_units"].rolling(12, min_periods=1).sum() / 12.0
df["cob_proxy"] = df["carbs_g"].rolling(12, min_periods=1).sum() / 12.0
df["variability"] = df["glucose_mgdl"].rolling(24, min_periods=2).std().fillna(0.0)
df["activity_factor"] = (df["steps"].div(200.0) + df["hr"].div(160.0)).clip(0, 1)
df["sleep_flag"] = df.get("sleep_flag", 0.0)
df["stress_index"] = df.get("stress_index", 0.5)
return df[
[
"timestamp",
"glucose_mgdl",
"roc_mgdl_min",
"deviation",
"iob_proxy",
"cob_proxy",
"variability",
"activity_factor",
"sleep_flag",
"stress_index",
]
].copy()
# -----------------------------------------------------------------------------
# Scoring & Modeling
# -----------------------------------------------------------------------------
def lightweight_score(row: pd.Series) -> float:
glucose = row["glucose_mgdl"]
roc = row["roc_mgdl_min"]
deviation = row["deviation"]
iob = row["iob_proxy"]
cob = row["cob_proxy"]
stress = row["stress_index"]
score = 0.0
score += max(0.0, (glucose - 180) / 80)
score += max(0.0, (70 - glucose) / 30)
score += abs(roc) / 6.0
score += abs(deviation) / 100.0
score += stress * 0.4
score += max(0.0, (cob - iob) * 0.04)
return float(np.clip(score, 0.0, 1.4))
def train_simple_model(df: pd.DataFrame) -> Optional[Pipeline]:
features = df[[
"glucose_mgdl",
"roc_mgdl_min",
"iob_proxy",
"cob_proxy",
"activity_factor",
"variability",
]]
labels = (df["glucose_mgdl"] > 180).astype(int)
model: Pipeline = Pipeline(
[
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=400, class_weight="balanced")),
]
)
try:
model.fit(features, labels)
return model
except Exception as exc:
LOGGER.warning("Model training failed: %s", exc)
return None
# -----------------------------------------------------------------------------
# UI rendering
# -----------------------------------------------------------------------------
def render_overview(
results: pd.DataFrame,
alerts: List[Dict[str, Any]],
gate_config: SundewGateConfig,
) -> None:
total = len(results)
activations = int(results["activated"].sum())
activation_rate = activations / max(total, 1)
energy_savings = max(0.0, 1.0 - activation_rate)
col_a, col_b, col_c, col_d = st.columns(4)
col_a.metric("Events", f"{total}")
col_b.metric("Heavy activations", f"{activations} ({activation_rate:.1%})")
col_c.metric("Estimated energy saved", f"{energy_savings:.1%}")
col_d.metric("Alerts", f"{len(alerts)}")
if gate_config.use_native and _HAS_SUNDEW:
st.caption(
"Energy savings follow 1 − activation rate. With native Sundew gating we target "
f"≈{gate_config.target_activation:.0%} activations, so savings approach "
f"{1 - gate_config.target_activation:.0%}."
)
else:
st.warning(
"Fallback gate active – heavy inference runs frequently, so savings mirror the observed activation rate."
)
with st.expander("Recent alerts", expanded=False):
if alerts:
st.table(pd.DataFrame(alerts).tail(10))
else:
st.info("No high-risk alerts in this window.")
st.area_chart(results.set_index("timestamp")["glucose_mgdl"], height=220)
def render_treatment_plan(medications: Dict[str, Any], next_visit: str) -> None:
st.subheader("Full-cycle treatment support")
st.write(
"Upload or edit medication schedules, insulin titration guidance, and clinician notes."
)
st.json(medications, expanded=False)
st.caption(f"Next scheduled review: {next_visit}")
def render_lifestyle_support(results: pd.DataFrame) -> None:
st.subheader("Lifestyle & wellbeing")
recent = results.tail(96).copy()
avg_glucose = recent["glucose_mgdl"].mean()
active_minutes = int((recent["activity_factor"] > 0.4).sum() * 5)
col1, col2 = st.columns(2)
col1.metric("Average glucose (8h)", f"{avg_glucose:.1f} mg/dL")
col2.metric("Active minutes", f"{active_minutes} min")
st.markdown(
"""
- Aim for gentle movement every hour you are awake.
- Pair carbohydrates with protein/fiber to smooth spikes.
- Sleep flagged recently? Try 10‑minute breathing before bed.
- Journal one gratitude moment — stress strongly shapes risk.
"""
)
def render_community_actions() -> Dict[str, List[str]]:
st.subheader("Community impact")
st.write(
"Invite families, caregivers, and clinics to the commons. Set up alerts, shared logs, and outreach."
)
contact_list = [
"SMS: +233-200-000-111",
"WhatsApp: Care Circle Group",
"Clinic portal: sundew.health/community",
]
st.table(pd.DataFrame({"Support channel": contact_list}))
return {
"Desired partners": ["Rural clinics", "Youth ambassadors", "Nutrition co-ops"],
"Needs": ["Smartphone grants", "Solar charging kits", "Translation volunteers"],
}
def render_telemetry(results: pd.DataFrame, telemetry: List[Dict[str, Any]]) -> None:
st.subheader("Telemetry & export")
st.write(
"Download event-level telemetry for validation, research, or regulatory reporting."
)
st.caption(
"Energy savings are computed as 1 minus the observed activation rate. When the gate stays mostly open, savings naturally trend toward zero."
)
json_payload = json.dumps(telemetry, default=str, indent=2)
st.download_button(
label="Download telemetry (JSON)",
data=json_payload,
file_name="sundew_diabetes_telemetry.json",
mime="application/json",
)
st.dataframe(results.tail(100), use_container_width=True)
# -----------------------------------------------------------------------------
# App
# -----------------------------------------------------------------------------
def main() -> None:
st.set_page_config(page_title="Sundew Diabetes Commons", layout="wide", page_icon="🩺")
st.title("Sundew Diabetes Commons")
st.caption("Open, compassionate diabetes care — monitoring, treatment, lifestyle, community.")
# Sidebar – data
st.sidebar.header("Load data")
uploaded = st.sidebar.file_uploader("CGM / diary CSV", type=["csv"])
use_example = st.sidebar.checkbox("Use synthetic example", True)
# Sidebar – config
st.sidebar.header("Sundew configuration")
use_native = st.sidebar.checkbox(
"Use native Sundew gating",
value=_HAS_SUNDEW,
help="Disable to demo the lightweight fallback gate only.",
)
target_activation = st.sidebar.slider("Target activation", 0.05, 0.90, 0.22, 0.01)
temperature = st.sidebar.slider("Gate temperature", 0.02, 0.50, 0.08, 0.01)
mode = st.sidebar.selectbox("Preset", ["tuned_v2", "conservative", "aggressive", "auto_tuned"], index=0)
# Data source
if uploaded is not None:
df = pd.read_csv(uploaded)
elif use_example:
df = load_example_dataset()
else:
st.stop()
features = compute_features(df)
model = train_simple_model(features)
gate_config = SundewGateConfig(
target_activation=target_activation,
temperature=temperature,
mode=mode,
use_native=use_native,
)
gate = AdaptiveGate(gate_config)
telemetry: List[Dict[str, Any]] = []
records: List[Dict[str, Any]] = []
alerts: List[Dict[str, Any]] = []
progress = st.progress(0)
status = st.empty()
for idx, row in enumerate(features.itertuples(index=False), start=1):
row_s = pd.Series(row._asdict())
score = lightweight_score(row_s)
should_run = gate.decide(score)
risk_proba: Optional[float] = None
if should_run and model is not None:
sample = np.array([[
row.glucose_mgdl,
row.roc_mgdl_min,
row.iob_proxy,
row.cob_proxy,
row.activity_factor,
row.variability,
]])
try:
risk_proba = float(model.predict_proba(sample)[0, 1]) # type: ignore[index]
except Exception as exc:
LOGGER.debug("predict_proba failed: %s", exc)
risk_proba = None
if (risk_proba is not None) and (risk_proba >= 0.6):
alerts.append({
"timestamp": row.timestamp,
"glucose": row.glucose_mgdl,
"risk": risk_proba,
"message": "Check CGM, hydrate, plan balanced snack/insulin",
})
records.append({
"timestamp": row.timestamp,
"glucose_mgdl": row.glucose_mgdl,
"roc_mgdl_min": row.roc_mgdl_min,
"deviation": row.deviation,
"iob_proxy": row.iob_proxy,
"cob_proxy": row.cob_proxy,
"variability": row.variability,
"activity_factor": row.activity_factor,
"score": score,
"activated": should_run,
"risk_proba": risk_proba,
})
telemetry.append({
"timestamp": str(row.timestamp),
"score": score,
"activated": should_run,
"risk_proba": risk_proba,
})
progress.progress(idx / len(features))
status.text(f"Processing event {idx}/{len(features)}")
progress.empty()
status.empty()
results = pd.DataFrame(records)
tabs = st.tabs(["Overview", "Treatment", "Lifestyle", "Community", "Telemetry"])
with tabs[0]:
render_overview(results, alerts, gate_config)
with tabs[1]:
st.subheader("Full-cycle treatment support")
default_plan = {
"Insulin": {
"Basal": "14u glargine at 21:00",
"Bolus": "1u per 10g carbs + correction 1u per 40 mg/dL over 140",
},
"Oral medications": {
"Metformin": "500mg breakfast + 500mg dinner",
"Empagliflozin": "10mg once daily (if eGFR > 45)",
},
"Monitoring": [
"CGM sensor change every 10 days",
"Morning fasted CGM calibration",
"Weekly telehealth coaching",
"Quarterly in-person clinician review",
],
"Safety plan": [
"Carry glucose tabs + glucagon kit",
"Emergency contact: +233-200-000-888",
],
"Lifestyle": [
"30 min brisk walk 5x/week",
"Bedtime snack if glucose < 110 mg/dL",
"Hydrate 2L water daily unless contraindicated",
],
}
st.caption("Upload or edit schedules, medication titration guidance, and clinician notes.")
uploaded_plan = st.file_uploader("Optional plan JSON", type=["json"], key="plan_uploader")
plan_text = st.text_area("Edit plan JSON", json.dumps(default_plan, indent=2), height=240)
plan_data = default_plan
if uploaded_plan is not None:
try:
plan_data = json.load(uploaded_plan)
except Exception as exc:
st.error(f"Could not parse uploaded plan JSON: {exc}")
plan_data = default_plan
else:
try:
plan_data = json.loads(plan_text)
except Exception as exc:
st.warning(f"Using default plan because text could not be parsed: {exc}")
plan_data = default_plan
next_visit = (datetime.utcnow() + timedelta(days=30)).strftime("%Y-%m-%d (telehealth)")
render_treatment_plan(plan_data, next_visit=next_visit)
with tabs[2]:
render_lifestyle_support(results)
with tabs[3]:
community_items = render_community_actions()
st.json(community_items, expanded=False)
with tabs[4]:
render_telemetry(results, telemetry)
st.sidebar.markdown("---")
status_text = (
"native gating" if gate_config.use_native and gate.sundew is not None else "fallback gate"
)
st.sidebar.caption(f"Sundew status: {status_text}")
if __name__ == "__main__":
main()
|