Skip to main content
Case Study / 01

LittleLife

Flood Forecasting and Disaster Management System — a satellite ML core with an autonomous agentic response layer

01 / Summary

Executive Summary & Facts

Problem: Monsoon floods across the Indus River basin in Pakistan cause widespread infrastructure loss; optical satellite imagery is blinded by continuous monsoon cloud cover, preventing timely spatial inundation mapping.

Result: Engineered an end-to-end spatiotemporal fusion pipeline prioritizing zero-miss disaster sensitivity, achieving an operational Inundation Recall of 0.8435 (84.5%) alongside a 0.6496 IoU (Dice/F1 of 0.7876) across 19,964 held-out multi-sensor samples, with pixel-level uncertainty bounds derived from Monte Carlo Dropout.

System: LittleLife extends that prediction core into a Flood Forecasting and Disaster Management System. A Python agentic orchestrator watches the shared PostGIS schema, scores district risk on a 60-second cycle, and signals a Go operational core that owns alert audiences, delivery, voice IVR, escalation, and routing.

Role: Lead AI/ML Engineer and system architect for the capstone; owned dataset ingestion, spatiotemporal model architecture, PyTorch training pipelines, spatial validation metrics, and the agentic orchestration layer that connects predictions to response.

Role & OwnershipFinal-year project · Lead AI/ML Engineer (ML core + agentic orchestrator)
Timeframe & Status2025 – 2026 · ML research + agentic response system
Core Stack
PyTorch · ResNet18 · ConvLSTM · U-Net · Monte Carlo Dropout · Google Colab (Tesla T4) · FastAPI · PostgreSQL / PostGIS · Redis · Gemini 2.0 Flash · Twilio Voice
Artifacts & References
Code Repository:Evaluation Notebook:Project Report:
02 / Problem

Problem & Environmental Constraints

Pakistan experiences catastrophic recurring floods during the annual summer monsoon season. Optical satellites (such as Sentinel-2 or Landsat) are frequently unusable for active disaster response because cloud cover obscures flood extents during critical rainfall windows.

Addressing this requires cloud-penetrating Synthetic Aperture Radar (SAR) combined with hydrometeorological indicators. However, SAR backscatter contains severe speckle noise and topographical distortions in mountainous terrain, and precipitation alone fails to account for soil saturation limits or river gradient dynamics.

Prediction is not response. A probability map still needs a decision about which district has crossed a risk boundary, which citizens are inside the hazard polygon, and which channel can reach them when cellular data is degraded. LittleLife adds that operational layer without moving the Go core’s transactional responsibilities into the ML service.

Primary Constraints:
• Compute: Trained strictly on Google Colab using a single NVIDIA Tesla T4 GPU (16 GB VRAM).
• Alignment: Heterogeneous spatial resolutions (Sentinel-1 at 10m vs SMAP soil moisture at ~9km) requiring re-gridding and raster reprojection.
• Reliability: Evacuations and emergency dispatch require actionable spatial confidence intervals rather than raw black-box segmentation.
• Integration: The shared PostGIS schema is owned by Go. The orchestrator reads that schema and emits signals; it does not duplicate alert, delivery, or escalation writes.
03 / ML Core

ML Core: Spatiotemporal Flood Mapping

The pipeline fuses 6 geospatial inputs across spatial and temporal dimensions. The input raster volume contains dual-polarization Sentinel-1 SAR backscatter (VV + VH), GPM precipitation accumulation, SMAP surface soil moisture, SRTM elevation, derived topographic slope, and ESA WorldCover land use masks.

LittleLife ML CorePyTorch · Spatiotemporal Fusion
INPUT SENSORSSentinel-1 SARGPM RainfallSMAP Soil Moist.DEM ElevationSlopeLand CoverSPATIALENCODERResNet18Feature MapsTEMPORALRECURRENTConvLSTMSpatiotemporalDECODER &UNCERTAINTYU-Net DecoderMC Dropout (p=0.2)
Figure 1: End-to-end spatiotemporal flood mapping pipeline. Spatial feature tensors from 6 multi-sensor bands pass through ResNet18 and ConvLSTM before pixel-level segmentation via U-Net.

A truncated ResNet18 acts as the spatial feature extractor, projecting high-resolution spatial contexts into latent embeddings. These embeddings are passed through a ConvLSTM cell to model the temporal progression of rainfall accumulation and antecedent moisture over multi-day lag windows. A symmetric U-Net decoder with skip connections restores spatial resolution to output a 1-channel probability map.

This is the prediction core of LittleLife. The next section covers the system that converts its outputs into district-level decisions and citizen-facing action.

