File size: 13,943 Bytes
4e21335
 
 
 
 
 
 
 
 
 
 
f110a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e21335
 
d074242
 
 
4e21335
 
 
f110a8c
28e23b5
 
 
4e21335
 
 
 
 
 
 
f110a8c
4e21335
 
 
 
d074242
 
 
 
 
 
 
 
 
f110a8c
d074242
 
 
 
4e21335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f110a8c
 
 
 
 
 
 
 
 
 
4e21335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f110a8c
 
 
 
 
 
 
 
 
4e21335
 
 
 
 
 
 
 
 
 
 
d074242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f110a8c
 
 
 
 
 
 
 
 
d074242
 
 
 
 
4e21335
 
 
 
 
 
 
 
 
d074242
4e21335
d074242
 
 
 
 
 
4e21335
 
f110a8c
4e21335
 
f110a8c
 
4e21335
 
 
 
 
 
 
 
 
 
 
 
 
f110a8c
d074242
 
 
4e21335
 
 
 
 
d074242
 
 
 
 
 
 
4e21335
 
 
 
 
 
 
7586faf
 
 
4e21335
7586faf
4e21335
f110a8c
 
 
 
 
 
7586faf
f110a8c
 
 
 
 
4e21335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f110a8c
 
4e21335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d074242
f110a8c
d074242
 
 
4e21335
 
 
 
 
d074242
 
 
 
 
 
 
4e21335
7586faf
 
 
 
 
 
f110a8c
 
 
 
 
7586faf
f110a8c
 
 
 
 
4e21335
 
 
 
 
 
 
 
 
 
 
 
 
d3d1d01
 
 
 
 
 
 
4e21335
f110a8c
4e21335
 
 
d3d1d01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e21335
 
 
 
d3d1d01
f110a8c
 
 
 
 
 
 
 
4e21335
 
 
 
 
 
 
 
 
 
 
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
"""Plotting utilities using Plotly for the Gradio app."""

from __future__ import annotations

from typing import Iterable, Optional, Sequence

import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

_BASE_COLORS = [
    "#1f77b4",
    "#ff7f0e",
    "#2ca02c",
    "#d62728",
    "#9467bd",
    "#8c564b",
    "#e377c2",
    "#7f7f7f",
    "#bcbd22",
    "#17becf",
    "#aec7e8",
    "#ffbb78",
    "#98df8a",
    "#ff9896",
    "#c5b0d5",
]

# Neutral alternating grays for CPD predictions (no state semantics)
_CPD_GRAYS = ["#555555", "#aaaaaa"]


