File size: 6,573 Bytes
5a3b83f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import json
import dash
from dash import html, dcc, callback, Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objects as go

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from model_loader import detect_anomaly, get_metadata

dash.register_page(__name__, path="/engine", name="Anomaly Engine")

META = get_metadata()
FEATURES = META["feature_columns"]
FMIN = META["feature_min"]
FMAX = META["feature_max"]

UNITS = {"coolant_temp": "C", "manifold_pressure": "kPa", "rpm": "RPM", "speed": "km/h",
         "intake_temp": "C", "mass_air_flow": "g/s", "throttle_pos": "%",
         "ambient_temp": "C", "accel_pedal": "%"}

# Presets are derived from real data and verified against the loaded model
# (see the diagnostics in the final-model workflow). Healthy passes; the two
# fault presets genuinely cross the threshold.
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "presets.json")) as _f:
    _PRESETS = json.load(_f)

HEALTHY_PRESET = _PRESETS["healthy"]
COOLANT_FAULT_PRESET = _PRESETS["coolant"]
INTAKE_FAULT_PRESET = _PRESETS["intake"]

DARK = dict(paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
            font=dict(color="#cfcfcf"), margin=dict(l=20, r=20, t=30, b=20))


def slider_row(feature, idx):
    lo, hi = FMIN[idx], FMAX[idx]
    step = max(round((hi - lo) / 100, 2), 0.1)
    return html.Div([
        html.Div([
            html.Label(feature, className="text-white fw-bold"),
            html.Span(id=f"val-{feature}", className="text-info float-end"),
        ]),
        dcc.Slider(
            id=f"slider-{feature}", min=lo, max=hi, step=step,
            value=HEALTHY_PRESET[feature],
            marks={lo: f"{lo:.0f}", hi: f"{hi:.0f}"},
            tooltip={"placement": "bottom", "always_visible": False},
            className="sensor-slider",
        ),
        html.Small(UNITS[feature], className="text-muted"),
    ], className="mb-3")


layout = html.Div([
    html.Div([
        html.H1("Anomaly Engine", className="text-white fw-bold mb-2"),
        html.P("Adjust the engine sensors and watch the autoencoder judge whether the reading "
               "fits healthy driving.", className="lead text-info"),
    ], className="mb-4"),

    dbc.Row([
        dbc.Col([
            dbc.Card(dbc.CardBody([
                html.Div([
                    html.H4("Sensor inputs", className="text-white mb-0 d-inline"),
                    html.Div([
                        dbc.Button("Healthy", id="preset-healthy", size="sm",
                                   color="success", outline=True, className="me-1"),
                        dbc.Button("Coolant fault", id="preset-coolant", size="sm",
                                   color="danger", outline=True, className="me-1"),
                        dbc.Button("Intake fault", id="preset-intake", size="sm",
                                   color="danger", outline=True),
                    ], className="float-end"),
                ], className="mb-4"),
                html.Div([slider_row(f, i) for i, f in enumerate(FEATURES)]),
            ]), className="modern-card"),
        ], md=6, className="mb-4"),

        dbc.Col([
            dbc.Card(dbc.CardBody([
                html.H4("Verdict", className="text-white mb-3"),
                html.Div(id="verdict-status", className="text-center mb-3"),
                html.Div(id="verdict-gauge"),
                html.Hr(style={"borderColor": "rgba(255,255,255,0.1)"}),
                html.H6("Sensors contributing most to the error", className="text-white mb-2"),
                html.Div(id="verdict-sensors"),
            ]), className="modern-card"),
        ], md=6, className="mb-4"),
    ]),
])


@callback(
    [Output(f"slider-{f}", "value") for f in FEATURES],
    [Input("preset-healthy", "n_clicks"),
     Input("preset-coolant", "n_clicks"),
     Input("preset-intake", "n_clicks")],
    prevent_initial_call=True,
)
def apply_preset(h, c, i):
    trig = dash.callback_context.triggered[0]["prop_id"]
    if "coolant" in trig:
        preset = COOLANT_FAULT_PRESET
    elif "intake" in trig:
        preset = INTAKE_FAULT_PRESET
    else:
        preset = HEALTHY_PRESET
    return [preset[f] for f in FEATURES]


@callback(
    [Output(f"val-{f}", "children") for f in FEATURES],
    [Input(f"slider-{f}", "value") for f in FEATURES],
)
def show_values(*values):
    return [f"{v:.1f} {UNITS[f]}" for f, v in zip(FEATURES, values)]


@callback(
    [Output("verdict-status", "children"),
     Output("verdict-gauge", "children"),
     Output("verdict-sensors", "children")],
    [Input(f"slider-{f}", "value") for f in FEATURES],
)
def run_detection(*values):
    reading = {f: v for f, v in zip(FEATURES, values)}
    result = detect_anomaly(reading)

    if result["is_anomaly"]:
        status = html.Div([
            html.I(className="bi bi-exclamation-triangle-fill fs-1 status-anomaly"),
            html.H2("ANOMALY", className="status-anomaly fw-bold mt-2"),
            html.P(f"{result['ratio']:.1f}x above threshold", className="text-muted"),
        ])
        bar_color = "#e24b4a"
    else:
        status = html.Div([
            html.I(className="bi bi-check-circle-fill fs-1 status-normal"),
            html.H2("HEALTHY", className="status-normal fw-bold mt-2"),
            html.P(f"{result['ratio']:.0%} of threshold", className="text-muted"),
        ])
        bar_color = "#2fe0a5"

    gauge = go.Figure(go.Indicator(
        mode="gauge+number",
        value=result["score"],
        number={"valueformat": ".4f", "font": {"color": "#fff"}},
        gauge={
            "axis": {"range": [0, max(result["threshold"] * 3, result["score"] * 1.2)],
                     "tickcolor": "#888"},
            "bar": {"color": bar_color},
            "threshold": {"line": {"color": "red", "width": 3},
                          "value": result["threshold"]},
            "bgcolor": "rgba(0,0,0,0)",
        },
    ))
    gauge.update_layout(height=220, **DARK)

    sensors = html.Div([
        html.Div([
            html.Span(s["sensor"], className="text-light"),
            html.Span(f"{s['error']:.4f}", className="text-info float-end"),
            dbc.Progress(value=min(s["error"] / max(result["top_sensors"][0]["error"], 1e-6) * 100, 100),
                         color="info", className="mb-2", style={"height": "6px"}),
        ]) for s in result["top_sensors"]
    ])

    return status, dcc.Graph(figure=gauge, config={"displayModeBar": False}), sensors