<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arun on Medium]]></title>
        <description><![CDATA[Stories by Arun on Medium]]></description>
        <link>https://medium.com/@arunram.in?source=rss-37b1abfd1f23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zd4dWgDt7rjYwYtOtTrIIQ.jpeg</url>
            <title>Stories by Arun on Medium</title>
            <link>https://medium.com/@arunram.in?source=rss-37b1abfd1f23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:29:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arunram.in/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Hesitation Into Autonomous Driving: The Code Behind “Hesitate or Commit”]]></title>
            <link>https://medium.com/@arunram.in/i-built-a-framework-that-teaches-autonomous-cars-to-hesitate-heres-why-that-matters-c0dd01827ed0?source=rss-37b1abfd1f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0dd01827ed0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[autonomous-driving]]></category>
            <dc:creator><![CDATA[Arun]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 02:55:10 GMT</pubDate>
            <atom:updated>2026-06-21T22:42:01.450Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A walkthrough of the actual implementation : ambiguity fusion, the state machine, HQM, and the experiments that validated it.</em></p><p>Updated : This article now covers the implementation in code rather than the conceptual overview. If you read the original narrative version, this is a different piece covering how it’s built.</p><p>My <a href="https://claude.ai/chat/4bd513a9-f3dd-4202-94e0-dc8b35335970#">first article</a> on this project covered the concept: hesitation as a measurable, optimizable decision primitive rather than a failure mode. This one is for people who want to see how it’s actually built. I’m walking through the real code from the framework, the same scripts that produced every number in the paper.</p><p>GitHub: <a href="https://github.com/Arun-K-Ram/hesitation-av">github.com/Arun-K-Ram/hesitation-av</a></p><h3>The ambiguity signal</h3><p>Everything starts with a single number per frame: A(t), scene ambiguity between 0 and 1. It’s a weighted sum of two components : perceptual ambiguity (how confident is detection) and behavioral ambiguity (how unpredictable is the agent’s motion).</p><p>The synthetic scenario generators used in Phase 1 experiments construct characteristic A(t) trajectories per scenario class. Here’s the pedestrian_curb generator, which produces rising ambiguity with superimposed oscillation:</p><pre>def scenario_pedestrian_curb(n_frames, dt, rng):<br>    t = np.arange(n_frames) * dt<br>    rise        = np.clip((t - 0.8) / 1.0, 0, 1)<br>    oscillation = 0.10 * np.sin(2 * np.pi * t * 2.1) * \<br>                  np.clip((t - 0.8) / 0.5, 0, 1)<br>    decay = np.clip(1.0 - (t - 2.8) / 0.8, 0, 1)<br>    A = np.clip(0.58 * rise * decay + oscillation<br>                + rng.normal(0, 0.018, n_frames), 0, 1)<br>    risk = np.clip(<br>        0.62 * np.exp(-((t - 1.5)**2) / 0.35)<br>        + 0.08 * np.clip(1.0 - (t - 3.0) / 1.5, 0, 1)<br>        + rng.normal(0, 0.012, n_frames), 0, 1)<br>    cfg_sm = load_config()[&quot;state_machine&quot;]<br>    greedy_mask = (t &gt; 1.2) &amp; (A &lt; cfg_sm[&quot;tau_low&quot;])<br>    t_greedy = float(t[greedy_mask][0]) if greedy_mask.any() \<br>               else float(t[-1])<br>    return {&quot;t&quot;: t, &quot;A&quot;: A, &quot;risk&quot;: risk,<br>            &quot;t_greedy&quot;: t_greedy, &quot;name&quot;: &quot;pedestrian_curb&quot;}</pre><p>The shape matters here, not just the numbers. Ambiguity rises, oscillates for a bit (the pedestrian shifting weight, glancing at traffic), then decays as intent resolves. The t_greedy field precomputes when a naive threshold policy would commit : this becomes the baseline every other policy gets compared against.</p><p>In production, A(t) isn’t synthetic : it comes from real YOLOv11n confidence scores over a sliding window:</p><pre>A_p(t) = λ · mean(1 − c_τ) + (1 − λ) · 4 · std(c_τ)</pre><p>The mean term (aleatoric) catches consistently low confidence. The std term (epistemic) catches frame-to-frame oscillation : a detector that flickers between 0.4 and 0.8 confidence is telling you something different than one that’s steadily at 0.6. Both signals matter and they’re not redundant.</p><h3>The guard that does the real work</h3><p>The state machine has eight transition guards, but G3 : the “earned commit” condition : is the one that actually encodes the framework’s core idea. Here it is as used in the experiment scripts:</p><pre>def g3_check(A, dA_dt, osc, risk, t_in_state):<br>    return (<br>        A &lt; tau_l * (1 - h) and<br>        dA_dt &lt; 0 and<br>        osc &lt; sigma_s and<br>        risk &lt; rho_c and<br>        t_in_state &gt;= t_min<br>    )</pre><p>Five conditions, all required simultaneously. Ambiguity has to be below threshold, decreasing, stable (low recent variance), paired with acceptable risk, and the system has to have been probing for a minimum duration. Compare this to a naive policy that just checks A(t) &lt; tau_l : that commits the instant ambiguity dips, even if it&#39;s about to spike back up.</p><p>The derivative and variance terms are computed over a 30-frame window inline in the simulation loop:</p><pre>window_start = max(0, i - 30)<br>osc      = float(np.var(A_arr[window_start:i+1]))<br>dR_dt    = 0.0 if i == 0 else \<br>           (risk_arr[i] - risk_arr[i-1]) / dt<br>risk_proj = float(np.clip(risk + dR_dt, 0, 1))</pre><p>dA_dt itself uses a centered finite difference for interior points and a one-sided difference at the boundaries : nothing exotic, but it matters for not introducing lag into a signal that&#39;s already noisy.</p><h3>Running six policies against the same scenario</h3><p>The ablation study compares hesitation against five baselines: greedy, fixed delay, random delay, risk-threshold, and TTC-only. Each policy runner shares the same scenario data so the comparison is apples-to-apples. Here’s the greedy baseline : deliberately simple, since it’s the floor everything else has to beat:</p><pre>def run_greedy_policy(scenario, trial):<br>    t_arr    = scenario[&quot;t&quot;]<br>    A_arr    = scenario[&quot;A&quot;]<br>    risk_arr = scenario[&quot;risk&quot;]<br>    cfg_sm   = load_config()[&quot;state_machine&quot;]<br>    <br>    commit_mask = A_arr &lt; cfg_sm[&quot;tau_low&quot;]<br>    if commit_mask.any():<br>        commit_idx  = int(np.argmax(commit_mask))<br>        commit_risk = float(risk_arr[commit_idx])<br>    else:<br>        commit_idx  = len(t_arr) - 1<br>        commit_risk = float(risk_arr[-1])<br>    unsafe_count = 1 if commit_risk &gt; \<br>                   cfg_sm[&quot;rho_commit&quot;] else 0<br>    greedy_hqm   = HQMComputer().greedy_baseline_hqm<br>    return TrialResult(<br>        scenario=scenario[&quot;name&quot;],<br>        policy=&quot;greedy&quot;, trial=trial,<br>        hqm=round(greedy_hqm, 4),<br>        S=0.0, E=1.0, B=1.0, R=1.0,<br>        unsafe_commits=unsafe_count,<br>        decision_latency_ms=0.0,<br>        resolution=&quot;GREEDY_COMMIT&quot;,<br>        n_transitions=0,<br>    )</pre><p>np.argmax on a boolean mask gives you the first True index : that&#39;s the first frame ambiguity dips below threshold, period, no matter what happens after.</p><p>The hesitation policy runner is heavier because it actually ticks the full state machine frame by frame and feeds HQM computation as it goes:</p><pre>def run_hesitation_policy(scenario, trial):<br>    t_arr, A_arr, risk_arr = scenario[&quot;t&quot;], scenario[&quot;A&quot;], scenario[&quot;risk&quot;]<br>    dt = float(t_arr[1] - t_arr[0])<br>    <br>    machine      = HesitationStateMachine()<br>    hqm_computer = HQMComputer()<br>    prev_state   = State.CRUISE<br>    for i, (t, A, risk) in enumerate(zip(t_arr, A_arr, risk_arr)):<br>        dA_dt = 0.0 if i == 0 else \<br>            (A_arr[i] - A_arr[i-1]) / dt if i == len(A_arr)-1 else \<br>            (A_arr[i+1] - A_arr[i-1]) / (2*dt)<br>        window_start = max(0, i - 30)<br>        osc = float(np.var(A_arr[window_start:i+1]))<br>        inp = MachineInput(t=t, A=A, dA_dt=dA_dt, osc=osc, risk=risk, ...)<br>        out = machine.tick(inp)<br>        if prev_state != State.PROBE and out.state == State.PROBE:<br>            hqm_computer.on_probe_enter(t, greedy_risk_estimate)<br>        if out.transition_fired:<br>            hqm_computer.on_transition(out.transition_fired, t, risk)<br>        prev_state = out.state<br>    episodes = hqm_computer.completed_episodes<br>    return episodes[-1] if episodes else hqm_computer.greedy_baseline_hqm</pre><p>Running this across 30 trials × 3 scenarios × 6 policies gave 540 trials, and that’s where the headline result came from: hesitation is the only policy that beats greedy in every scenario class, while naive delay (fixed or random) consistently scores <em>below</em> greedy. Waiting blindly isn’t hesitation : it’s just latency with extra steps.</p><h3>HQM: turning a trajectory into one number</h3><p>The Hesitation Quality Metric needed to answer one question per episode: did the system commit at the right time? Here’s the core computation that runs at counterfactual commit time, used both in live evaluation and in the offset-shifting analysis:</p><pre>def compute_hqm_at_commit(scenario, t_commit, fps=30.0):<br>    t_arr, A_arr, risk_arr = scenario[&quot;t&quot;], scenario[&quot;A&quot;], scenario[&quot;risk&quot;]<br>    t_greedy = scenario[&quot;t_greedy&quot;]<br><br>    commit_idx = min(int(np.searchsorted(t_arr, t_commit)), len(t_arr) - 1)<br>        risk_at_commit = float(risk_arr[commit_idx])<br>        greedy_idx = min(int(np.searchsorted(t_arr, t_greedy)), len(risk_arr) - 1)<br>        risk_at_greedy = float(risk_arr[greedy_idx])<br>        S = float(np.clip(risk_at_greedy - risk_at_commit, -1.0, 1.0))<br>        # Find when G3 first becomes eligible<br>        t_g3_eligible = None<br>        for i in range(len(t_arr)):<br>            ...<br>            if g3_check(A_arr[i], dA_dt, osc, risk_arr[i], t_arr[i]):<br>                t_g3_eligible = t_arr[i]<br>                break<br>        T_actual    = t_commit - t_arr[0]<br>        T_necessary = max(0.0, (t_g3_eligible - t_arr[0]) if t_g3_eligible else T_actual)<br>        excess      = max(0.0, T_actual - T_necessary)<br>        E = float(np.exp(-excess / T_budget))<br>        osc_mean = float(np.var(A_arr[:commit_idx+1]))<br>        B = float(np.clip(1.0 - osc_mean * 10.0, 0.0, 1.0))<br>        R = 1.0 if (t_g3_eligible and t_commit &gt;= t_g3_eligible) else 0.5<br>        HQM = alpha_s*S + beta_e*E + gamma_b*B + delta_r*R<br>        return {&quot;hqm&quot;: round(HQM, 4), &quot;S&quot;: S, &quot;E&quot;: E, &quot;B&quot;: B, &quot;R&quot;: R}</pre><p>The interesting design choice is in E: it doesn’t penalize <em>all</em> waiting, only waiting <em>beyond</em> the point where G3 first becomes eligible. A system that commits the instant it’s earned the right to gets E=1.0. A system that hesitates past that point starts losing efficiency points exponentially. This is what lets the framework distinguish “patient” from “indecisive.”</p><p>This same function powers the counterfactual analysis : shift the actual commit time by an offset and recompute HQM to see what would have happened if the system had committed earlier or later:</p><pre>OFFSETS = [-2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]<br><br>for offset in OFFSETS:<br>    t_cf = t_actual_commit + offset<br>    hqm_dict = compute_hqm_at_commit(scenario, t_cf, fps)</pre><p>This produced the asymmetry result : committing 1.5 seconds early costs more (ΔHQM = +0.066) than committing 1.5 seconds late, verified with a Wilcoxon signed-rank test on each symmetric offset pair:</p><pre>stat, p = stats.wilcoxon(early_hqm, late_hqm)</pre><h3>Stress-testing the parameters</h3><p>I didn’t trust the result until I’d tried to break it. The robustness sweep samples 1,000 random parameter configurations and reruns the entire trial set for each:</p><pre>def run_random_param_sweep(n_configs=1000, n_trials=10, seed=42):<br>    base_sm = load_config()[&quot;state_machine&quot;]<br>    rng = np.random.default_rng(seed + 999)<br><br>    param_ranges = {<br>        &quot;tau_low&quot;:      (base_sm[&quot;tau_low&quot;]      * 0.6, base_sm[&quot;tau_low&quot;]      * 1.4),<br>        &quot;tau_high&quot;:     (base_sm[&quot;tau_high&quot;]     * 0.6, base_sm[&quot;tau_high&quot;]     * 1.4),<br>        &quot;rho_commit&quot;:   (base_sm[&quot;rho_commit&quot;]   * 0.6, base_sm[&quot;rho_commit&quot;]   * 1.4),<br>        &quot;sigma_stable&quot;: (base_sm[&quot;sigma_stable&quot;] * 0.6, base_sm[&quot;sigma_stable&quot;] * 1.4),<br>    }<br>    beats_greedy = 0<br>    for config_idx in range(n_configs):<br>        sampled = {k: float(rng.uniform(lo, hi))<br>                   for k, (lo, hi) in param_ranges.items()}<br>        hqm_vals = []<br>        for scenario_fn in SCENARIOS:<br>            for _ in range(n_trials):<br>                hqm_vals.append(run_trial(scenario_fn, rng, dt, n_frames, sampled))<br>        mean_hqm = float(np.mean(hqm_vals))<br>        if mean_hqm &gt; 0.60:<br>            beats_greedy += 1<br>    return beats_greedy / n_configs</pre><p>All four guard parameters perturbed simultaneously, ±40% of baseline, 30,000 total trials. Result: 100% win rate, HQM range 0.642–0.692. That’s the number that convinced me the framework wasn’t an artifact of careful threshold tuning : it works across a wide parameter neighborhood, not just at one lucky point.</p><h3>CARLA: from synthetic curves to a physics simulator</h3><p>Synthetic A(t) curves are useful for isolating the decision logic, but they don’t prove anything about a real perception pipeline. CARLA validation closes that gap : sort of. Here’s how ambiguity gets estimated from raw simulator state, without any camera feed:</p><pre>def estimate_ambiguity_from_world(world, ego, primary_agent):<br>    if primary_agent is None:<br>        return {&quot;A&quot;: 0.1, &quot;Ap&quot;: 0.1, &quot;Ab&quot;: 0.0}<br>        ego_loc   = ego.get_transform().location<br>            agent_loc = primary_agent.get_transform().location<br>            distance  = math.sqrt(<br>                (ego_loc.x - agent_loc.x)**2 +<br>                (ego_loc.y - agent_loc.y)**2<br>            )<br>            visibility = min(1.0, distance / 30.0)<br>            Ap = float(np.clip(1.0 - visibility + np.random.normal(0, 0.05), 0.0, 1.0))<br>            agent_velocity = primary_agent.get_velocity()<br>            speed = math.sqrt(agent_velocity.x**2 + agent_velocity.y**2)<br>            Ab = float(np.clip(1.0 - speed / 5.0, 0.0, 1.0))<br>            cfg = load_config()<br>            A = float(np.clip(cfg[&quot;ambiguity&quot;][&quot;alpha&quot;] * Ap +<br>                               cfg[&quot;ambiguity&quot;][&quot;beta&quot;] * Ab, 0.0, 1.0))<br>            return {&quot;A&quot;: A, &quot;Ap&quot;: Ap, &quot;Ab&quot;: Ab, &quot;distance&quot;: distance, &quot;agent_speed&quot;: speed}&quot;agent_speed&quot;: speed}</pre><p>This is a distance-based proxy, not real detection confidence : and it shows. Phase 2 HQM (0.354 overall) comes in noticeably lower than Phase 1 (0.60+) across every scenario. I call this the ambiguity estimation gap in the paper: the proxy doesn’t generate the oscillating A(t) patterns needed to reliably trigger G1 and G3, so the system spends most of its time in CRUISE rather than actively hesitating. The fix is straightforward : pipe real YOLOv11n confidence from CARLA’s RGB sensor instead of distance : but it’s future work, not done yet.</p><p>What <em>did</em> hold up: zero collisions across all 240 trials, all four weather conditions (ClearNoon, HardRainNoon, SoftRainSunset, ClearNight). Even with a degraded ambiguity signal, the hesitation framework defaulted to CRUISE/HOLD during uncertain periods rather than committing unsafely. That’s the right failure mode : conservative, not reckless.</p><h3>What ties it together</h3><p>None of these pieces are individually exotic : sliding window statistics, a finite state machine, a weighted sum metric, a Monte Carlo parameter sweep. The contribution isn’t algorithmic novelty in any single component. It’s that they compose into a system where “when to act” is treated as a first-class, measurable, optimizable quantity instead of an afterthought bolted onto a perception pipeline.</p><p>If you want to dig into the rest : the MLP that learns adaptive α/β weights, the full CNN training pipeline for scene classification, the React dashboard : it’s all in the repo.</p><p><strong>GitHub:</strong> <a href="https://github.com/Arun-K-Ram/hesitation-av">github.com/Arun-K-Ram/hesitation-av</a></p><p><em>Questions, pushback, or ideas for the camera-integrated CARLA fix : reach out.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0dd01827ed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Silent Killer in Enterprise Operations: How I Built TraceRoot to Catch What No One Sees]]></title>
            <link>https://medium.com/@arunram.in/the-silent-killer-in-enterprise-operations-how-i-built-traceroot-to-catch-what-no-one-sees-f3079d805628?source=rss-37b1abfd1f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3079d805628</guid>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[healthcare-ai]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Arun]]></dc:creator>
            <pubDate>Mon, 25 May 2026 22:51:44 GMT</pubDate>
            <atom:updated>2026-05-26T18:06:56.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Failures in any business system happen out of the blue..they happen unannounced, usually without any alerts. The workflow simply stops quietly..while the business continues operating as if everything is fine. Until it is not.</p><p>A purchase order sits unprocessed for 72 hours because the approver’s account was deactivated three weeks earlier and no one updated the system. A new employee starts their first day without laptop access because a provisioning step silently timed out. A $124,000 order never ships because inventory was marked as reserved in the ERP, but the warehouse never actually moved the stock.</p><p>These are not edge cases. They are everyday realities in enterprise operations. And they are incredibly expensive..not because the failures are complicated, but because no one notices them until the damage has already been done.</p><p>That is the problem TraceRoot is built to solve.</p><p><strong>Why I built this</strong></p><p>I kept coming back to the same observation: enterprise workflows are everywhere.</p><p>Order fulfillment. Employee onboarding. Invoice approvals. Contract reviews. Procurement. Incident resolution. Every company runs dozens of these processes simultaneously across platforms like SAP, Workday, Salesforce, and ServiceNow, and once these workflows begin, keeping track of what is happening in the backend becomes difficult and most become effectively invisible.</p><p>The tools available today only tell you what happened after the fact. You get logs, audit trails, maybe a support ticket saying the customer is angry because the order never arrived. What you do not get is a system that monitors the workflow in real time, understands the chain of dependencies, and tells you the moment something breaks , and why it broke.</p><p>So I built one.</p><p><strong>What TraceRoot actually does?</strong></p><p>TraceRoot is a causal business process automation system. It monitors business workflows in real time, detects failures the moment they occur, reconstructs the chain of events that caused them, and attempts to resolve the issue automatically.</p><p>Most monitoring tools can tell you that a step failed. TraceRoot explains why it failed, what caused it, and which downstream processes are now blocked because of it. There is a major difference between:</p><p>“Inventory Reserved failed.” and “Inventory Reserved failed because the assigned agent account was deactivated, which blocked Shipment Dispatch, Delivery, and Invoice Generation…putting a $124,000 order at risk.”</p><p>The second explanation is what an operations manager actually needs in order to make a decision.</p><p>Not all workflow failures look the same. TraceRoot’s detection engine identifies five structural patterns that account for most silent failures in enterprise systems:</p><p><strong>Inactive Assignee : </strong>the workflow is waiting for someone whose account no longer exists. The process will never continue.</p><p><strong>Unsatisfiable Rule</strong> : the workflow is evaluating a condition that can never be met based on the current data. The process is permanently blocked.</p><p><strong>Lost Confirmation</strong> : the workflow is waiting for an event that was never delivered because of a webhook failure, API timeout, or synchronization issue. No one realizes the event is missing.</p><p><strong>False Completion</strong> : the workflow appears complete, but the expected outcome never actually happened. Everything looks normal on the surface.</p><p><strong>Silent Timeout</strong> : the workflow timed out without generating an error, alert, or visible failure signal.</p><p>Each pattern has its own detection logic, explanation model, and remediation strategy.</p><p>When TraceRoot detects a failure, it does not simply generate a report. It actively attempts to fix the issue. The remediation engine can reroute inventory to a secondary warehouse, escalate approvals to backup personnel, re-trigger missing confirmation events, and execute other recovery actions automatically.</p><p>The system then reports exactly what was attempted, what succeeded, what failed, and why.</p><p><strong>The architecture</strong></p><p>TraceRoot is built in two layers.</p><p>The V1 layer is a Flask backend with a React frontend. It handles the simulation engine . 80 pre-built scenarios across six business domains, each with five failure pattern variants. This is the demo layer. It lets you see TraceRoot’s reasoning across ERP, HR, Finance, Supply Chain, Operations, and Legal workflows without needing to connect a live system.</p><p>The V2 layer is a FastAPI causal engine. This is where the real work happens. It maintains an event bus, reconstructs workflow state from raw events, runs the failure detector, and exposes the remediation engine. V2 is designed to ingest live data from real systems.</p><p>The first live integration is Apache Airflow. When an Airflow task completes or fails, it fires a callback to TraceRoot V2. The adapter converts the Airflow event into a canonical TraceRoot event, publishes it to the event bus, and the causal engine does the rest. The entire loop : task execution to failure detection to diagnosis ….happens in real time.</p><p>The adapter pattern means every future integration follows the same structure. NetSuite, Salesforce, SAP, Propel each one is an adapter that converts that system’s events into TraceRoot’s canonical format. The engine never changes.</p><p><strong>What I learned building this</strong></p><p>The hardest part was not the technical architecture. The hardest part was understanding the difference between observability and monitoring.</p><p>Monitoring tells you something is broken. Observability tells you why it is broken, what it depends on, and what breaks next because of it. That distinction sounds simple but it changes everything about how you design a system.</p><p>A monitoring tool focuses on: is this step healthy? while an observability tool primary focus: given everything that has happened in this workflow up to this point, what is the most likely explanation for the current state, and what are the downstream consequences?</p><p>The second question is much harder to answer. It requires understanding the workflow as a causal graph ..not a list of steps, but a chain of dependencies where every event has a cause and every failure has consequences.</p><p>Building TraceRoot forced me to think in those terms constantly. Every design decision came back to the same question: does this help us understand causality, or does it just tell us something broke?</p><p><strong>The broader problem</strong></p><p>Enterprise workflow failures are quietly expensive in a way that almost never gets measured.</p><p>When a workflow breaks visibly ..a system goes down, an alert fires, an engineer gets paged ..the cost gets attributed. Someone fixes it, it gets logged, lessons get learned.</p><p>When a workflow breaks silently..an assignee is inactive, a webhook drops, a completion is phantom..the cost gets absorbed. The customer waits. The invoice is late. The employee starts without access. Nobody connects it to a specific failure because nobody saw the failure happen.</p><p>Multiply that across dozens of workflows, hundreds of process instances per day, six enterprise platforms, and the number becomes significant very quickly.</p><p>TraceRoot is built on the belief that this is a solvable problem. Not by adding more alerts, not by hiring more operations staff, but by building a system that understands workflows the way a senior engineer understands code..causally, structurally, and in real time.</p><p><strong>What is next</strong></p><p>The Airflow integration is live. The roadmap includes adapters for NetSuite, Salesforce, and SAP, moving TraceRoot from a single-system observer to a cross-system causal layer , one that can trace a failure that starts in Salesforce, propagates through NetSuite, and surfaces in a custom ERP as a delayed shipment.</p><p>The longer term vision is a system that learns from its own history. When TraceRoot sees a failure pattern it has seen before, it should be able to say this looks like the incident from March, which was resolved by switching to the secondary vendor, and that resolution took four hours. That is where the RAG layer comes in, grounding explanations in real historical context rather than pattern matching alone.</p><p>If you are building in the workflow observability space, working on enterprise operations tooling, or just interested in causal reasoning systems. I would genuinely love to connect.</p><p>TraceRoot is open source. The code is on GitHub. The demo runs 80 simulations across six business domains. And as of this week, it ingests real data from Apache Airflow.</p><p>The silent failures are still out there. We are just starting to see them.</p><p><em>TraceRoot: causal workflow observability</em> <em>GitHub: </em><a href="https://github.com/Arun-K-Ram">https://github.com/Arun-K-Ram</a></p><p><em>Demo: </em><a href="https://traceroot-app.vercel.app/">https://traceroot-app.vercel.app/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3079d805628" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hospital monitors go off all day…and most of the alarms don’t actually mean anything.]]></title>
            <link>https://medium.com/@arunram.in/hospital-monitors-go-off-all-day-and-most-of-the-alarms-dont-actually-mean-anything-45bc97e022dd?source=rss-37b1abfd1f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/45bc97e022dd</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[medtech]]></category>
            <dc:creator><![CDATA[Arun]]></dc:creator>
            <pubDate>Mon, 25 May 2026 22:03:48 GMT</pubDate>
            <atom:updated>2026-05-25T23:35:14.939Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a machine learning system to figure out which alarms are worth acting on : and what I learned about signal intelligence along the way.</em></p><p>I’ve been reading about alarm fatigue for a while. It shows up in nursing journals, patient safety reports, FDA adverse event databases. The numbers are consistent enough that they stop feeling abstract after a while.</p><p>According to an article on Nurse.org discussing alarm fatigue, ICU monitors can generate nearly 350 alarms per patient per day, with an estimated 85-99% classified as false positives. Over a three-year period, 80 documented patient deaths were linked to clinicians ignoring alarms that later turned out to represent real clinical events.</p><p>Hospital monitors were built to do one thing: sound an alarm when a reading crosses a threshold. Blood oxygen drops below 90% or the heart rate spikes above 120, the alarm goes off. They’re incredibly good at measuring signals: but they have no sense of whether the reading actually matters or should even be trusted.</p><p>A sensor slips off a patient’s finger. The monitor has no way of knowing that, it just sees a number out of range and sounds the alarm. By the 347th alert of the shift, the nurse has to make a judgment call. Sometimes the real question is whether to ignore it or act on it.</p><p>That’s the gap I wanted to work on..</p><pre>Acronyms Used in This Article<br><br>• ICU - Intensive Care Unit  <br>• AUC - Area Under the Curve  <br>• ROC - Receiver Operating Characteristic  <br>• CWT - Continuous Wavelet Transform  <br>• CNN - Convolutional Neural Network  <br>• LSTM - Long Short-Term Memory  <br>• ECG - Electrocardiogram  <br>• SpO₂ - Peripheral Oxygen Saturation  <br>• SVM - Support Vector Machine  <br>• FDA - Food and Drug Administration  <br>• SaMD - Software as a Medical Device  <br>• Hz - Samples recorded per second  <br>• SNR - Signal-to-Noise Ratio  <br>• Grad-CAM - Gradient-weighted Class Activation Mapping  <br>• EfficientNet - Pretrained CNN architecture used for feature extraction  <br>• XGBoost - Tree-based machine learning model  <br>• PhysioNet - Public repository of medical datasets</pre><h3>The Question Nobody Is Asking</h3><p>Most medical AI systems I came across were focused on one question: <em>What does this signal mean?</em></p><p>Whether it was arrhythmia classification, deterioration prediction, or disease diagnosis, they were all tackling reasonable and important problems. But they shared the same assumption: that the input data could be trusted. The sensor reading was taken at face value, and the reasoning started from there.</p><p>What we really should be asking is: <em>Should we trust this signal at all?</em> And how confident are we in what it’s telling us?</p><p>That distinction matters more than it sounds. Because if the reading itself isn’t reliable, then whether the heart rate is abnormal becomes irrelevant.</p><h3>The Dataset</h3><p>I used the PhysioNet Challenge 2015 dataset, <em>“Reducing False Arrhythmia Alarms in the ICU.”</em> It contains 750 real ICU alarm recordings, each labeled by clinicians as either a true or false alarm. Every record includes four channels: two ECG leads, blood oxygen, and respiration, sampled at 250 Hz over 60 seconds.</p><p>After filtering out recordings with fewer than four usable channels, 498 records remained. The dataset is nearly perfectly balanced, with 251 true alarms and 247 false alarms.</p><h3>Experiment 01 : Teaching a Model to See Signal Patterns</h3><p>Raw ECG signals are just numbers: a sequence of voltages measured over time. They contain structure that’s difficult to see directly, but it becomes much more visible when the signal is transformed into a time-frequency representation using a technique called the Continuous Wavelet Transform (CWT).</p><p>The idea is to convert each 60-second recording into a heatmap, where one axis represents time and the other represents frequency. Bright regions indicate strong signal activity at a particular frequency and moment in time.</p><p>Each of the four channels produces a (64, 64) scalogram. Stacking them together creates a (4, 64, 64) image for each recording, essentially the same shape as a 4-channel image. This is then fed into EfficientNet-B0.</p><pre>from torchvision import models<br>import torch.nn as nn<br><br>def build_efficientnet(n_channels=4):<br>    m    = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)<br>    orig = m.features[0][0]<br>    # Replace first conv to accept 4 channels instead of 3<br>    new  = nn.Conv2d(4, orig.out_channels, orig.kernel_size,<br>                     orig.stride, orig.padding, bias=False)<br>    with torch.no_grad():<br>        new.weight[:, :3] = orig.weight<br>        new.weight[:, 3]  = orig.weight.mean(dim=1)   # init 4th channel<br>    m.features[0][0] = new<br>    return m</pre><p><strong>Result: AUC 0.641.</strong></p><h3>Experiment 02 : Hand-Crafted Features</h3><p>Instead of images, I extracted 103 clinical measurements directly from each signal : noise levels, dominant frequency, cross-channel correlation, signal variance over time. Then trained XGBoost, SVM, and gradient boosting on those features.</p><pre>def extract_features(signal, fs=250):<br>    features = {}<br>    # Signal quality<br>    features[&quot;std&quot;]         = np.std(signal)<br>    features[&quot;snr&quot;]         = estimate_snr(signal)<br>    features[&quot;zero_cross&quot;]  = zero_crossing_rate(signal)<br>    # Frequency domain<br>    freqs, psd              = scipy.signal.welch(signal, fs=fs)<br>    features[&quot;dom_freq&quot;]    = freqs[np.argmax(psd)]<br>    features[&quot;spectral_entropy&quot;] = spectral_entropy(psd)<br>    # ... 98 more features<br>    return features</pre><p><strong>Result: AUC 0.539.</strong> The hand-defined measurements were less informative than the visual patterns EfficientNet discovered on its own.</p><h3>Experiment 03 : Per-Alarm Classifiers</h3><p>Hospitals deal with four main types of alarms, each with a distinct waveform pattern on the monitor. I built a Pan-Tompkins beat detector, extracted morphology features from each heartbeat, and trained a separate XGBoost classifier for each alarm type.</p><p>The best result came from the tachycardia classifier, which achieved an AUC of 0.612. This showed that a one-size-fits-all model was the wrong approach : but that per-alarm classifiers alone still weren’t enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgx-td0GzB4MEwQpVyl5NQ.png" /><figcaption>Figure 1: AUC comparison across all four experiments. Experiments 01-03 used static classification on the full 60-second window. The jump to Experiment 04 reflects what happens when you give the model a sense of time. Random guessing sits at 0.50 for reference.</figcaption></figure><h3>Experiment 04 : The One That Actually Worked</h3><p>This is where things got interesting.</p><p>The first three experiments treated each 60-second window as a static snapshot. The model could see the signal itself, but not how it evolved over time.</p><p>In real cardiac events, changes usually build gradually. The signal often deteriorates over the course of the window leading up to the alarm. In contrast, sensor artifacts tend to appear abruptly : one moment the signal looks normal, and the next the reading is corrupted.</p><p>That temporal structure is invisible to a static classifier.</p><p>To address this, I split each 60-second recording into six consecutive 10-second segments. Each segment was converted into its own scalogram. A shared EfficientNet encoder processed each segment independently, and an LSTM then analyzed the resulting sequence of six feature vectors.</p><pre># Build temporal dataset<br>def build_sequence(sig, n_chunks=6):<br>    &quot;&quot;&quot;<br>    sig shape: (15000, 4)  - 60s × 250Hz × 4 channels<br>    Returns:   (6, 4, 64, 64) - sequence of scalograms<br>    &quot;&quot;&quot;<br>    chunks   = np.array_split(sig, n_chunks, axis=0)<br>    sequence = []<br>    for chunk in chunks:<br>        chunk_scalograms = []<br>        for ch in range(4):<br>            scalo = cwt_scalogram(chunk[:, ch])   # (64, 64)<br>            chunk_scalograms.append(scalo)<br>        sequence.append(np.stack(chunk_scalograms))   # (4, 64, 64)<br>    return np.stack(sequence)   # (6, 4, 64, 64)</pre><p>The model architecture:</p><pre>class TemporalAlarmClassifier(nn.Module):<br>    def __init__(self, feat_dim=1280, lstm_hidden=64,<br>                 lstm_layers=2, dropout=0.3):<br>        super().__init__()<br>        self.encoder = build_efficientnet()<br>        self.lstm = nn.LSTM(<br>            input_size  = feat_dim,<br>            hidden_size = lstm_hidden,<br>            num_layers  = lstm_layers,<br>            batch_first = True,<br>            dropout     = dropout,<br>        )<br>        self.classifier = nn.Sequential(<br>            nn.Linear(lstm_hidden, 64),<br>            nn.ReLU(),<br>            nn.Dropout(dropout),<br>            nn.Linear(64, 2)<br>        )<br>    def forward(self, x):<br>        # x: (batch, 6, 4, 64, 64)<br>        batch, chunks, C, H, W = x.shape<br>        # Encode each chunk with shared EfficientNet<br>        feats = self.encoder(x.view(batch * chunks, C, H, W))<br>        feats = feats.view(batch, chunks, -1)<br>        # LSTM reads the sequence<br>        _, (hn, _) = self.lstm(feats)<br>        return self.classifier(hn[-1])</pre><p><strong>Result: AUC 0.825. </strong>Up from 0.641 in Experiment 01. An 18 percentage point improvement on the same dataset, same signal, same labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eWOmnwLhD54N8x_CH8iEA.png" /><figcaption><em>Figure 2: </em>Validation AUC per epoch for the EfficientNet + LSTM model. The dashed line at 0.641 is the Experiment 01 static baseline. The LSTM crosses it within the first few epochs and keeps climbing. The dotted green line is the final test AUC of 0.825. Early stopping kicks in around epoch 8. Beyond that the model starts memorizing rather than learning.</figcaption></figure><h3>The Hyperparameter Sweep</h3><p>I used a structured one-parameter-at-a-time sweep across all four experiments: 48 training runs in total, with every result logged. The principle was simple: vary one parameter while keeping all others fixed. No random search, no guesswork.</p><pre>HIDDEN_VALUES  = [64, 128, 256, 512]<br>DROPOUT_VALUES = [0.2, 0.3, 0.4, 0.5]<br>LR_VALUES      = [0.01, 0.001, 0.0001, 0.00001]<br><br># Sweep hidden size, hold others fixed<br>for hidden in HIDDEN_VALUES:<br>    auc = train_and_evaluate(<br>        lstm_hidden = hidden,<br>        dropout     = DEFAULT_DROPOUT,   # 0.5<br>        lr          = DEFAULT_LR,        # 1e-4<br>    )<br>    print(f&quot;hidden={hidden}  val_auc={auc:.4f}&quot;)</pre><p>Sweep results for the LSTM:</p><pre>SWEEP 1 - LSTM hidden size<br>  hidden=64    val_auc=0.8137  # winner<br>  hidden=128   val_auc=0.8137<br>  hidden=256   val_auc=0.7974<br>  hidden=512   val_auc=0.7941<br><br>SWEEP 2 - Dropout rate<br>  dropout=0.2  val_auc=0.8235<br>  dropout=0.3  val_auc=0.8407  # winner<br>  dropout=0.4  val_auc=0.7933<br>  dropout=0.5  val_auc=0.8121<br><br>SWEEP 3 - Learning rate<br>  lr=0.01      val_auc=0.5935<br>  lr=0.001     val_auc=0.7974  # winner<br>  lr=0.0001    val_auc=0.7786<br>  lr=0.00001   val_auc=0.6855</pre><p>A few observations stood out. Smaller hidden sizes generalized better: with only 498 usable training records, larger LSTM layers tended to memorize the data before learning meaningful patterns.</p><p>Lower dropout rates also worked better than in the static model, likely because the LSTM’s gating mechanism already provides a form of implicit regularization.</p><p>Finally, the hybrid model benefited from a higher learning rate than EfficientNet alone. The sequence model needs a stronger early gradient signal to learn temporal dependencies before the LSTM gates begin to saturate.</p><p>None of this was obvious going in. The sweep found it.</p><h3>Grad-CAM : What the Model Actually Looked At</h3><p>After training the best static model, I applied Grad-CAM (Gradient-weighted Class Activation Mapping) to visualize which regions of the scalogram had the greatest influence on each prediction.</p><pre>class GradCAM:<br>    def __init__(self, model):<br>        self.gradients   = None<br>        self.activations = None<br>        # Hook into features[4] : more spatial detail than final layer<br>        model.features[4].register_forward_hook(self._save_activation)<br>        model.features[4].register_full_backward_hook(self._save_gradient)<br><br>    def generate(self, tensor, class_idx):<br>        out = self.model.features(tensor)<br>        out = self.model.avgpool(out).flatten(1)<br>        out[0, class_idx].backward()<br>        weights = self.gradients.mean(dim=(2,3), keepdim=True)<br>        cam     = torch.relu((weights * self.activations).sum(dim=1))<br>        cam     = cam.squeeze().cpu().numpy()<br><br>        # Normalize<br>        if cam.max() &gt; 0:<br>            cam = (cam - cam.min()) / (cam.max() - cam.min())<br>        return cam</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZAM6wksgywSdMjgXqipAA.png" /><figcaption><em>Figure 3: </em>Record v101l. A real ventricular flutter alarm. Top row: the raw CWT scalograms across all four signal channels. Each column is a channel (ECG Lead II, ECG Lead V, SpO₂, Respiration). Bright areas mean strong signal activity at that frequency. Bottom row: Grad-CAM overlay. Red areas show where the model placed the most weight when deciding this was a real alarm. Notice the attention is concentrated in the mid-frequency band and in the later time window-consistent with a rhythm disturbance that built up in the seconds before the alarm fired.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGS4AEpJBLpqIRjkim5mUA.png" /><figcaption><em>Figure 4: </em>Record t116s. A false tachycardia alarm. The patient’s heart rate reading was elevated but the alarm was a sensor artifact, not a real event. The Grad-CAM attention here is scattered and diffuse compared to Figure 3. The model correctly called it a false alarm at 69% confidence. The lack of concentrated attention in any specific frequency band or time window is itself a signal. There’s no coherent pattern to focus on because the underlying reading wasn’t reliable</figcaption></figure><p>These aren’t X-ray images, they’re mathematical fingerprints of the heart’s electrical activity. The red regions highlight the time periods and frequency bands that had the greatest influence on the model’s decision.</p><p>In true alarm cases, the model consistently focused on mid-frequency activity near the end of the recording : exactly where a real arrhythmia tends to develop. In contrast, the sensor artifact cases showed scattered attention patterns, consistent with noisy and unreliable signals.</p><h3>What I Actually Learned</h3><p>What stayed with me from this project was what the LSTM result revealed.</p><p>The information needed to tell a real alarm from a false one was always present in the data. It wasn’t hidden but was simply encoded in time.</p><p>Think of it this way…imagine watching a patient’s heart monitor. If you only see the final second before the alarm goes off, it’s difficult to know whether the event is real. But if you watch the entire minute leading up to it, the pattern becomes much clearer. A genuine cardiac event usually develops gradually...the signal becomes increasingly unstable over time. A sensor artifact looks different: the signal appears normal, then suddenly breaks.</p><p>That distinction only becomes visible when you look at how the signal evolves over time. A static classifier sees a single frame. The LSTM watches the entire sequence.</p><p>That’s why it performed better…not because it was a more complex model, but because it was analyzing the right kind of information.</p><p>I think this idea extends far beyond hospital alarms. In many real-world problems, the way something changes over time matters just as much as its current state. Treating a time-based signal like a frozen image can discard some of the most valuable information available.</p><p>In hindsight, that seems obvious. But it usually only feels obvious after you’ve watched the score improve from 0.641 to 0.825.</p><h3>Honest Limitations</h3><p>An AUC of 0.825 is not a deployable system.</p><p>The dataset contains 498 usable records, which is small for training a deep learning model. Results also vary between runs because of random initialization ..that variability is real, and I’ve reported it as such. Clinical deployment would require far more: validation on a much larger dataset, prospective testing in an actual ICU, regulatory approval under FDA AI/ML SaMD guidelines, and patient-specific calibration.</p><p>None of that is in scope here.</p><p>What is in scope is showing the approach, demonstrating that temporal modeling meaningfully outperforms static classification on this problem, and building the infrastructure to push it further.</p><p>The demo at sigmamedstat.vercel.app shows real model predictions on six PhysioNet records, including the worst failure case: where the model was 93% confident and wrong. That kind of transparency is essential in medical AI.</p><h3>What’s Next</h3><p>The obvious next step is patient-specific calibration. A population-level model learns what alarms generally look like. A patient-specific model learns what this patient’s normal looks like and flags deviations from that baseline. That’s a fundamentally different, and more powerful framing.</p><p>The data infrastructure is already in place, and the architecture is already working. The next version builds directly on both.</p><p><em>All code on GitHub: </em><a href="https://github.com/Arun-K-Ram"><em>github.com/Arun-K-Ram</em></a> . <em>Follow along for what’s coming next.</em></p><p><em>Live demo: </em><a href="https://sigmamedstat.vercel.app/"><em>sigmamedstat.vercel.app</em></a></p><p><em>PhysioNet Challenge 2015 dataset: physionet.org/content/challenge-2015</em></p><p><em>SigmaMedStat is a research project. Not FDA cleared. Not for clinical use.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45bc97e022dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>