-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathxas_ui.py
More file actions
1874 lines (1594 loc) · 72.5 KB
/
Copy pathxas_ui.py
File metadata and controls
1874 lines (1594 loc) · 72.5 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 numpy as np
def _patch_pymatgen_neighbors():
try:
from pymatgen.optimization import neighbors as pmg_neighbors
_original_find_points = pmg_neighbors.find_points_in_spheres
def _patched_find_points_in_spheres(
all_coords, center_coords, r, pbc, lattice, tol=1e-8
):
pbc = np.asarray(pbc, dtype=np.int64)
return _original_find_points(
all_coords, center_coords, r, pbc, lattice, tol
)
pmg_neighbors.find_points_in_spheres = _patched_find_points_in_spheres
print("Applied Windows int64 compatibility patch for pymatgen")
except Exception as e:
print(f"Warning: Could not apply pymatgen patch: {e}")
_patch_pymatgen_neighbors()
from base64 import b64encode, b64decode
import os
import io
import tempfile
import pathlib
from zipfile import ZipFile
import re
import pandas as pd
import numpy as np
import dash
from dash import dcc, html
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State, ALL
from dash.exceptions import PreventUpdate
from pymatgen.core.structure import Structure
from mp_api.client import MPRester
import crystal_toolkit.components as ctc
from crystal_toolkit.helpers.layouts import (
Box,
Column,
Columns,
Loading
)
from lightshowai.models import predict
from lightshowai.postprocess import compare_utils
app = dash.Dash(prevent_initial_callbacks=True, title="OmniXAS@Lightshow.ai",
url_base_pathname="/omnixas/")
server = app.server
struct_component = ctc.StructureMoleculeComponent(id="st_vis",
show_image_button=False,
show_export_button=False)
search_component = ctc.SearchComponent(id='mpid_search')
upload_component = ctc.StructureMoleculeUploadComponent(id='file_loader')
# Combined single/multiple structure upload component
batch_upload_component = dcc.Upload(
id='batch_structure_upload',
children=html.Div([
html.Div([
'Drag & Drop or ',
html.A('Select File(s)', style={'color': '#333', 'cursor': 'pointer', 'fontWeight': '500', 'textDecoration': 'underline'})
])
]),
style={
'width': '100%',
'height': '50px',
'lineHeight': '50px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderColor': '#d0d0d0',
'borderRadius': '6px',
'textAlign': 'center',
'backgroundColor': '#fafafa',
'cursor': 'pointer',
'color': '#666',
'fontSize': '12px',
'fontFamily': "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
},
multiple=True, # Allow single or multiple file selection
accept='.cif,.vasp,.poscar,.json'
)
# Store for batch processing status
batch_processing_store = dcc.Store(id='batch_processing_store', data={'status': 'idle', 'processed': 0, 'total': 0})
xas_plot = dcc.Graph(id='xas_plot')
st_source = html.H1(id='st_source', children='No structure loaded yet')
all_elements = ['Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu']
ene_start = {'Ti': 4964.504, 'V': 5464.097, 'Cr': 5989.168, 'Mn': 6537.886,
'Fe': 7111.23, 'Co': 7709.282, 'Ni': 8332.181, 'Cu': 8983.173}
ene_grid = {el: np.linspace(start, start + 35, 141) for el, start in ene_start.items()}
xas_model_names = [f'{el} FEFF' for el in all_elements] + ['Ti VASP', 'Cu VASP']
absorber_dropdown = dcc.Dropdown(xas_model_names, clearable=False, value='Ti VASP', id='absorber')
# All available metrics for display
ALL_METRICS = ["coss_deriv", "pearson", "spearman", "coss", "kendalltaub", "normed_wasserstein"]
# Short display names for table headers
METRIC_SHORT_NAMES = {
"coss_deriv": "Cos(∂)",
"pearson": "Pearson",
"spearman": "Spearman",
"coss": "Cosine",
"kendalltaub": "Kendall",
"normed_wasserstein": "Wasser.",
}
def get_spectrum_match_score(predicted_spectrum, exp_spectrum, element):
"""
Compare predicted spectrum against experimental spectrum using
lightshow.postprocess.compare_utils.compare_between_spectra.
Returns comparison_range which is the energy range used for comparison.
"""
try:
ene = ene_grid[element]
ml_spectrum = np.column_stack((ene, predicted_spectrum))
exp_energy = np.array(exp_spectrum['energy'])
exp_absorption = np.array(exp_spectrum['absorption'])
expt_spectrum = np.column_stack((exp_energy, exp_absorption))
opt_metric = "coss_deriv"
other_metrics = ["pearson", "spearman", "coss", "kendalltaub", "coss_deriv", "normed_wasserstein"]
erange = 35
erange_threshold = 0.04
truncation_strategy = "from_spect2"
erange_lbound_delta = 5
correlations, shift = compare_utils.compare_between_spectra(
expt_spectrum,
ml_spectrum,
erange=erange,
erange_threshold=erange_threshold,
erange_lbound_delta=erange_lbound_delta,
truncation_strategy=truncation_strategy,
grid_interpolator=compare_utils.gridInterpolatorFixedSpacing(0.25),
output_correlations=other_metrics,
opt_strategy="grid_search_and_local_opt",
accuracy=0.1,
method=opt_metric,
norm_y_axis=True
)
# Calculate the comparison range
# The shift returned aligns ML spectrum to experimental spectrum
# ML spectrum energy range after shift: (ene + shift)
# The comparison uses erange (35 eV) starting from edge
# For ML spectrum (spect2), find where edge starts
ml_y_normalized = (ml_spectrum[:, 1] - np.min(ml_spectrum[:, 1])) / (np.max(ml_spectrum[:, 1]) - np.min(ml_spectrum[:, 1]))
ml_edge_idx = np.argmax(ml_y_normalized > erange_threshold)
ml_edge_energy = ml_spectrum[ml_edge_idx, 0]
# The comparison range in the EXPERIMENTAL spectrum's energy scale
# ML edge energy + shift = where ML edge aligns in exp energy scale
comparison_start = ml_edge_energy + shift
comparison_end = comparison_start + erange
# Debug output
# print(f"=== Comparison Range Debug ===")
# print(f"ML edge energy: {ml_edge_energy:.1f} eV")
# print(f"Shift: {shift:.2f} eV")
# print(f"Comparison range: {comparison_start:.1f} - {comparison_end:.1f} eV")
score = correlations.get(opt_metric, 0.0)
if np.isnan(score) or np.isinf(score):
score = 0.0
return {
'score': round(float(score), 3),
'correlations': {k: round(float(v), 3) if not (np.isnan(v) or np.isinf(v)) else 0.0
for k, v in correlations.items()},
'shift': round(float(shift), 2),
'comparison_range': (round(float(comparison_start), 1), round(float(comparison_end), 1))
}
except Exception as e:
print(f"Error in spectrum matching: {e}")
import traceback
traceback.print_exc()
return {
'score': 0.0,
'correlations': {},
'shift': 0.0,
'comparison_range': None
}
# Store for matching results
matching_results_store = dcc.Store(id='matching_results_store', data=[])
structure_scores_store = dcc.Store(id='structure_scores_store', data=[])
comparison_range_store = dcc.Store(id='comparison_range_store', data=None)
selected_spectra_store = dcc.Store(id='selected_spectra_store', data=[])
sort_metric_store = dcc.Store(id='sort_metric_store', data='coss_deriv')
# Custom experimental spectrum upload component
exp_upload_component = dcc.Upload(
id='exp_spectrum_upload',
children=html.Div([
html.Div([
'Drag and Drop or ',
html.A('Select File', style={'color': '#333', 'cursor': 'pointer', 'fontWeight': '500', 'textDecoration': 'underline'})
])
]),
style={
'width': '100%',
'height': '50px',
'lineHeight': '50px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderColor': '#d0d0d0',
'borderRadius': '6px',
'textAlign': 'center',
'backgroundColor': '#fafafa',
'cursor': 'pointer',
'color': '#666',
'fontSize': '12px',
'fontFamily': "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
},
multiple=False,
accept='.dat,.mat,.csv,.xdi'
)
# Input for material name
exp_material_name_input = dcc.Input(
id='exp_material_name',
type='text',
placeholder='e.g., Anatase TiO2',
style={
'width': '100%',
'padding': '10px 12px',
'borderRadius': '6px',
'border': '1px solid #ddd',
'fontSize': '12px',
'boxSizing': 'border-box',
'fontFamily': "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
}
)
# Store for raw file data (before column selection)
exp_raw_data_store = dcc.Store(id='exp_raw_data_store', data=None)
# Store for column definitions
exp_columns_store = dcc.Store(id='exp_columns_store', data=None)
# Store for final experimental spectrum data
exp_spectrum_store = dcc.Store(id='exp_spectrum_store', data=None)
# Dynamic column definition area
exp_column_definition_area = html.Div(
id='exp_column_definition_area',
children=[],
style={'marginTop': '10px'}
)
# Dropdown for X-axis column selection
exp_x_axis_dropdown = dcc.Dropdown(
id='exp_x_axis_dropdown',
options=[],
placeholder='Select X-axis column',
style={'marginBottom': '8px'}
)
# Dropdown for Y-axis column selection
exp_y_axis_dropdown = dcc.Dropdown(
id='exp_y_axis_dropdown',
options=[],
placeholder='Select Y-axis column',
style={'marginBottom': '8px'}
)
# Button to apply column selection and plot
exp_apply_btn = html.Button(
"Apply & Plot",
id="exp_apply_btn",
style={
'padding': '8px 16px',
'fontSize': '12px',
'border': 'none',
'borderRadius': '6px',
'backgroundColor': '#333',
'color': 'white',
'cursor': 'pointer',
'fontWeight': '500',
'marginRight': '8px',
'fontFamily': "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
}
)
# Display for uploaded experimental file info
exp_file_info = html.Div(id='exp_file_info', children='No experimental spectrum loaded',
style={
'fontSize': '11px',
'color': '#888',
'marginTop': '10px',
'fontFamily': "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
})
# Button to clear experimental spectrum
clear_exp_btn = html.Button("Clear", id="clear_exp_btn",
style={
'fontSize': '12px',
'padding': '8px 16px',
'border': '1px solid #ddd',
'borderRadius': '6px',
'backgroundColor': 'white',
'color': '#666',
'cursor': 'pointer',
'fontFamily': "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
})
# Common styles
base_font = "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
section_header_style = {
"fontWeight": "600",
"fontSize": "13px",
"color": "#333",
"marginBottom": "14px",
"paddingBottom": "10px",
"borderBottom": "1px solid #eee",
"fontFamily": base_font,
"letterSpacing": "0.2px"
}
column_header_style = {
"fontWeight": "600",
"fontSize": "13px",
"color": "#333",
"marginBottom": "14px",
"paddingBottom": "10px",
"borderBottom": "1px solid #eee",
"fontFamily": base_font,
"letterSpacing": "0.2px"
}
input_label_style = {
"fontSize": "12px",
"color": "#666",
"marginBottom": "6px",
"fontWeight": "500",
"fontFamily": base_font
}
card_style = {
"backgroundColor": "white",
"borderRadius": "8px",
"padding": "18px",
"marginBottom": "12px",
"border": "1px solid #e8e8e8"
}
button_primary_style = {
'padding': '10px 20px',
'fontSize': '13px',
'border': 'none',
'borderRadius': '6px',
'backgroundColor': '#333',
'color': 'white',
'cursor': 'pointer',
'fontWeight': '500',
'marginRight': '8px',
'fontFamily': base_font
}
button_secondary_style = {
'padding': '8px 16px',
'fontSize': '12px',
'border': '1px solid #ddd',
'borderRadius': '6px',
'backgroundColor': 'white',
'color': '#666',
'cursor': 'pointer',
'fontFamily': base_font
}
onmixas_layout = html.Div([
# Main content area
Columns([
# Column 1: Input Controls
Column(
html.Div([
# Experimental Spectrum Upload Card
html.Div([
html.Div("Upload Experimental Spectrum", style=section_header_style),
html.Div("Material Name (optional):", style=input_label_style),
exp_material_name_input,
html.Div(
"Accepted formats: .csv, .dat, .mat, .xdi",
style={"fontSize": "11px", "color": "#999", "marginTop": "10px", "marginBottom": "8px"}
),
exp_upload_component,
exp_column_definition_area,
html.Div(
id='exp_column_selection_area',
children=[
html.Div("Select columns to plot:", style={**input_label_style, "marginTop": "12px"}),
html.Div([
html.Div([
html.Span("X-axis:", style={"fontSize": "11px", "display": "block", "marginBottom": "4px", "color": "#666"}),
exp_x_axis_dropdown,
], style={"display": "inline-block", "width": "48%", "marginRight": "4%", "verticalAlign": "top"}),
html.Div([
html.Span("Y-axis:", style={"fontSize": "11px", "display": "block", "marginBottom": "4px", "color": "#666"}),
exp_y_axis_dropdown,
], style={"display": "inline-block", "width": "48%", "verticalAlign": "top"}),
]),
html.Div([
exp_apply_btn,
clear_exp_btn,
], style={"marginTop": "12px"}),
],
style={"display": "none"}
),
exp_file_info,
exp_raw_data_store,
exp_columns_store,
exp_spectrum_store,
], style=card_style),
# Load Structure Card
html.Div([
html.Div("Load Structure", style=section_header_style),
# Single structure search
html.Div("Search by Materials Project ID:", style={**input_label_style, "marginBottom": "8px"}),
Loading(search_component.layout()),
html.Hr(style={"margin": "15px 0", "border": "none", "borderTop": "1px solid #eee"}),
# Combined single/multiple file upload
html.Div("Upload structure file(s):", style={**input_label_style, "marginBottom": "4px"}),
html.Div(
"Single or multiple files • Supported: .cif, .vasp, .poscar, .json",
style={"fontSize": "10px", "color": "#999", "marginBottom": "8px"}
),
batch_upload_component,
batch_processing_store,
# Processing status
html.Div(id='batch_status', children='', style={
"fontSize": "11px",
"color": "#666",
"marginTop": "8px",
"fontFamily": base_font
}),
html.Div(st_source, style={"marginTop": "10px"}),
], style=card_style),
# XAS Model Prediction Card
html.Div([
html.Div("XAS Model Prediction", style=section_header_style),
Loading(absorber_dropdown),
], style=card_style),
], style={"width": "100%"}),
narrow=True,
),
# Column 2: Crystal Structure Viewer
Column(
html.Div([
html.Div([
html.Div("Crystal Structure Viewer", style=column_header_style),
Loading(struct_component.layout(size="100%")),
], style={
"backgroundColor": "white",
"borderRadius": "8px",
"padding": "18px",
"border": "1px solid #e8e8e8",
"minHeight": "500px"
})
]),
style={"flex": "1", "minWidth": "400px", "padding": "0 6px"}
),
# Column 3: Spectrum Analysis
Column(
html.Div([
html.Div([
html.Div("XANES Spectrum Analysis", style=column_header_style),
xas_plot,
# Energy shift slider
html.Div([
html.Div([
html.Span("Shift Predicted Spectrum: ", style={"fontSize": "12px", "color": "#666", "fontFamily": base_font}),
html.Span(id='energy_shift_display', children="0.0 eV",
style={"fontSize": "12px", "fontWeight": "600", "color": "#333", "fontFamily": base_font}),
], style={"marginTop": "15px", "marginBottom": "8px"}),
dcc.Slider(
id='energy_shift_slider',
min=-50,
max=50,
step=0.01,
value=0,
marks=None,
tooltip={"placement": "bottom", "always_visible": False},
updatemode='drag',
included=False,
),
html.Div([
html.Span("-50 eV", style={"fontSize": "10px", "color": "#999", "fontFamily": base_font}),
html.Span("0", style={"fontSize": "10px", "color": "#999", "position": "absolute", "left": "50%", "transform": "translateX(-50%)", "fontFamily": base_font}),
html.Span("+50 eV", style={"fontSize": "10px", "color": "#999", "fontFamily": base_font}),
], style={"display": "flex", "justifyContent": "space-between", "position": "relative", "marginTop": "-5px"}),
html.Button("Reset Shift", id="reset_shift_btn", style={**button_secondary_style, "marginTop": "10px", "fontSize": "11px", "padding": "6px 14px"}),
], id='energy_shift_container', style={"padding": "0 10px"}),
html.Hr(style={"margin": "20px 0", "border": "none", "borderTop": "1px solid #eee"}),
html.Button("Download POSCAR and Spectrum", id="download_btn", style={
**button_primary_style,
"width": "100%",
"padding": "12px",
"fontSize": "12px",
"marginRight": "0",
"borderRadius": "6px"
}),
dcc.Download(id="download_sink"),
# Matching Results Section
html.Div([
html.Div([
html.Span("Structure Matching Scores", style={
"fontWeight": "600",
"fontSize": "13px",
"color": "#333",
}),
html.Button("Clear All", id="clear_scores_btn", style={
"fontSize": "10px",
"padding": "4px 10px",
"border": "1px solid #ddd",
"borderRadius": "4px",
"backgroundColor": "white",
"color": "#666",
"cursor": "pointer",
"marginLeft": "10px"
}),
], style={
"display": "flex",
"alignItems": "center",
"justifyContent": "space-between",
"marginTop": "20px",
"marginBottom": "12px",
"paddingBottom": "10px",
"borderBottom": "1px solid #eee"
}),
html.Div(id='matching_results_table', children=[
html.Div("Upload experimental spectrum and load structures to see matching scores",
style={"color": "#999", "fontSize": "12px", "textAlign": "center", "padding": "20px"})
]),
structure_scores_store,
comparison_range_store,
selected_spectra_store,
sort_metric_store,
]),
], style={
"backgroundColor": "white",
"borderRadius": "8px",
"padding": "18px",
"border": "1px solid #e8e8e8"
})
]),
style={"flex": "1", "minWidth": "400px", "padding": "0 6px"}
),
],
desktop_only=False,
centered=False),
], style={
"backgroundColor": "#f5f5f5",
"minHeight": "100vh",
"padding": "12px",
"fontFamily": base_font
})
# Store for energy shift value
energy_shift_store = dcc.Store(id='energy_shift_store', data=0)
def parse_file_columns(contents, filename):
"""
Parse uploaded file and extract all columns with their data.
Supports XDI format with # Column.N: name headers.
"""
if contents is None:
return None
content_type, content_string = contents.split(',')
decoded = b64decode(content_string)
try:
if filename is None:
filename = "unknown.dat"
ext = pathlib.Path(filename).suffix.lower()
print(f"=== DEBUG: Parsing file '{filename}' with extension '{ext}'")
columns = []
data = []
auto_x_col = 0
auto_y_col = 1
if ext in ['.csv', '.dat', '.txt', '.xdi']:
text = decoded.decode('utf-8').replace('\r\n', '\n').replace('\r', '\n')
lines = [line.strip() for line in text.strip().split('\n') if line.strip()]
comment_lines = []
data_lines = []
for line in lines:
if line.startswith(('#', '%', '!')):
comment_lines.append(line)
else:
data_lines.append(line)
if len(data_lines) == 0:
raise ValueError("No data lines found in file")
xdi_columns = {}
energy_col_candidates = []
absorption_col_candidates = []
for comment in comment_lines:
xdi_match = re.match(r'#\s*Column\.(\d+):\s*(.+)', comment, re.IGNORECASE)
if xdi_match:
col_num = int(xdi_match.group(1)) - 1
col_name = xdi_match.group(2).strip()
xdi_columns[col_num] = col_name
print(f"=== DEBUG: Found XDI column {col_num}: '{col_name}'")
col_lower = col_name.lower()
if any(term in col_lower for term in ['energy', ' e ', 'ev', 'photon']):
energy_col_candidates.append(col_num)
if any(term in col_lower for term in ['norm', 'absorption', 'abs', 'mu', 'flat']):
absorption_col_candidates.append(col_num)
if comment_lines and not xdi_columns:
last_comment = comment_lines[-1]
header_text = last_comment.lstrip('#').strip()
header_parts = header_text.split()
if len(header_parts) >= 2 and ':' not in header_text:
print(f"=== DEBUG: Found inline header: {header_parts}")
for i, name in enumerate(header_parts):
xdi_columns[i] = name
name_lower = name.lower()
if name_lower in ['e', 'energy', 'ev']:
energy_col_candidates.append(i)
if name_lower in ['norm', 'flat', 'abs', 'mu', 'absorption']:
absorption_col_candidates.append(i)
first_line = data_lines[0]
if ',' in first_line:
delimiter = ','
else:
delimiter = None
first_parts = first_line.split(delimiter) if delimiter else first_line.split()
num_columns = len(first_parts)
try:
float(first_parts[0].strip())
header = None
start_idx = 0
except ValueError:
header = [p.strip() for p in first_parts]
start_idx = 1
if not xdi_columns:
for i, name in enumerate(header):
xdi_columns[i] = name
data = [[] for _ in range(num_columns)]
for line in data_lines[start_idx:]:
parts = line.split(delimiter) if delimiter else line.split()
for i, part in enumerate(parts):
if i < num_columns:
try:
data[i].append(float(part.strip()))
except ValueError:
pass
for i in range(num_columns):
if i in xdi_columns:
col_name = xdi_columns[i]
elif header and i < len(header):
col_name = header[i]
else:
col_name = f"Column {i+1}"
sample_values = data[i][:5] if len(data[i]) >= 5 else data[i]
columns.append({
'index': i,
'name': col_name,
'num_values': len(data[i]),
'sample_values': sample_values
})
if energy_col_candidates:
auto_x_col = energy_col_candidates[0]
if absorption_col_candidates:
for candidate in absorption_col_candidates:
col_name = xdi_columns.get(candidate, '').lower()
if 'norm' in col_name or 'flat' in col_name:
auto_y_col = candidate
break
else:
auto_y_col = absorption_col_candidates[0]
elif len(columns) > 1:
auto_y_col = 1
elif ext == '.mat':
try:
from scipy.io import loadmat
mat_data = loadmat(io.BytesIO(decoded))
data_keys = [k for k in mat_data.keys() if not k.startswith('__')]
for i, key in enumerate(data_keys):
arr = mat_data[key]
if isinstance(arr, np.ndarray) and arr.size > 1:
flat_arr = arr.flatten().astype(float).tolist()
sample_values = flat_arr[:5] if len(flat_arr) >= 5 else flat_arr
columns.append({
'index': i,
'name': key,
'num_values': len(flat_arr),
'sample_values': sample_values
})
data.append(flat_arr)
key_lower = key.lower()
if any(term in key_lower for term in ['energy', 'e', 'ev']):
auto_x_col = i
if any(term in key_lower for term in ['absorption', 'abs', 'mu', 'norm']):
auto_y_col = i
except ImportError:
raise ValueError("scipy is required to read .mat files")
else:
raise ValueError(f"Unsupported file format: {ext}")
if len(columns) < 2:
raise ValueError("File must have at least 2 columns for X and Y axes")
auto_x_col = min(auto_x_col, len(columns) - 1)
auto_y_col = min(auto_y_col, len(columns) - 1)
if auto_x_col == auto_y_col and len(columns) > 1:
auto_y_col = 1 if auto_x_col == 0 else 0
print(f"=== DEBUG: Found {len(columns)} columns")
for col in columns:
print(f" Column {col['index']}: {col['name']} ({col['num_values']} values)")
print(f"=== DEBUG: Auto-selected X={auto_x_col}, Y={auto_y_col}")
return {
'columns': columns,
'data': data,
'filename': filename,
'auto_x_col': auto_x_col,
'auto_y_col': auto_y_col
}
except Exception as e:
print(f"Error parsing file columns: {e}")
import traceback
traceback.print_exc()
return {'error': str(e)}
@app.callback(
Output('exp_raw_data_store', 'data'),
Output('exp_columns_store', 'data'),
Output('exp_x_axis_dropdown', 'options'),
Output('exp_y_axis_dropdown', 'options'),
Output('exp_x_axis_dropdown', 'value'),
Output('exp_y_axis_dropdown', 'value'),
Output('exp_column_selection_area', 'style'),
Output('exp_column_definition_area', 'children'),
Output('exp_file_info', 'children', allow_duplicate=True),
Output('exp_spectrum_upload', 'contents'),
Output('exp_spectrum_upload', 'filename'),
Output('exp_material_name', 'value'),
Input('exp_spectrum_upload', 'contents'),
Input('clear_exp_btn', 'n_clicks'),
State('exp_spectrum_upload', 'filename'),
prevent_initial_call=True
)
def handle_file_upload(contents, clear_clicks, filename):
"""Handle file upload - parse columns and populate dropdowns."""
ctx = dash.callback_context
if not ctx.triggered:
raise PreventUpdate
trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
hidden_style = {"display": "none"}
visible_style = {"display": "block"}
if trigger_id == 'clear_exp_btn':
return (None, None, [], [], None, None, hidden_style, [],
'No experimental spectrum loaded', None, None, '')
if contents is None:
raise PreventUpdate
result = parse_file_columns(contents, filename)
if result is None or 'error' in result:
error_msg = result.get('error', 'Failed to parse file') if result else 'Failed to parse file'
return (None, None, [], [], None, None, hidden_style, [],
html.Span(f"Error: {error_msg}", style={'color': 'red'}),
dash.no_update, dash.no_update, dash.no_update)
columns = result['columns']
options = [{'label': f"{col['name']} ({col['num_values']} pts)", 'value': col['index']} for col in columns]
default_x = result.get('auto_x_col', 0)
default_y = result.get('auto_y_col', 1 if len(columns) > 1 else 0)
max_visible_rows = 5
table_height = "auto" if len(columns) <= max_visible_rows else f"{max_visible_rows * 40 + 30}px"
col_definition = html.Div([
html.Div(f"Detected {len(columns)} columns (edit names if needed):",
style={"fontSize": "12px", "marginBottom": "6px", "marginTop": "10px"}),
html.Div([
html.Table([
html.Thead(html.Tr([
html.Th("#", style={"padding": "4px 8px", "fontSize": "11px", "width": "30px", "position": "sticky", "top": "0", "backgroundColor": "#fafafa", "zIndex": "1"}),
html.Th("Column Name", style={"padding": "4px 8px", "fontSize": "11px", "position": "sticky", "top": "0", "backgroundColor": "#fafafa", "zIndex": "1"}),
html.Th("Points", style={"padding": "4px 8px", "fontSize": "11px", "width": "50px", "position": "sticky", "top": "0", "backgroundColor": "#fafafa", "zIndex": "1"}),
html.Th("Sample Values", style={"padding": "4px 8px", "fontSize": "11px", "position": "sticky", "top": "0", "backgroundColor": "#fafafa", "zIndex": "1"}),
])),
html.Tbody([
html.Tr([
html.Td(col['index'] + 1, style={"padding": "4px 8px", "fontSize": "11px", "verticalAlign": "middle"}),
html.Td(
dcc.Input(
id={'type': 'col-name-input', 'index': col['index']},
type='text',
value=col['name'],
style={
'width': '100%',
'padding': '4px',
'fontSize': '11px',
'border': '1px solid #ccc',
'borderRadius': '3px'
}
),
style={"padding": "4px"}
),
html.Td(col['num_values'], style={"padding": "4px 8px", "fontSize": "11px", "verticalAlign": "middle"}),
html.Td(
", ".join([f"{v:.2f}" for v in col['sample_values'][:3]]) + "...",
style={"padding": "4px 8px", "fontSize": "10px", "color": "#666", "verticalAlign": "middle"}
),
]) for col in columns
])
], style={"borderCollapse": "collapse", "width": "100%"})
], style={
"maxHeight": table_height,
"overflowY": "auto" if len(columns) > max_visible_rows else "visible",
"border": "1px solid #ddd",
"marginBottom": "10px"
}),
html.Button("Update Column Names", id="exp_update_col_names_btn",
style={"fontSize": "11px", "padding": "4px 8px", "marginBottom": "10px"})
])
x_col_name = columns[default_x]['name'] if default_x < len(columns) else "Column 1"
y_col_name = columns[default_y]['name'] if default_y < len(columns) else "Column 2"
info_text = f"File loaded: {filename} (auto-selected: X={x_col_name}, Y={y_col_name})"
material_name_from_file = pathlib.Path(filename).stem if filename else ""
return (result, columns, options, options, default_x, default_y, visible_style, col_definition,
html.Span(info_text, style={'color': 'blue'}),
dash.no_update, dash.no_update, material_name_from_file)
@app.callback(
Output('exp_columns_store', 'data', allow_duplicate=True),
Output('exp_x_axis_dropdown', 'options', allow_duplicate=True),
Output('exp_y_axis_dropdown', 'options', allow_duplicate=True),
Output('exp_file_info', 'children', allow_duplicate=True),
Input('exp_update_col_names_btn', 'n_clicks'),
State({'type': 'col-name-input', 'index': ALL}, 'value'),
State('exp_columns_store', 'data'),
prevent_initial_call=True
)
def update_column_names(n_clicks, new_names, columns):
"""Update column names when user edits them."""
if n_clicks is None or columns is None:
raise PreventUpdate
for i, new_name in enumerate(new_names):
if i < len(columns):
columns[i]['name'] = new_name.strip() if new_name else f"Column {i+1}"
options = [{'label': f"{col['name']} ({col['num_values']} pts)", 'value': col['index']} for col in columns]
return columns, options, options, html.Span("Column names updated!", style={'color': 'green'})
@app.callback(
Output('exp_spectrum_store', 'data'),
Output('exp_file_info', 'children', allow_duplicate=True),
Input('exp_apply_btn', 'n_clicks'),
State('exp_raw_data_store', 'data'),
State('exp_columns_store', 'data'),
State('exp_x_axis_dropdown', 'value'),
State('exp_y_axis_dropdown', 'value'),
State('exp_material_name', 'value'),
prevent_initial_call=True
)
def apply_column_selection(n_clicks, raw_data, columns, x_col_idx, y_col_idx, material_name):
"""Apply column selection and create the spectrum data for plotting."""
if n_clicks is None or raw_data is None:
raise PreventUpdate
if x_col_idx is None or y_col_idx is None:
return None, html.Span("Please select both X and Y axis columns", style={'color': 'red'})
try:
data = raw_data['data']
filename = raw_data['filename']
x_data = np.array(data[x_col_idx])
y_data = np.array(data[y_col_idx])
min_len = min(len(x_data), len(y_data))
x_data = x_data[:min_len]
y_data = y_data[:min_len]
if len(x_data) < 2:
return None, html.Span("Not enough data points", style={'color': 'red'})
sort_idx = np.argsort(x_data)
x_data = x_data[sort_idx]
y_data = y_data[sort_idx]
x_label = columns[x_col_idx]['name']
y_label = columns[y_col_idx]['name']
display_name = material_name if material_name and material_name.strip() else filename
result = {
'energy': x_data.tolist(),
'absorption': y_data.tolist(),
'filename': filename,
'material_name': display_name,
'x_label': x_label,
'y_label': y_label
}
x_min, x_max = x_data.min(), x_data.max()
info_text = f"✓ {display_name} ({len(x_data)} points, {x_label}: {x_min:.1f}-{x_max:.1f})"
return result, html.Span(info_text, style={'color': 'green'})
except Exception as e:
print(f"Error applying column selection: {e}")
return None, html.Span(f"Error: {str(e)}", style={'color': 'red'})
@app.callback(
Output("download_sink", "data"),
Input("download_btn", "n_clicks"),
State(struct_component.id(), "data"),
State('absorber', 'value'),