def _adjust_color_hex(hex_color: str, factor: float) -> str:
    hex_color = hex_color.lstrip("#")
    r, g, b = (int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
    r = min(255, max(0, int(r + (255 - r) * factor)))
    g = min(255, max(0, int(g + (255 - g) * factor)))
    b = min(255, max(0, int(b + (255 - b) * factor)))
    return f"#{r:02x}{g:02x}{b:02x}"


def build_segment_color_map(n_segments: int, n_dims: int) -> list[list[str]]:
    colors = []
    for idx in range(n_segments):
        base = _BASE_COLORS[idx % len(_BASE_COLORS)]
        segment_colors = [_adjust_color_hex(base, min(0.15 * dim, 0.85)) for dim in range(n_dims)]
        colors.append(segment_colors)
    return colors


def build_cpd_color_map(n_segments: int, n_dims: int) -> list[list[str]]:
    """Build an alternating neutral-gray color map for CPD predictions.

    Uses two distinguishable gray shades that alternate across segments,
    avoiding any implication of state identity.
    """
    colors = []
    for idx in range(n_segments):
        base = _CPD_GRAYS[idx % len(_CPD_GRAYS)]
        segment_colors = [_adjust_color_hex(base, min(0.10 * dim, 0.85)) for dim in range(n_dims)]
        colors.append(segment_colors)
    return colors


def _iter_segments(states: Sequence[int]) -> Iterable[tuple[int, int, int]]:
    start = 0
    current = states[0]
    for idx in range(1, len(states)):
        if states[idx] != current:
            yield start, idx, current
            start = idx
            current = states[idx]
    yield start, len(states), current


def make_annotation_figure(
    signal: np.ndarray,
    change_points: Sequence[int],
    states: Sequence[int],
    title: str,
    color_map: list[list[str]],
) -> go.Figure:
    """Build a Plotly figure highlighting segments and change points."""
    n_samples, n_dims = signal.shape
    fig = go.Figure()

    for start, stop, state in _iter_segments(states):
        for dim in range(n_dims):
            color = color_map[state % len(color_map)][dim % len(color_map[state % len(color_map)])]
            fig.add_trace(
                go.Scatter(
                    x=np.arange(start, stop),
                    y=signal[start:stop, dim],
                    mode="lines",
                    line=dict(color=color, width=2),
                    name=f"State {state} Β· Dim {dim}",
                    showlegend=False,
                )
            )

    for cp in change_points:
        fig.add_vline(x=cp, line=dict(color="#333333", width=1, dash="dash"))

    fig.update_layout(
        title=title,
        xaxis_title="Time",
        yaxis_title="Value",
        template="plotly_white",
        height=300 + 30 * n_dims,
        margin=dict(t=40, b=40, l=50, r=20),
    )
    return fig


def make_signal_figure(signal: np.ndarray, title: str = "Signal") -> go.Figure:
    """Simple signal visualization without state coloring."""
    n_samples, n_dims = signal.shape
    fig = go.Figure()
    for dim in range(n_dims):
        fig.add_trace(
            go.Scatter(
                x=np.arange(n_samples),
                y=signal[:, dim],
                mode="lines",
                name=f"Dim {dim}",
                line=dict(color=_BASE_COLORS[dim % len(_BASE_COLORS)], width=1.5),
            )
        )
    fig.update_layout(
        title=title,
        xaxis_title="Time",
        yaxis_title="Value",
        template="plotly_white",
        height=300,
        margin=dict(t=40, b=40, l=50, r=20),
    )
    return fig


def _make_cpd_prediction_figure(
    signal: np.ndarray,
    pred_cps: Sequence[int],
) -> go.Figure:
    """Build a prediction subplot with alternating neutral grays for CPD.

    Does NOT imply state identity β€” only visually marks segment boundaries.
    """
    n_samples, n_dims = signal.shape
    # Build alternating segments from CPs
    boundaries = [0] + sorted(pred_cps) + [n_samples]
    n_segs = len(boundaries) - 1
    cpd_cmap = build_cpd_color_map(n_segs, n_dims)

    fig = go.Figure()
    for seg_idx, (start, stop) in enumerate(zip(boundaries[:-1], boundaries[1:])):
        for dim in range(n_dims):
            color = cpd_cmap[seg_idx % len(cpd_cmap)][dim % len(cpd_cmap[seg_idx % len(cpd_cmap)])]
            fig.add_trace(
                go.Scatter(
                    x=np.arange(start, stop),
                    y=signal[start:stop, dim],
                    mode="lines",
                    line=dict(color=color, width=2),
                    showlegend=False,
                )
            )
    for cp in pred_cps:
        fig.add_vline(x=cp, line=dict(color="#333333", width=1, dash="dash"))
    return fig


def make_comparison_figure(
    signal: np.ndarray,
    truth_states: Optional[Sequence[int]],
    truth_cps: Optional[Sequence[int]],
    pred_states: Optional[Sequence[int]],
    pred_cps: Optional[Sequence[int]],
    color_map: list[list[str]],
    *,
    fallback_states: Optional[Sequence[int]] = None,
    task: str = "change_point_detection",
) -> go.Figure:
    """Two-row figure contrasting ground-truth and predictions.

    For CPD-only algorithms (task='change_point_detection' and no native
    pred_states), the prediction row uses neutral alternating grays to
    avoid implying state identity.
    """
    has_truth = truth_states is not None
    n_rows = 2 if has_truth else 1
    titles = ["Ground Truth", "Prediction"] if has_truth else ["Prediction"]

    fig = make_subplots(
        rows=n_rows,
        cols=1,
        shared_xaxes=True,
        vertical_spacing=0.08,
        subplot_titles=titles,
    )

    if has_truth:
        truth_fig = make_annotation_figure(signal, truth_cps or [], truth_states, "", color_map)
        for trace in truth_fig.data:
            fig.add_trace(trace, row=1, col=1)
        for shape in truth_fig.layout.shapes or []:
            fig.add_shape(shape, row=1, col=1)

    pred_row = 2 if has_truth else 1
    is_cpd = task == "change_point_detection"

    if pred_states is not None and not is_cpd:
        # State Detection: use full state colors
        pred_fig = make_annotation_figure(signal, pred_cps or [], pred_states, "", color_map)
        for trace in pred_fig.data:
            fig.add_trace(trace, row=pred_row, col=1)
        for shape in pred_fig.layout.shapes or []:
            fig.add_shape(shape, row=pred_row, col=1)
    elif pred_cps:
        # CPD or CPD-only: neutral alternating grays
        pred_fig = _make_cpd_prediction_figure(signal, pred_cps)
        for trace in pred_fig.data:
            fig.add_trace(trace, row=pred_row, col=1)
        for shape in pred_fig.layout.shapes or []:
            fig.add_shape(shape, row=pred_row, col=1)
    elif fallback_states is not None:
        pred_fig = make_annotation_figure(signal, pred_cps or [], fallback_states, "", color_map)
        for trace in pred_fig.data:
            fig.add_trace(trace, row=pred_row, col=1)
        for shape in pred_fig.layout.shapes or []:
            fig.add_shape(shape, row=pred_row, col=1)
    else:
        # No predicted change points and no fallback states: render the signal
        # as a single neutral segment so the dimensions don't get distinct
        # state-like colors (which would falsely imply "1 state per channel").
        n_dims = signal.shape[1]
        neutral_cmap = build_cpd_color_map(1, n_dims)
        for dim in range(n_dims):
            fig.add_trace(
                go.Scatter(
                    x=np.arange(signal.shape[0]),
                    y=signal[:, dim],
                    mode="lines",
                    name=f"Dim {dim}",
                    line=dict(color=neutral_cmap[0][dim], width=2),
                    showlegend=False,
                ),
                row=pred_row,
                col=1,
            )

    height = 350 * n_rows
    fig.update_layout(height=height, template="plotly_white", margin=dict(t=50, b=40, l=50, r=20))
    fig.update_yaxes(title_text="Value", row=1, col=1)
    if n_rows > 1:
        fig.update_yaxes(title_text="Value", row=2, col=1)
    fig.update_xaxes(title_text="Time", row=n_rows, col=1)
    return fig


def make_multi_comparison_figure(
    signal: np.ndarray,
    runs: list[dict],
    truth_states: Optional[Sequence[int]] = None,
    truth_cps: Optional[Sequence[int]] = None,
) -> go.Figure:
    """Multi-row figure comparing several algorithm runs.

    Parameters
    ----------
    signal : np.ndarray
        The input signal, shape (n_timestamps, n_dims).
    runs : list of dict
        Each dict has keys: 'name', 'pred_states', 'pred_cps'.
    truth_states, truth_cps : optional ground truth.
    """
    has_truth = truth_states is not None
    n_rows = len(runs) + (1 if has_truth else 0)
    if n_rows == 0:
        return go.Figure()

    n_states_max = 1
    if has_truth:
        n_states_max = max(n_states_max, int(np.max(truth_states)) + 1)
    for run in runs:
        if run.get("pred_states") is not None:
            n_states_max = max(n_states_max, int(np.max(run["pred_states"])) + 1)

    color_map = build_segment_color_map(n_states_max, signal.shape[1])

    titles = []
    if has_truth:
        titles.append("Ground Truth")
    for run in runs:
        titles.append(run["name"])

    fig = make_subplots(
        rows=n_rows,
        cols=1,
        shared_xaxes=True,
        vertical_spacing=0.04,
        subplot_titles=titles,
    )

    row = 1
    if has_truth:
        truth_fig = make_annotation_figure(signal, truth_cps or [], truth_states, "", color_map)
        for trace in truth_fig.data:
            fig.add_trace(trace, row=row, col=1)
        for shape in truth_fig.layout.shapes or []:
            fig.add_shape(shape, row=row, col=1)
        row += 1

    for run in runs:
        ps = run.get("pred_states")
        pc = run.get("pred_cps", [])
        run_task = run.get("task", "change_point_detection")
        is_sd = run_task == "state_detection"

        if ps is not None and is_sd:
            # State Detection run: use full state colors
            run_fig = make_annotation_figure(signal, pc, ps, "", color_map)
            for trace in run_fig.data:
                fig.add_trace(trace, row=row, col=1)
            for shape in run_fig.layout.shapes or []:
                fig.add_shape(shape, row=row, col=1)
        elif pc:
            # CPD run: neutral alternating grays
            run_fig = _make_cpd_prediction_figure(signal, pc)
            for trace in run_fig.data:
                fig.add_trace(trace, row=row, col=1)
            for shape in run_fig.layout.shapes or []:
                fig.add_shape(shape, row=row, col=1)
        else:
            # No predicted change points: render the signal as a single
            # neutral segment to avoid implying that each dimension is a
            # distinct state.
            n_dims = signal.shape[1]
            neutral_cmap = build_cpd_color_map(1, n_dims)
            for dim in range(n_dims):
                fig.add_trace(
                    go.Scatter(
                        x=np.arange(signal.shape[0]),
                        y=signal[:, dim],
                        mode="lines",
                        line=dict(color=neutral_cmap[0][dim], width=2),
                        showlegend=False,
                    ),
                    row=row,
                    col=1,
                )
        row += 1

    fig.update_layout(
        height=max(250 * n_rows, 400),
        template="plotly_white",
        margin=dict(t=50, b=40, l=50, r=20),
        showlegend=False,
    )
    fig.update_xaxes(title_text="Time", row=n_rows, col=1)
    return fig


def make_metrics_bar_chart(scores_df) -> go.Figure:
    """Bar chart comparing metric scores across algorithms.

    Colors are grouped semantically:
    - F1-related metrics β†’ blue palette
    - Covering metrics β†’ green palette
    - State detection metrics β†’ purple/orange palette
    """
    import pandas as pd

    if not isinstance(scores_df, pd.DataFrame) or scores_df.empty:
        return go.Figure()

    # Semantic color mapping for metrics
    _METRIC_COLORS = {
        # F1-related β†’ blues
        "F1 Score": "#1f77b4",
        "F1 Score (precision)": "#4a9ecf",
        "F1 Score (recall)": "#7ec4e8",
        # Covering β†’ greens
        "Covering": "#2ca02c",
        "Bidirectional Covering": "#5cc85c",
        # State metrics β†’ warm tones
        "Adjusted Rand Index": "#d62728",
        "Normalized Mutual Information": "#e87d2e",
        "Adjusted Mutual Information": "#f0a050",
        "Weighted ARI": "#9467bd",
        "Weighted NMI": "#b694d4",
        "State Matching Score": "#8c564b",
    }

    fig = go.Figure()
    metric_cols = [c for c in scores_df.columns if c != "Algorithm"]

    for i, metric in enumerate(metric_cols):
        color = _METRIC_COLORS.get(metric, _BASE_COLORS[i % len(_BASE_COLORS)])
        fig.add_trace(
            go.Bar(
                x=scores_df["Algorithm"],
                y=scores_df[metric],
                name=metric,
                marker_color=color,
            )
        )

    fig.update_layout(
        barmode="group",
        title="Metric Scores Comparison",
        xaxis_title="Algorithm",
        yaxis_title="Score",
        template="plotly_white",
        height=400,
        margin=dict(t=50, b=40, l=50, r=20),
    )
    return fig