forked from Enrique-Val/ProbExplainer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdash_probExplainer.py
More file actions
1725 lines (1541 loc) · 69.1 KB
/
dash_probExplainer.py
File metadata and controls
1725 lines (1541 loc) · 69.1 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dash
from dash import dcc, html, Input, Output, State, ALL
import dash_bootstrap_components as dbc
import base64
import json
import logging
import warnings
from dash.exceptions import PreventUpdate
import pandas as pd
from pgmpy.readwrite import BIFReader
import pyAgrum as gum
import os
import sys
import tempfile
# Add parent directory to sys.path to resolve imports
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
# Import session management components (absolute imports)
try:
from dash_session_manager import start_session_manager, get_session_manager
from dash_session_components import create_session_components, setup_session_callbacks, register_long_running_process
SESSION_MANAGEMENT_AVAILABLE = True
except ImportError as e:
print(f"Warning: Session management not available: {e}")
SESSION_MANAGEMENT_AVAILABLE = False
# Define dummy functions to prevent errors
def start_session_manager(): pass
def get_session_manager(): return None
def create_session_components(): return None, html.Div()
def setup_session_callbacks(app): pass
def register_long_running_process(session_id): pass
warnings.filterwarnings("ignore")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Start the global session manager
if SESSION_MANAGEMENT_AVAILABLE:
start_session_manager()
# ---------- (1) CREATE DASH APP ---------- #
app = dash.Dash(
__name__,
external_stylesheets=[
dbc.themes.BOOTSTRAP,
'https://bayes-interpret.com/Evidence/ProbExplainerDash/assets/liquid-glass.css' # Apple Liquid Glass CSS
],
requests_pathname_prefix='/Evidence/ProbExplainerDash/',
suppress_callback_exceptions=True
)
server = app.server
# Create session components - but use dynamic session creation
if SESSION_MANAGEMENT_AVAILABLE:
# Don't create session here - will be created dynamically per user
session_components = html.Div([
# Dynamic session store - will be populated by callback
dcc.Store(id='session-id-store', data=None),
dcc.Store(id='heartbeat-counter', data=0),
# Interval component for heartbeat (every 5 seconds)
dcc.Interval(
id='heartbeat-interval',
interval=5*1000, # 5 seconds
n_intervals=0,
disabled=False
),
# Interval for cleanup check (every 30 seconds)
dcc.Interval(
id='cleanup-interval',
interval=30*1000, # 30 seconds
n_intervals=0,
disabled=False
),
# Hidden div for status
html.Div(id='session-status', style={'display': 'none'}),
# Client-side script for session management
html.Script("""
// Generate unique session ID per browser
if (!window.dashSessionId) {
window.dashSessionId = 'session_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
}
// Send heartbeat on page activity
document.addEventListener('click', function() {
if (window.dashHeartbeat) window.dashHeartbeat();
});
document.addEventListener('keypress', function() {
if (window.dashHeartbeat) window.dashHeartbeat();
});
// Handle page unload
window.addEventListener('beforeunload', function() {
if (navigator.sendBeacon) {
navigator.sendBeacon('/dash/_disconnect', JSON.stringify({
session_id: window.dashSessionId
}));
}
});
// Handle iframe unload (when parent page changes)
if (window.parent !== window) {
try {
window.parent.addEventListener('beforeunload', function() {
if (navigator.sendBeacon) {
navigator.sendBeacon('/dash/_disconnect', JSON.stringify({
session_id: window.dashSessionId
}));
}
});
} catch(e) {
console.log('Cross-origin iframe detected');
}
}
"""),
], style={'display': 'none'})
session_id = None # Will be set dynamically
else:
session_id = None
session_components = html.Div()
# ---------- (2) HELPER FUNCTION FOR pyAgrum PARSING FROM STRING ---------- #
def loadBNfromMemory(bif_string):
"""
Workaround for pyAgrum versions that do NOT have loadBNFromString.
We write 'bif_string' into a temp .bif file, then load it.
"""
with tempfile.NamedTemporaryFile(suffix=".bif", delete=False, mode='w') as tmp:
tmp_name = tmp.name
tmp.write(bif_string)
try:
bn = gum.loadBN(tmp_name)
finally:
# Clean up the temp file
os.remove(tmp_name)
return bn
# ---------- (3) APP LAYOUT ---------- #
app.layout = html.Div([
# SESSION MANAGEMENT COMPONENTS - ADD THESE TO ALL DASH APPS
session_components,
dcc.Loading(
id="global-spinner",
type="default",
fullscreen=False,
color="#00A2E1",
style={
"position": "fixed",
"top": "50%",
"left": "50%",
"transform": "translate(-50%, -50%)",
"zIndex": "999999"
},
children=html.Div([
html.H1("Bayesian Network ProbExplainer ", style={'textAlign': 'center'}),
########################################################
# Info text
########################################################
html.Div(
className="link-bar",
style={
"textAlign": "center",
"marginBottom": "20px"
},
children=[
html.A(
children=[
html.Img(
src="https://cig.fi.upm.es/wp-content/uploads/github.png",
style={"height": "24px", "marginRight": "8px"}
),
"Original GitHub"
],
href="https://github.com/Enrique-Val/ProbExplainer",
target="_blank",
className="btn btn-outline-info me-2"
),
html.A(
children=[
html.Img(
src="https://cig.fi.upm.es/wp-content/uploads/2023/11/cropped-logo_CIG.png",
style={"height": "24px", "marginRight": "8px"}
),
"Paper PDF"
],
href="https://cig.fi.upm.es/wp-content/uploads/2024/01/Efficient-search-for-relevance-explanations-using-MAP-independence-in-Bayesian-networks.pdf",
target="_blank",
className="btn btn-outline-primary me-2"
),
html.A(
children=[
html.Img(
src="https://cig.fi.upm.es/wp-content/uploads/github.png",
style={"height": "24px", "marginRight": "8px"}
),
"Dash Adapted GitHub"
],
href="https://github.com/KeevinPR/ProbExplainer",
target="_blank",
className="btn btn-outline-info me-2"
),
]
),
########################################################
# Short explanatory text
########################################################
html.Div(
[
html.P(
"Library to adapt and explain probabilistic models and specially aimed for Bayesian networks.",
style={"textAlign": "center", "maxWidth": "800px", "margin": "0 auto"}
)
],
style={"marginBottom": "20px"}
),
########################################################
# (A) Data upload
########################################################
html.Div(className="card", children=[
html.H3("1. Upload Dataset", style={'textAlign': 'center'}),
# Container "card"
html.Div([
# Top part with icon and text
html.Div([
html.Img(
src="https://img.icons8.com/ios-glyphs/40/cloud--v1.png",
className="upload-icon"
),
html.Div("Drag and drop or select a CSV/BIF file", className="upload-text")
]),
# Upload component
dcc.Upload(
id='upload-data',
children=html.Div([], style={'display': 'none'}),
className="upload-dropzone",
multiple=False
),
], className="upload-card"),
# Use default dataset + help icon
html.Div([
dcc.Checklist(
id='use-default-network',
options=[{'label': 'Use the default dataset', 'value': 'default'}],
value=[],
style={'display': 'inline-block', 'textAlign': 'center', 'marginTop': '10px'}
),
dbc.Button(
html.I(className="fa fa-question-circle"),
id="help-button-default-dataset",
color="link",
style={"display": "inline-block", "marginLeft": "8px"}
),
], style={'textAlign': 'center'}),
]),
# Section to select action
html.Div(className="card", children=[
html.H3("2. Select an Action to Perform", style={'textAlign': 'center'}),
html.Div([
dbc.Select(
id='action-dropdown',
options=[
{'label': 'Compute Posterior', 'value': 'posterior'},
{'label': 'Map Independence', 'value': 'map_independence'},
{'label': 'Get Defeaters', 'value': 'defeaters'}
],
value='posterior', # Default action
style={
'width': '100%',
'border': '1px solid #d0d7de',
'borderRadius': '6px',
'padding': '8px 12px',
'backgroundColor': 'rgba(255, 255, 255, 0.8)',
'backdropFilter': 'blur(10px)',
'boxShadow': '0 1px 3px rgba(0, 0, 0, 0.1)',
'transition': 'all 0.2s ease',
'fontSize': '14px'
}
)
], style={'width': '300px', 'margin': '0 auto'})
]),
# Evidence selection
html.Div(className="card", children=[
html.Div([
html.H3("3. Select Evidence Variables", style={'display': 'inline-block', 'marginRight': '10px', 'textAlign': 'center'}),
dbc.Button(
html.I(className="fa fa-question-circle"),
id="help-button-evidence",
color="link",
style={"display": "inline-block", "verticalAlign": "middle", "padding": "0", "marginLeft": "5px"}
),
], style={"textAlign": "center", "position": "relative"}),
# Buttons for bulk selection
html.Div([
dbc.Button(
"Select All",
id="select-all-evidence",
color="outline-primary",
size="sm",
style={'marginRight': '10px'}
),
dbc.Button(
"Clear All",
id="clear-evidence",
color="outline-secondary",
size="sm"
)
], style={'textAlign': 'center', 'marginBottom': '15px'}),
# Checkbox container for evidence variables
html.Div(
id='evidence-checkbox-container',
style={
'maxHeight': '200px',
'overflowY': 'auto',
'border': '1px solid #ddd',
'borderRadius': '5px',
'padding': '10px',
'margin': '0 auto',
'width': '80%',
'backgroundColor': '#f8f9fa'
}
),
html.Div(id='evidence-values-container')
]),
# Target variables
html.Div(className="card", children=[
html.Div([
html.H3("4. Select Target Variables", style={'display': 'inline-block', 'marginRight': '10px', 'textAlign': 'center'}),
dbc.Button(
html.I(className="fa fa-question-circle"),
id="help-button-targets",
color="link",
style={"display": "inline-block", "verticalAlign": "middle", "padding": "0", "marginLeft": "5px"}
),
], style={"textAlign": "center", "position": "relative"}),
# Buttons for bulk selection
html.Div([
dbc.Button(
"Select All",
id="select-all-targets",
color="outline-primary",
size="sm",
style={'marginRight': '10px'}
),
dbc.Button(
"Clear All",
id="clear-targets",
color="outline-secondary",
size="sm"
)
], style={'textAlign': 'center', 'marginBottom': '15px'}),
# Checkbox container for target variables
html.Div(
id='target-checkbox-container',
style={
'maxHeight': '200px',
'overflowY': 'auto',
'border': '1px solid #ddd',
'borderRadius': '5px',
'padding': '10px',
'margin': '0 auto',
'width': '80%',
'backgroundColor': '#f8f9fa'
}
),
# Info message about intelligent selection
html.Div([
html.I(className="fa fa-info-circle", style={'marginRight': '5px', 'color': '#6c757d'}),
html.Span("Target variables automatically exclude evidence variables. Previous selections are preserved when possible.",
style={'fontSize': '11px', 'color': '#6c757d'})
], style={'textAlign': 'center', 'marginTop': '8px'}),
]),
# Set R (only needed for map_independence)
html.Div(className="card", children=[
html.Div([
html.H3("5. Select Set R (only for Map Independence)", style={'display': 'inline-block', 'marginRight': '10px', 'textAlign': 'center'}),
dbc.Button(
html.I(className="fa fa-question-circle"),
id="help-button-r-vars",
color="link",
style={"display": "inline-block", "verticalAlign": "middle", "padding": "0", "marginLeft": "5px"}
),
], style={"textAlign": "center", "position": "relative"}),
# Buttons for bulk selection
html.Div([
dbc.Button(
"Select All",
id="select-all-r-vars",
color="outline-primary",
size="sm",
style={'marginRight': '10px'}
),
dbc.Button(
"Clear All",
id="clear-r-vars",
color="outline-secondary",
size="sm"
)
], style={'textAlign': 'center', 'marginBottom': '15px'}),
# Checkbox container for R variables
html.Div(
id='r-vars-checkbox-container',
style={
'maxHeight': '200px',
'overflowY': 'auto',
'border': '1px solid #ddd',
'borderRadius': '5px',
'padding': '10px',
'margin': '0 auto',
'width': '80%',
'backgroundColor': '#f8f9fa'
}
),
# Info message about R set selection
html.Div([
html.I(className="fa fa-info-circle", style={'marginRight': '5px', 'color': '#6c757d'}),
html.Span("R variables exclude both evidence and target variables.",
style={'fontSize': '11px', 'color': '#6c757d'})
], style={'textAlign': 'center', 'marginTop': '8px'}),
]),
# Run button
html.Div([
dbc.Button(
[
html.I(className="fas fa-play-circle me-2"),
"Run Analysis"
],
id='run-action-button',
n_clicks=0,
color="info",
className="btn-lg",
style={
'fontSize': '1.1rem',
'padding': '0.75rem 2rem',
'borderRadius': '8px',
'boxShadow': '0 2px 4px rgba(0,0,0,0.1)',
'transition': 'all 0.3s ease',
'backgroundColor': '#00A2E1',
'border': 'none',
'margin': '1rem 0',
'color': 'white',
'fontWeight': '500'
}
)
], style={'textAlign': 'center'}),
html.Br(),
html.Div(id='action-results', style={'textAlign': 'center'}),
# Store to keep the chosen network path/string
dcc.Store(id='stored-network'),
# Store to keep the nodes and states (so we don't parse repeatedly)
dcc.Store(id='stored-model-info'),
# Stores for tracking selections
dcc.Store(id='previous-evidence-selection', data=[]),
dcc.Store(id='previous-target-selection', data=[]),
dcc.Store(id='previous-r-selection', data=[]),
# Store to detect dataset changes and trigger reset
dcc.Store(id='dataset-change-detector', data=None),
# Store for tracking clean state
dcc.Store(id='app-clean-state', data=True),
# Notification system
dcc.Store(id='notification-store'),
])
),
dbc.Popover(
[
dbc.PopoverHeader(
[
"Help",
html.I(className="fa fa-info-circle ms-2", style={"color": "#0d6efd"})
],
style={
"backgroundColor": "#f8f9fa", # Light gray background
"fontWeight": "bold"
}
),
dbc.PopoverBody(
[
html.P(
[
"For details and content of the dataset, check out: ",
html.A(
"network_5.bif",
href="https://github.com/KeevinPR/ProbExplainer/blob/main/expert_networks/network_5.bif",
target="_blank",
style={"textDecoration": "underline", "color": "#0d6efd"}
),
]
),
html.Hr(), # Horizontal rule for a modern divider
html.P("Feel free to upload your own dataset at any time.")
],
style={
"backgroundColor": "#ffffff",
"borderRadius": "0 0 0.25rem 0.25rem"
}
),
],
id="help-popover-default-dataset",
target="help-button-default-dataset",
placement="right",
is_open=False,
trigger="hover"
),
# Add Evidence Selection Popover
dbc.Popover(
[
dbc.PopoverHeader(
[
"Evidence Selection",
html.I(className="fa fa-info-circle ms-2", style={"color": "#0d6efd"})
],
style={"backgroundColor": "#f8f9fa", "fontWeight": "bold"}
),
dbc.PopoverBody(
[
html.P("Evidence variables are the known states in your Bayesian network."),
html.P("Select one or more variables that you want to use as evidence."),
html.P("For each selected variable, you'll need to specify its state."),
html.P("These values will be used in the probabilistic analysis."),
],
style={"backgroundColor": "#ffffff", "borderRadius": "0 0 0.25rem 0.25rem", "maxWidth": "300px"}
),
],
id="help-popover-evidence",
target="help-button-evidence",
placement="right",
is_open=False,
trigger="hover",
style={"position": "absolute", "zIndex": 1000, "marginLeft": "5px"}
),
# Add Target Variables Popover
dbc.Popover(
[
dbc.PopoverHeader(
[
"Target Variables",
html.I(className="fa fa-info-circle ms-2", style={"color": "#0d6efd"})
],
style={"backgroundColor": "#f8f9fa", "fontWeight": "bold"}
),
dbc.PopoverBody(
[
html.P("Target variables are the nodes you want to analyze in your Bayesian network."),
html.P("Select one or more variables for your analysis:"),
html.Ul([
html.Li("Compute Posterior: Variables to compute probabilities for"),
html.Li("Map Independence: Variables for MAP estimation"),
html.Li("Get Defeaters: Variables to find defeaters for")
]),
html.P("Variables used as evidence cannot be selected as targets."),
],
style={"backgroundColor": "#ffffff", "borderRadius": "0 0 0.25rem 0.25rem", "maxWidth": "300px"}
),
],
id="help-popover-targets",
target="help-button-targets",
placement="right",
is_open=False,
trigger="hover",
style={"position": "absolute", "zIndex": 1000, "marginLeft": "5px"}
),
# Add R Variables Popover
dbc.Popover(
[
dbc.PopoverHeader(
[
"Set R Variables",
html.I(className="fa fa-info-circle ms-2", style={"color": "#0d6efd"})
],
style={"backgroundColor": "#f8f9fa", "fontWeight": "bold"}
),
dbc.PopoverBody(
[
html.P("Set R is only used for Map Independence analysis."),
html.P("These variables represent the intervention set for testing independence."),
html.P("The analysis will check if the MAP assignment is independent of interventions on these variables."),
html.P("R variables exclude both evidence and target variables."),
],
style={"backgroundColor": "#ffffff", "borderRadius": "0 0 0.25rem 0.25rem", "maxWidth": "300px"}
),
],
id="help-popover-r-vars",
target="help-button-r-vars",
placement="right",
is_open=False,
trigger="hover",
style={"position": "absolute", "zIndex": 1000, "marginLeft": "5px"}
),
# Notification container (outside dcc.Loading to avoid interference)
html.Div(id='notification-container', style={
'position': 'fixed',
'bottom': '20px',
'right': '20px',
'zIndex': '1000',
'width': '300px',
'transition': 'all 0.3s ease-in-out',
'transform': 'translateY(100%)',
'opacity': '0'
}),
])
# ---------- (4) CALLBACKS ---------- #
# (B) Clear default checkbox when file is uploaded
@app.callback(
Output('use-default-network', 'value'),
Input('upload-data', 'contents'),
State('use-default-network', 'value'),
prevent_initial_call=True
)
def clear_default_on_upload(contents, current_value):
"""
Clear the 'Use default dataset' checkbox when a file is uploaded.
This prevents confusion about which dataset is being used.
"""
if contents is not None:
logger.info("File uploaded, clearing default dataset checkbox")
return [] # Clear the checkbox
raise PreventUpdate
# (C) Store the chosen network (default or uploaded) in 'stored-network'
@app.callback(
Output('stored-network', 'data'),
Output('notification-store', 'data'),
Output('dataset-change-detector', 'data'),
Input('upload-data', 'contents'),
State('upload-data', 'filename'),
Input('use-default-network', 'value')
)
def load_network(contents, filename, default_value):
"""
Store path/string in 'stored-network' and provide user feedback via notifications.
Also manages dataset change detection.
- If 'default' is in default_value => use the known path to network_5.bif (or your default).
- If user uploads => decode the BIF string.
- If nothing => PreventUpdate.
"""
import time
# Generate unique change ID for dataset change detection
change_id = str(time.time())
# Priority 1: Handle file upload (takes precedence over default)
if contents:
logger.info(f"Attempting to load uploaded network: {filename}")
# Validate file extension
if filename and not filename.lower().endswith('.bif'):
return dash.no_update, create_warning_notification(
"Please upload a .bif file. Other formats are not supported.",
"Invalid File Format"
), dash.no_update
try:
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
bif_data = decoded.decode('utf-8')
# Check if valid BIF with pgmpy
reader_check = BIFReader(string=bif_data)
model = reader_check.get_model() # fails if invalid
# Additional validations
if not model.nodes():
return dash.no_update, create_error_notification(
"The uploaded network has no nodes. Please check your BIF file.",
"Empty Network"
), dash.no_update
node_count = len(model.nodes())
if node_count > 100:
network_data = {
'network_name': filename,
'network_type': 'string',
'content': bif_data
}
notification = create_warning_notification(
f"Large network detected ({node_count} nodes). Performance may be affected.",
"Large Network"
)
return network_data, notification, change_id
logger.info(f"Valid network uploaded: {filename} with {node_count} nodes")
network_data = {
'network_name': filename,
'network_type': 'string',
'content': bif_data
}
return network_data, None, change_id
except UnicodeDecodeError:
logger.error(f"Error decoding file: {filename}")
return dash.no_update, create_error_notification(
"Unable to decode the file. Please ensure it's a valid text-based BIF file.",
"File Encoding Error"
), dash.no_update
except Exception as e:
error_msg = str(e)
logger.error(f"Error loading network: {e}")
# Provide specific error messages for common issues
if "variable" in error_msg.lower() and "not found" in error_msg.lower():
notification = create_error_notification(
"Network contains undefined variables. Please check your BIF file structure.",
"Invalid Network Structure"
)
elif "probability" in error_msg.lower():
notification = create_error_notification(
"Network contains invalid probability values. Please verify your CPTs.",
"Invalid Probabilities"
)
elif "parse" in error_msg.lower() or "syntax" in error_msg.lower():
notification = create_error_notification(
"BIF file has syntax errors. Please check the file format.",
"Syntax Error"
)
else:
notification = create_error_notification(
f"Error loading network: {error_msg}",
"Network Loading Error"
)
return dash.no_update, notification, dash.no_update
# Priority 2: Handle default checkbox (only if no file was uploaded)
elif 'default' in default_value:
try:
# Check if default file exists and is valid
default_path = '/var/www/html/CIGModels/backend/cigmodelsdjango/cigmodelsdjangoapp/ProbExplainer/expert_networks/network_5.bif'
# Validate default file
with open(default_path, 'r') as f:
default_data = f.read()
test_reader = BIFReader(string=default_data)
_ = test_reader.get_model() # Validate structure
logger.info("Using default network: network_5.bif")
network_data = {
'network_name': 'network_5.bif',
'network_type': 'path',
'content': default_path
}
return network_data, None, change_id
except FileNotFoundError:
logger.error("Default network file not found")
return dash.no_update, create_error_notification(
"Default network file not found. Please upload your own BIF file.",
"File Not Found"
), dash.no_update
except Exception as e:
logger.error(f"Error loading default network: {e}")
return dash.no_update, create_error_notification(
f"Error loading default network: {str(e)}",
"Invalid Default Network"
), dash.no_update
# If neither default is checked nor any file is uploaded => do nothing
raise PreventUpdate
# (B.5) Reset app state when dataset changes
@app.callback(
Output('action-results', 'children', allow_duplicate=True),
Output('app-clean-state', 'data'),
Output('previous-evidence-selection', 'data', allow_duplicate=True),
Output('previous-target-selection', 'data', allow_duplicate=True),
Output('previous-r-selection', 'data', allow_duplicate=True),
Output('notification-store', 'data', allow_duplicate=True),
Input('dataset-change-detector', 'data'),
prevent_initial_call=True
)
def reset_app_state_on_dataset_change(change_id):
"""
Reset app to clean state when dataset changes.
This clears previous results and selections to avoid confusion.
"""
if change_id is not None:
logger.info(f"Dataset changed (ID: {change_id}), resetting app state")
# Create notification to inform user of reset
notification = create_info_notification(
"Application state has been reset due to dataset change. Previous selections and results have been cleared.",
"State Reset"
)
return (
html.Div(), # Clear action results
True, # Mark app as clean
[], # Clear previous evidence selection
[], # Clear previous target selection
[], # Clear previous R selection
notification # Notify user of reset
)
raise PreventUpdate
# (B.6) Clear checkboxes when dataset changes
@app.callback(
Output({'type': 'evidence-checkbox', 'index': ALL}, 'value', allow_duplicate=True),
Output({'type': 'target-checkbox', 'index': ALL}, 'value', allow_duplicate=True),
Output({'type': 'r-vars-checkbox', 'index': ALL}, 'value', allow_duplicate=True),
Input('dataset-change-detector', 'data'),
State({'type': 'evidence-checkbox', 'index': ALL}, 'id'),
State({'type': 'target-checkbox', 'index': ALL}, 'id'),
State({'type': 'r-vars-checkbox', 'index': ALL}, 'id'),
prevent_initial_call=True
)
def clear_checkboxes_on_dataset_change(change_id, evidence_ids, target_ids, r_vars_ids):
"""
Clear all checkbox selections when dataset changes to start fresh.
"""
if change_id is not None:
logger.info("Clearing all checkbox selections due to dataset change")
# Return empty lists for all checkboxes to clear them
evidence_clear = [[] for _ in evidence_ids]
target_clear = [[] for _ in target_ids]
r_vars_clear = [[] for _ in r_vars_ids]
return evidence_clear, target_clear, r_vars_clear
raise PreventUpdate
# (B.7) Clear evidence values container when dataset changes
@app.callback(
Output('evidence-values-container', 'children', allow_duplicate=True),
Input('dataset-change-detector', 'data'),
prevent_initial_call=True
)
def clear_evidence_values_on_dataset_change(change_id):
"""
Clear evidence values dropdowns when dataset changes.
"""
if change_id is not None:
logger.info("Clearing evidence values container due to dataset change")
return []
raise PreventUpdate
# (C) Once 'stored-network' is set, parse it with pgmpy => store nodes/states in 'stored-model-info'
@app.callback(
Output('stored-model-info', 'data'),
Output('notification-store', 'data', allow_duplicate=True),
Input('stored-network', 'data'),
prevent_initial_call=True
)
def parse_network_and_store_info(stored_net):
if not stored_net:
raise PreventUpdate
logger.info("Parsing network with pgmpy to extract nodes/states...")
try:
if stored_net['network_type'] == 'path':
reader_local = BIFReader(stored_net['content'])
else:
# read from string
reader_local = BIFReader(string=stored_net['content'])
net = reader_local.get_model()
nodes_list = sorted(net.nodes())
# Validate network structure
if not nodes_list:
logger.error("Network has no nodes")
return dash.no_update, create_error_notification(
"The network has no nodes. Please check your BIF file.",
"Empty Network"
)
# For each node, gather possible states and validate:
states_dict = {}
problematic_nodes = []
for var in nodes_list:
try:
cpd = net.get_cpds(var)
states = cpd.state_names[var]
# Validate states
if not states or len(states) == 0:
problematic_nodes.append(f"{var} (no states)")
elif len(states) == 1:
logger.warning(f"Node {var} has only one state: {states[0]}")
states_dict[var] = states
except Exception as e:
logger.error(f"Error processing node {var}: {e}")
problematic_nodes.append(f"{var} (processing error)")
# Report warnings for problematic nodes
if problematic_nodes:
warning_msg = f"Some nodes have issues: {', '.join(problematic_nodes[:3])}"
if len(problematic_nodes) > 3:
warning_msg += f" and {len(problematic_nodes) - 3} more"
return {
'nodes': nodes_list,
'states': states_dict
}, create_warning_notification(
warning_msg,
"Network Structure Issues"
)
# Success case - no notification needed
return {
'nodes': nodes_list,
'states': states_dict
}, None
except Exception as e:
error_msg = str(e)
logger.error(f"Error parsing network in parse_network_and_store_info: {e}")
# Provide specific error messages
if "file not found" in error_msg.lower():
return dash.no_update, create_error_notification(
"Network file not found. Please re-upload your BIF file.",
"File Not Found"
)
elif "permission" in error_msg.lower():
return dash.no_update, create_error_notification(
"Permission denied accessing network file. Please try uploading again.",
"Access Error"
)
else:
return dash.no_update, create_error_notification(
f"Failed to parse network: {error_msg}",
"Parsing Error"
)
# (D) Populate evidence checkbox container only if a model is available
@app.callback(
Output('evidence-checkbox-container', 'children'),
Input('stored-model-info', 'data')
)
def update_evidence_variables(model_info):
if not model_info:
return html.Div("No network loaded", style={'textAlign': 'center', 'color': '#666'})
variables = model_info['nodes']
if not variables:
return html.Div("No variables found", style={'textAlign': 'center', 'color': '#666'})
# Create checkboxes in a grid layout
checkboxes = []
for i, var in enumerate(variables):
checkboxes.append(
html.Div([
dcc.Checklist(
id={'type': 'evidence-checkbox', 'index': var},
options=[{'label': f' {var}', 'value': var}],
value=[],
style={'margin': '0'}
)
], style={'display': 'inline-block', 'width': '50%', 'marginBottom': '5px'})
)
return html.Div(checkboxes, style={'columnCount': '2', 'columnGap': '20px'})