File size: 23,381 Bytes
4862c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
"""
Plotting functionality for functional metrics.

This module provides comprehensive visualization of metrics from functional_metrics.py,
"""

import json
import pandas as pd
import numpy as np
from pathlib import Path
from typing import Dict, Any, List, Optional
import warnings

import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.io as pio

# Set plotly template
pio.templates.default = "plotly_white"
warnings.filterwarnings('ignore')


def create_model_cluster_dataframe(model_cluster_scores: Dict[str, Any]) -> pd.DataFrame:
    """Convert model-cluster scores to a tidy dataframe."""
    rows = []
    for model, clusters in model_cluster_scores.items():
        for cluster, metrics in clusters.items():
            # Filter out "No properties" clusters
            if cluster == "No properties":
                continue
                
            row = {
                'model': model,
                'cluster': cluster,
                'size': metrics.get('size', 0),
                'proportion': metrics.get('proportion', 0),
                'proportion_delta': metrics.get('proportion_delta', 0)
            }
            
            # Add confidence intervals if available
            if 'proportion_ci' in metrics:
                ci = metrics['proportion_ci']
                row.update({
                    'proportion_ci_lower': ci.get('lower', 0),
                    'proportion_ci_upper': ci.get('upper', 0),
                    'proportion_ci_mean': ci.get('mean', 0)
                })
            
            if 'proportion_delta_ci' in metrics:
                ci = metrics['proportion_delta_ci']
                row.update({
                    'proportion_delta_ci_lower': ci.get('lower', 0),
                    'proportion_delta_ci_upper': ci.get('upper', 0),
                    'proportion_delta_ci_mean': ci.get('mean', 0)
                })
            
            # Add significance flags
            row['proportion_delta_significant'] = metrics.get('proportion_delta_significant', False)
            
            # Add quality metrics
            quality = metrics.get('quality', {})
            quality_delta = metrics.get('quality_delta', {})
            quality_ci = metrics.get('quality_ci', {})
            quality_delta_ci = metrics.get('quality_delta_ci', {})
            quality_delta_significant = metrics.get('quality_delta_significant', {})
            
            for metric_name in quality.keys():
                row[f'quality_{metric_name}'] = quality[metric_name]
                row[f'quality_delta_{metric_name}'] = quality_delta.get(metric_name, 0)
                row[f'quality_delta_{metric_name}_significant'] = quality_delta_significant.get(metric_name, False)
                
                if metric_name in quality_ci:
                    ci = quality_ci[metric_name]
                    row.update({
                        f'quality_{metric_name}_ci_lower': ci.get('lower', 0),
                        f'quality_{metric_name}_ci_upper': ci.get('upper', 0),
                        f'quality_{metric_name}_ci_mean': ci.get('mean', 0)
                    })
                
                if metric_name in quality_delta_ci:
                    ci = quality_delta_ci[metric_name]
                    row.update({
                        f'quality_delta_{metric_name}_ci_lower': ci.get('lower', 0),
                        f'quality_delta_{metric_name}_ci_upper': ci.get('upper', 0),
                        f'quality_delta_{metric_name}_ci_mean': ci.get('mean', 0)
                    })
            
            rows.append(row)
    
    return pd.DataFrame(rows)