04 / Agentic Orchestrator

Agentic Orchestrator: From Prediction to Response

LittleLife runs two runtimes with a hard boundary. The Python orchestrator is the decision layer: it reads the shared PostGIS schema, scores districts, maintains risk state, serves citizen interfaces, and emits signals. The Go core is the action layer: it owns authentication, transactional writes, alert delivery, escalation, and route navigation.

LittleLife System ArchitecturePython orchestrator · Go operational core
FLOOD EVIDENCEAI flood zonesVerified reportsShelter strainPopulation + terrainShared PostGIS schemaPYTHON ORCHESTRATORSupervisor · 60s cycleSurveillance · risk stateSignal handoff + retriesChat / IVR / admin APIsReads, scores, signalsGO OPERATIONAL COREPolygon audience queryAlert outbox + staff noticeEscalation + navigationTransactional writes / auditOwns citizen-facing actionsignalsCITIZEN INTERFACESGemini chatTwilio IVR
Figure 2: LittleLife separates prediction from action. The Python orchestrator reads the shared schema and emits boundary-crossing signals; the Go core owns polygon audience selection, alert delivery, staff notification, escalation, routing, and transactional writes.
Python OrchestratorGo Operational Core
Reads hazard zones, reports, shelters, population contextResolves the alert audience with polygon containment
Scores districts and maintains watch / elevated stateWrites alerts, deliveries, staff notices, and escalation rows
Emits escalate / stand_down signals with retriesOwns the outbox, provider delivery, and transactional audit
Serves Gemini chat, Twilio IVR, and admin telemetryOwns auth, routing, escalation workflows, and navigation

The 60-second control loop. A supervisor runs one cycle immediately on startup, then every 60 seconds. A Redis lock with a 50-second TTL prevents replicas from double-running a cycle; if Redis is unavailable, the service falls back to an in-process lock. Every cycle writes an orchestrator_decision_runs row with the district snapshot, state transitions, signal outcomes, timings, and worker errors. Surveillance memory (state plus confirmation streaks) is carried in that audit record, so the next cycle can cool a district down even after its inputs disappear.

Agent 1 — Hazard surveillance. The score is deliberately simple and auditable:

composite = 0.6 × AI + 0.4 × min(reports, 10) / 10

A district elevates at 0.70 after 2 consecutive cycles and stands down below 0.60 after 3 consecutive cycles. A watch state starts at 0.50. Reports alone cap at 0.40, so community evidence corroborates the AI signal rather than triggering an alert by itself. Only boundary crossings emit signals; a sustained elevated state does not re-alert every cycle.

Agent 2 — Geofenced signal handoff. The orchestrator does not write alerts. It sends escalate or stand_down to Go with an idempotency key of run_id:region_id:signal. Go performs the PostGIS audience query, raises the citizen alert, and writes the staff notice. Failed deliveries retry three times with backoff; retryable failures stay pending for up to 30 minutes, while 4xx responses are recorded as rejected. Go’s idempotency table makes a replay safe.

Agent 3 — Outbound voice IVR. For critical alerts that remain unacknowledged after 15 minutes, the telephony worker places a Twilio call. The TwiML prompt is bilingual (Urdu then English); keypress 1 marks the delivery safe, while keypress 2 also opens a critical aid ticket. Calls are deduplicated per delivery, and the call ledger records provider status and errors.

Agent 4 — Gemini rescue chat. A 24/7 bilingual assistant accepts a session and message history, then calls Gemini with three tools: check_local_flood_risk, find_nearest_open_shelter, and create_emergency_aid_ticket. The tools query active hazard zones and open shelter capacity through PostGIS, or create a critical pending aid request. Without an API key, a deterministic heuristic mode keeps the flow testable.

Hazard SurveillanceActive · default

Reads fresh AI flood zones, verified community reports, and shelter strain. Scores each district and advances a normal → watch → elevated state machine.

Geofenced Signal HandoffActive · default

Sends escalate / stand_down signals to the Go core with an idempotency key. Go performs the polygon audience query and owns alert delivery.

Outbound Voice IVRImplemented · opt-in

Calls unacknowledged critical alerts after 15 minutes with a bilingual TwiML prompt. Keypress 1 marks the household safe; 2 opens a critical aid ticket.

Gemini Rescue ChatImplemented · mounted

A bilingual 24/7 assistant with three tools: local flood risk, nearest open shelter, and emergency aid-ticket creation.

Aid Prioritization + NGO EscalationOpt-in · superseded

The Python implementations remain as reference, but Go’s relief and escalation modules now own ranking and formal escalation.

Evacuation + Route NavigationGo-owned