def create_cluster_dataframe(cluster_scores: Dict[str, Any]) -> pd.DataFrame:
    """Convert cluster scores to a tidy dataframe."""
    rows = []
    for cluster, metrics in cluster_scores.items():
        # Filter out "No properties" clusters
        if cluster == "No properties":
            continue
            
        row = {
            'cluster': cluster,
            'size': metrics.get('size', 0),
            'proportion': metrics.get('proportion', 0)
        }
        
        # Add confidence intervals if available
        if 'proportion_ci' in metrics:
            ci = metrics['proportion_ci']
            row.update({
                'proportion_ci_lower': ci.get('lower', 0),
                'proportion_ci_upper': ci.get('upper', 0),
                'proportion_ci_mean': ci.get('mean', 0)
            })
        
        # Add quality metrics
        quality = metrics.get('quality', {})
        quality_delta = metrics.get('quality_delta', {})
        quality_ci = metrics.get('quality_ci', {})
        quality_delta_ci = metrics.get('quality_delta_ci', {})
        quality_delta_significant = metrics.get('quality_delta_significant', {})
        
        for metric_name in quality.keys():
            row[f'quality_{metric_name}'] = quality[metric_name]
            row[f'quality_delta_{metric_name}'] = quality_delta.get(metric_name, 0)
            row[f'quality_delta_{metric_name}_significant'] = quality_delta_significant.get(metric_name, False)
            
            if metric_name in quality_ci:
                ci = quality_ci[metric_name]
                row.update({
                    f'quality_{metric_name}_ci_lower': ci.get('lower', 0),
                    f'quality_{metric_name}_ci_upper': ci.get('upper', 0),
                    f'quality_{metric_name}_ci_mean': ci.get('mean', 0)
                })
            
            if metric_name in quality_delta_ci:
                ci = quality_delta_ci[metric_name]
                row.update({
                    f'quality_delta_{metric_name}_ci_lower': ci.get('lower', 0),
                    f'quality_delta_{metric_name}_ci_upper': ci.get('upper', 0),
                    f'quality_delta_{metric_name}_ci_mean': ci.get('mean', 0)
                })
        
        rows.append(row)
    
    return pd.DataFrame(rows)


def create_model_dataframe(model_scores: Dict[str, Any]) -> pd.DataFrame:
    """Convert model scores to a tidy dataframe."""
    rows = []
    for model, metrics in model_scores.items():
        row = {
            'model': model,
            'size': metrics.get('size', 0),
            'proportion': metrics.get('proportion', 0)
        }
        
        # Add confidence intervals if available
        if 'proportion_ci' in metrics:
            ci = metrics['proportion_ci']
            row.update({
                'proportion_ci_lower': ci.get('lower', 0),
                'proportion_ci_upper': ci.get('upper', 0),
                'proportion_ci_mean': ci.get('mean', 0)
            })
        
        # Add quality metrics
        quality = metrics.get('quality', {})
        quality_delta = metrics.get('quality_delta', {})
        quality_ci = metrics.get('quality_ci', {})
        quality_delta_ci = metrics.get('quality_delta_ci', {})
        quality_delta_significant = metrics.get('quality_delta_significant', {})
        
        for metric_name in quality.keys():
            row[f'quality_{metric_name}'] = quality[metric_name]
            row[f'quality_delta_{metric_name}'] = quality_delta.get(metric_name, 0)
            row[f'quality_delta_{metric_name}_significant'] = quality_delta_significant.get(metric_name, False)
            
            if metric_name in quality_ci:
                ci = quality_ci[metric_name]
                row.update({
                    f'quality_{metric_name}_ci_lower': ci.get('lower', 0),
                    f'quality_{metric_name}_ci_upper': ci.get('upper', 0),
                    f'quality_{metric_name}_ci_mean': ci.get('mean', 0)
                })
            
            if metric_name in quality_delta_ci:
                ci = quality_delta_ci[metric_name]
                row.update({
                    f'quality_delta_{metric_name}_ci_lower': ci.get('lower', 0),
                    f'quality_delta_{metric_name}_ci_upper': ci.get('upper', 0),
                    f'quality_delta_{metric_name}_ci_mean': ci.get('mean', 0)
                })
        
        rows.append(row)
    
    return pd.DataFrame(rows)


def get_quality_metrics(df: pd.DataFrame) -> List[str]:
    """Extract quality metric names from dataframe columns."""
    quality_cols = [col for col in df.columns if col.startswith('quality_') and not col.endswith(('_ci_lower', '_ci_upper', '_ci_mean', '_significant'))]
    return [col.replace('quality_', '') for col in quality_cols]


def create_interactive_cluster_plot(cluster_df: pd.DataFrame, model_cluster_df: pd.DataFrame, 
                                 metric_col: str, title: str, 
                                 ci_lower_col: Optional[str] = None, ci_upper_col: Optional[str] = None,
                                 significant_col: Optional[str] = None) -> go.Figure:
    """Create an interactive cluster plot with dropdown for view mode."""
    
    # Create the figure with subplots
    fig = make_subplots(
        rows=1, cols=1,
        specs=[[{"secondary_y": False}]],
        subplot_titles=[title]
    )
    
    # Prepare cluster_df - reset index if cluster is the index
    if 'cluster' not in cluster_df.columns and cluster_df.index.name == 'cluster':
        cluster_df = cluster_df.reset_index()
    
    # Sort clusters by metric value in descending order for consistent ordering
    cluster_df = cluster_df.sort_values(metric_col, ascending=False)
    
    # Add aggregated view (default) - using cluster_df
    if ci_lower_col and ci_upper_col and ci_lower_col in cluster_df.columns and ci_upper_col in cluster_df.columns:
        fig.add_trace(
            go.Bar(
                x=cluster_df['cluster'],
                y=cluster_df[metric_col],
                name='Aggregated (All Models)',
                error_y=dict(
                    type='data',
                    array=cluster_df[ci_upper_col] - cluster_df[metric_col],
                    arrayminus=cluster_df[metric_col] - cluster_df[ci_lower_col],
                    visible=True
                ),
                visible=True
            )
        )
    else:
        fig.add_trace(
            go.Bar(
                x=cluster_df['cluster'],
                y=cluster_df[metric_col],
                name='Aggregated (All Models)',
                visible=True
            )
        )
    
    # Grouped by model view - using model_cluster_df
    for model in model_cluster_df['model'].unique():
        model_df = model_cluster_df[model_cluster_df['model'] == model]
        # Sort model_df to match the cluster order
        model_df = model_df.set_index('cluster').reindex(cluster_df['cluster']).reset_index()
        if ci_lower_col and ci_upper_col and ci_lower_col in model_cluster_df.columns and ci_upper_col in model_cluster_df.columns:
            fig.add_trace(
                go.Bar(
                    x=model_df['cluster'],
                    y=model_df[metric_col],
                    name=f'Model: {model}',
                    error_y=dict(
                        type='data',
                        array=model_df[ci_upper_col] - model_df[metric_col],
                        arrayminus=model_df[metric_col] - model_df[ci_lower_col],
                        visible=False
                    ),
                    visible=False
                )
            )
        else:
            fig.add_trace(
                go.Bar(
                    x=model_df['cluster'],
                    y=model_df[metric_col],
                    name=f'Model: {model}',
                    visible=False
                )
            )
    
    # Add significance markers if available (for aggregated view)
    # Red asterisks (*) indicate clusters with statistically significant quality delta values
    # (confidence intervals that do not contain 0)
    if significant_col and significant_col in cluster_df.columns:
        for i, (cluster, is_sig) in enumerate(zip(cluster_df['cluster'], cluster_df[significant_col])):
            if is_sig:
                fig.add_annotation(
                    x=cluster,
                    y=cluster_df[cluster_df['cluster'] == cluster][metric_col].iloc[0],
                    text="*",
                    showarrow=False,
                    font=dict(size=16, color="red"),
                    yshift=10
                )
    
    # Update layout
    fig.update_layout(
        title=title,
        xaxis_title="Cluster",
        yaxis_title=metric_col.replace('_', ' ').title(),
        barmode='group',
        height=500,
        showlegend=True,
        annotations=[
            dict(
                text="* = Statistically significant (CI does not contain 0)",
                showarrow=False,
                xref="paper", yref="paper",
                x=0.01, y=0.01,
                xanchor="left", yanchor="bottom",
                font=dict(size=10, color="red")
            )
        ] if significant_col and significant_col in cluster_df.columns else []
    )
    
    # Add dropdown for view selection - only 2 options
    buttons = []
    
    # Aggregated view button (all models combined)
    visibility = [True] + [False] * len(model_cluster_df['model'].unique())
    buttons.append(
        dict(
            label="Aggregated (All Models)",
            method="update",
            args=[{"visible": visibility, "barmode": "group"}]
        )
    )
    
    # Grouped by model view (each model as separate bars)
    visibility = [False] + [True] * len(model_cluster_df['model'].unique())
    buttons.append(
        dict(
            label="Grouped by Model",
            method="update",
            args=[{"visible": visibility, "barmode": "group"}]
        )
    )
    
    fig.update_layout(
        updatemenus=[
            dict(
                buttons=buttons,
                direction="down",
                showactive=True,
                x=0.95,
                xanchor="right",
                y=1.25,
                yanchor="top"
            )
        ]
    )
    
    return fig