The orchestrator does not calculate routes. Go navigation consumes active hazard geometry and avoids flooded polygons.

Runtime Invariants
60scycle interval
2 / 3cycles to escalate / stand down
15 minunacknowledged call trigger
30 minpending-signal retry horizon
05 / Key Decisions

Engineering Decisions & Defenses

Every structural choice was selected against specific baselines and hardware trade-offs:

Decision: Sensor Selection: Sentinel-1 SAR over Sentinel-2 Optical
Selected Approach:Sentinel-1 C-band Synthetic Aperture Radar (VV and VH polarizations)
Alternatives Evaluated:Sentinel-2 multispectral MSI, MODIS flood products
Engineering Rationale:

Optical bands exhibit complete data dropouts during heavy monsoon precipitation events due to 100% cloud occlusions. Active C-band radar penetrates cloud cover and precipitation directly, allowing continuous surface water observation.

Decision: Spatial Feature Extractor: ResNet18 over ResNet50 or Vision Transformer
Selected Approach:Pretrained ResNet18 encoder with tailored 6-channel input stem
Alternatives Evaluated:ResNet50, Swin Transformer, SegFormer
Engineering Rationale:

The training runtime was constrained to a single Tesla T4 (16 GB VRAM). ResNet18 fit the spatio-temporal batch dimensions alongside the memory-heavy ConvLSTM hidden states without out-of-memory crashes, while preventing overfitting on limited historical SAR flood pairs.

Decision: Uncertainty Quantification: Monte Carlo Dropout over Deep Ensembles
Selected Approach:Test-time Monte Carlo Dropout (p = 0.2 across 20 forward passes)
Alternatives Evaluated:Deep Ensemble of 5 distinct models, Conformal Prediction
Engineering Rationale:

Training and serving a full deep ensemble of 5 spatiotemporal models was computationally prohibitive on Colab and in latency-sensitive emergency pipelines. MC Dropout provides pixel-level variance and uncertainty bounds with zero additional model storage.

Decision: Action Boundary: Signal Handoff over Duplicate Alert Writes
Selected Approach:Python emits escalate / stand_down signals with an idempotency key; Go owns alerts, deliveries, staff notices, and escalation
Alternatives Evaluated:Write alerts and deliveries directly from the orchestrator; let each service own its own notification path
Engineering Rationale:

Go already owns the alert schema, outbox, retention, and transactional audit. Duplicating those writes in Python would create two sources of truth and two delivery paths. A signal contract keeps the orchestrator a decision service, and the idempotency key makes retries safe without double-alerting.

Decision: Risk Trigger: Edge-Triggered State Machine over Threshold Alerts
Selected Approach:Elevate after 2 consecutive cycles above 0.70; stand down after 3 below 0.60
Alternatives Evaluated:Alert on every prediction above a fixed threshold; alert on every model refresh
Engineering Rationale:

Raw threshold alerts are noisy: a single cloudy SAR tile or one optimistic prediction can page an entire district. Confirmation streaks and hysteresis suppress single-spike alerts, while edge-triggered signals prevent repeated pages for a district that is already elevated. The trade-off is a small detection delay, which is acceptable against alert fatigue and duplicate dispatch.

Decision: Runtime Split: Python for Agentic Intelligence, Go for Operational Writes
Selected Approach:FastAPI/Python orchestrator for PostGIS analytics, Gemini, Twilio, and decision state; Go core for auth, alerting, escalation, and routing
Alternatives Evaluated:Fold the orchestrator into the Go monolith; let the Python service own the full response workflow
Engineering Rationale:

The AI and agent tooling ecosystem is strongest in Python, while the operational core needs Go’s transactional guarantees, auth middleware, and existing alert/outbox code. The split keeps each runtime close to its strengths and forces an explicit contract at the boundary.

06 / Evaluation

Empirical Evaluation & Error Analysis

The model was evaluated against an independent, held-out spatial test set consisting of 19,964 samples across diverse regional terrain throughout Pakistan. These ML metrics are unchanged; the agentic layer is evaluated separately on reliability and control behavior.

MetricScoreTarget / Meaning
Recall (Sensitivity)0.8435 (84.5%)Primary life-safety metric: minimizes false negatives to avoid missing flooded settlements or evacuation corridors
Intersection over Union (IoU)0.6496Secondary spatial metric: pixel-level spatial overlap ensuring boundary tightness without over-segmentation
Dice / F1-Score0.7876Harmonic mean of spatial precision and recall across water bodies
Precision0.7642Fraction of predicted water pixels that were actual flood water
Evaluated on held-out test split of 19,964 raster tiles across the Indus basin.
Auditor Rationale · Asymmetric Cost Function in Flood Informatics