def create_interactive_heatmap(df: pd.DataFrame, value_col: str, title: str,
                             pivot_index: str = 'model', pivot_columns: str = 'cluster',
                             significant_col: Optional[str] = None) -> go.Figure:
    """Create an interactive heatmap with hover information."""
    
    # Create pivot table
    pivot_df = df.pivot(index=pivot_index, columns=pivot_columns, values=value_col)
    
    # Sort by mean values for consistent ordering
    if pivot_index == 'model':
        # Sort models by their mean values across clusters
        model_means = pivot_df.mean(axis=1).sort_values(ascending=False)
        pivot_df = pivot_df.reindex(model_means.index)
    else:
        # Sort clusters by their mean values across models
        cluster_means = pivot_df.mean(axis=0).sort_values(ascending=False)
        pivot_df = pivot_df.reindex(columns=cluster_means.index)
    
    # Transpose the data for more intuitive visualization (models on x-axis, clusters on y-axis)
    pivot_df = pivot_df.T
    
    # Create heatmap
    fig = go.Figure(data=go.Heatmap(
        z=pivot_df.values,
        x=pivot_df.columns,  # Models
        y=pivot_df.index,    # Clusters
        colorscale='RdBu_r' if 'delta' in value_col else 'Viridis',
        zmid=0 if 'delta' in value_col else None,
        text=pivot_df.values.round(3),
        texttemplate="%{text}",
        textfont={"size": 10},
        hoverongaps=False
    ))
    
    # Add significance markers if available
    if significant_col and significant_col in df.columns:
        sig_pivot = df.pivot(index=pivot_index, columns=pivot_columns, values=significant_col)
        # Apply same sorting as the main pivot
        if pivot_index == 'model':
            sig_pivot = sig_pivot.reindex(model_means.index)
        else:
            sig_pivot = sig_pivot.reindex(columns=cluster_means.index)
        sig_pivot = sig_pivot.T  # Transpose to match the main heatmap
        for i, cluster in enumerate(pivot_df.index):
            for j, model in enumerate(pivot_df.columns):
                if sig_pivot.loc[cluster, model]:
                    fig.add_annotation(
                        x=model,
                        y=cluster,
                        text="*",
                        showarrow=False,
                        font=dict(size=16, color="red"),
                        xshift=10,
                        yshift=10
                    )
    
    fig.update_layout(
        title=title,
        xaxis_title="Model",
        yaxis_title="Cluster",
        height=500,
        annotations=[
            dict(
                text="* = Statistically significant (CI does not contain 0)",
                showarrow=False,
                xref="paper", yref="paper",
                x=0.01, y=0.01,
                xanchor="left", yanchor="bottom",
                font=dict(size=10, color="red")
            )
        ] if significant_col and significant_col in df.columns else []
    )
    
    return fig


def create_interactive_model_plot(model_df: pd.DataFrame, model_cluster_df: pd.DataFrame, 
                                metric_col: str, title: str, 
                                ci_lower_col: Optional[str] = None, ci_upper_col: Optional[str] = None,
                                significant_col: Optional[str] = None) -> go.Figure:
    """Create an interactive model plot with dropdown for view mode."""
    
    # Create the figure with subplots
    fig = make_subplots(
        rows=1, cols=1,
        specs=[[{"secondary_y": False}]],
        subplot_titles=[title]
    )
    
    # Prepare model_df - reset index if model is the index
    if 'model' not in model_df.columns and model_df.index.name == 'model':
        model_df = model_df.reset_index()
    
    # Add aggregated view (default) - using model_df
    if ci_lower_col and ci_upper_col and ci_lower_col in model_df.columns and ci_upper_col in model_df.columns:
        fig.add_trace(
            go.Bar(
                x=model_df['model'],
                y=model_df[metric_col],
                name='Aggregated (All Clusters)',
                error_y=dict(
                    type='data',
                    array=model_df[ci_upper_col] - model_df[metric_col],
                    arrayminus=model_df[metric_col] - model_df[ci_lower_col],
                    visible=True
                ),
                visible=True
            )
        )
    else:
        fig.add_trace(
            go.Bar(
                x=model_df['model'],
                y=model_df[metric_col],
                name='Aggregated (All Clusters)',
                visible=True
            )
        )
    
    # Grouped by cluster view - using model_cluster_df
    for cluster in model_cluster_df['cluster'].unique():
        cluster_df = model_cluster_df[model_cluster_df['cluster'] == cluster]
        if ci_lower_col and ci_upper_col and ci_lower_col in cluster_df.columns and ci_upper_col in cluster_df.columns:
            fig.add_trace(
                go.Bar(
                    x=cluster_df['model'],
                    y=cluster_df[metric_col],
                    name=f'Cluster: {cluster}',
                    error_y=dict(
                        type='data',
                        array=cluster_df[ci_upper_col] - cluster_df[metric_col],
                        arrayminus=cluster_df[metric_col] - cluster_df[ci_lower_col],
                        visible=False
                    ),
                    visible=False
                )
            )
        else:
            fig.add_trace(
                go.Bar(
                    x=cluster_df['model'],
                    y=cluster_df[metric_col],
                    name=f'Cluster: {cluster}',
                    visible=False
                )
            )
    
    # Add significance markers if available (for aggregated view)
    if significant_col and significant_col in model_df.columns:
        for i, (model, is_sig) in enumerate(zip(model_df['model'], model_df[significant_col])):
            if is_sig:
                fig.add_annotation(
                    x=model,
                    y=model_df[model_df['model'] == model][metric_col].iloc[0],
                    text="*",
                    showarrow=False,
                    font=dict(size=16, color="red"),
                    yshift=10
                )
    
    # Update layout
    fig.update_layout(
        title=title,
        xaxis_title="Model",
        yaxis_title=metric_col.replace('_', ' ').title(),
        barmode='group',
        height=500,
        showlegend=True
    )
    
    # Add dropdown for view selection - only 2 options
    buttons = []
    
    # Aggregated view button (all clusters combined)
    visibility = [True] + [False] * len(model_cluster_df['cluster'].unique())
    buttons.append(
        dict(
            label="Aggregated (All Clusters)",
            method="update",
            args=[{"visible": visibility, "barmode": "group"}]
        )
    )
    
    # Grouped by cluster view (each cluster as separate bars)
    visibility = [False] + [True] * len(model_cluster_df['cluster'].unique())
    buttons.append(
        dict(
            label="Grouped by Cluster",
            method="update",
            args=[{"visible": visibility, "barmode": "group"}]
        )
    )
    
    fig.update_layout(
        updatemenus=[
            dict(
                buttons=buttons,
                direction="down",
                showactive=True,
                x=0.95,
                xanchor="right",
                y=1.25,
                yanchor="top"
            )
        ]
    )
    
    return fig


def create_interactive_model_cluster_plot(df: pd.DataFrame, metric_col: str, title: str,
                                       ci_lower_col: Optional[str] = None, ci_upper_col: Optional[str] = None,
                                       significant_col: Optional[str] = None) -> go.Figure:
    """Create an interactive model-cluster plot with grouped bars."""
    
    # Create grouped bar chart
    if ci_lower_col and ci_upper_col and ci_lower_col in df.columns and ci_upper_col in df.columns:
        fig = px.bar(
            df, 
            x='cluster', 
            y=metric_col, 
            color='model',
            error_y=df[ci_upper_col] - df[metric_col],
            error_y_minus=df[metric_col] - df[ci_lower_col],
            title=title,
            barmode='group'
        )
    else:
        fig = px.bar(
            df, 
            x='cluster', 
            y=metric_col, 
            color='model',
            title=title,
            barmode='group'
        )
    
    # Add significance markers if available
    if significant_col and significant_col in df.columns:
        for i, row in df.iterrows():
            if row[significant_col]:
                fig.add_annotation(
                    x=row['cluster'],
                    y=row[metric_col],
                    text="*",
                    showarrow=False,
                    font=dict(size=16, color="red"),
                    yshift=10
                )
    
    fig.update_layout(
        height=500,
        xaxis_title="Cluster",
        yaxis_title=metric_col.replace('_', ' ').title()
    )
    
    return fig