In life-critical disaster mitigation, false negatives (unpredicted flood waters reaching inhabited communities) directly endanger human life and critical infrastructure. Hence, maximizing Recall (0.8435 / 84.5%) is the primary operational mandate. IoU (0.6496) is tracked as the secondary guardrail to ensure spatial delineation fidelity without inducing catastrophic miss rates.

Error Analysis & Known Failure Modes:

1. Specular Reflection in Arid Sandy Basins: Very dry, flat sandy soil occasionally produces very low radar backscatter resembling open, calm water, causing localized false positive predictions.

2. Dense Urban Flooding: Double-bounce radar reflections from flooded building walls create intense bright backscatter rather than dark specular reflection, occasionally leading to false negatives in narrow city streets.

Agentic Reliability Evaluation

The orchestrator suite verifies state-machine edges and hysteresis, signal idempotency, retry / pending / stale paths, worker isolation, all three chat tools, TwiML / DTMF behavior, and admin authorization. External services are mocked by default; an opt-in PostGIS test exercises the real schema inside a rolled-back transaction.

Production telemetry for alert delivery latency, IVR answer rate, and false-alert rate is the next measurement layer.

07 / Cost & Latency

Compute Cost & Latency Profile

Inference Latency~420 ms / tileForward pass on Tesla T4 (batch size 1, 512×512 input)
Training ComputeGoogle Colab (Tesla T4)Mixed-precision training (FP16), AdamW optimizer, Cosine Annealing
Orchestrator Cadence60s / cycleRedis-locked FastAPI cycle; no GPU required for the decision layer
Signal Delivery3 attempts0.5s / 1.5s backoff; pending retries capped at 30 minutes

The expensive inference remains the satellite model. The orchestrator adds a lightweight control loop: spatial reads, risk scoring, and small JSON signal calls to Go.

08 / Deployment

Deployment Status & Runtime Boundaries

Honest deployment status: The ML core is an offline research pipeline and evaluation harness. It is not deployed as an autonomous real-time public early warning service due to satellite orbit revisit latency (Sentinel-1 operates on a 6 to 12-day revisit interval per orbit path).

LittleLife’s orchestrator is the runtime bridge. It runs as a FastAPI service, starts one cycle immediately, then repeats every 60 seconds, and sends boundary signals to Go. The default configuration enables hazard surveillance and signal handoff. Voice IVR and Gemini chat are implemented; aid prioritization and NGO escalation remain opt-in while their schema assumptions are reconciled with Go-owned migrations. Evacuation and route navigation stay entirely in Go.

ComponentCurrent State
Satellite ML coreResearch pipeline; offline evaluation; 420 ms / tile on T4
Surveillance + signal handoffActive by default; 60-second Redis-locked cycle
Twilio IVR + Gemini chatImplemented; production hardening and webhook validation next
Aid prioritizer + NGO escalationOpt-in; Go relief and escalation modules now own these paths
Evacuation + routingGo-owned; consumes active hazard geometry

The deliberate constraint is that Python never writes alerts or delivery rows. Go remains the single transactional owner, which keeps retries idempotent and avoids two competing notification paths.

09 / Retrospective

What Failed, What Is Unfinished & Next Steps

What Failed:

Initial experiments attempting to train a 3D-CNN directly on multi-temporal raw SAR stacks suffered from severe overfitting due to spatial speckle and temporal sparsity across orbits. Moving to a decoupled ResNet18 spatial feature extractor + ConvLSTM stabilized gradient propagation.

Agentic Orchestration Lessons:

  • Schema ownership is architecture. Workers written against columns that do not exist in the Go-owned database stay opt-in until the migration contract is reconciled.
  • Idempotency and retries are mandatory for life-safety signals; every alert boundary crossing needs a stable key.
  • Edge-triggered state beats raw threshold alerts. Confirmation streaks and hysteresis are what keep an alert stream usable.
  • Observability belongs in the data model. The decision-run audit record captures scores, signals, outcomes, timings, and worker errors in one place.

What I Would Do Next:

  • Integrate hydrological river routing physics (e.g. 1D Saint-Venant equations) as physics-informed neural loss terms.
  • Incorporate daily optical MODIS data via cross-modal knowledge distillation to bridge the SAR revisit time gap.
  • Package the inference worker into a containerized AWS Lambda or ECS task triggered by Copernicus S3 notifications.
  • Measure production alert delivery latency, IVR answer rate, and false-alert rate; turn the static metrics endpoint into real orchestration telemetry.
  • Wire Twilio signature validation and rate limiting before exposing citizen webhooks publicly.