-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
6420 lines (5472 loc) · 299 KB
/
app.py
File metadata and controls
6420 lines (5472 loc) · 299 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
from shiny import App, Inputs, Outputs, Session, render, ui, reactive
from shinywidgets import output_widget, render_plotly, render_widget
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import pandas as pd
import tempfile
from pathlib import Path
import math
import requests
import os
from urllib.parse import urlparse
import plotly.graph_objects as go
from plotly.graph_objects import FigureWidget
from compute import (
fit_ellipse_fixed_center,
normalize,
normalize_image,
read_mrc_as_image,
load_image,
fft_image_with_matplotlib,
compute_fft_image_region,
compute_average_fft,
calculate_apix_from_distance,
calculate_distance_from_apix,
calculate_tilt_angle,
get_resolution_info,
compute_fft_1d_data,
# compute_fft_polar_heatmap_data,
calibrateMag_process_one_region_advanced,
calibrateMag_process_one_region_fast,
resolution_to_radius,
# create_fft_1d_plotly_figure,
get_image,
plot_image,
get_image_with_binning,
extract_region_no_binning,
bin_image,
google_analytics,
detect_elliptical_distortion
)
# ---------- Documentation ----------
"""Magnification Calibration Tool
This tool helps calibrate electron microscopes by analyzing test specimen images.
It calculates the pixel size (Angstroms/pixel) by measuring diffraction patterns
from known specimens like graphene, gold, or ice.
Key Features:
- Supports common image formats (.png, .tif) and MRC files
- Interactive FFT analysis with resolution circles
- Automatic pixel size detection
- Radial averaging for enhanced signal detection
- Customizable resolution measurements
Usage:
1. Upload a test specimen image
2. Select the expected diffraction pattern (graphene/gold/ice)
3. Adjust the region size to analyze
4. Click points in the FFT to measure distances
5. Use auto-search to find the best pixel size match
The tool will display:
- Original image with selected region
- FFT with resolution circles
- 1D radial plot
- Calculated pixel size (Angstroms/pixel)
"""
import argparse
def print_help():
"""Print usage instructions and help information."""
help_text = """
Magnification Calibration Tool
---------------------------
Usage:
Run the Shiny app and follow the web interface.
Input Files:
- Image formats: PNG, TIFF
- MRC files from microscopes
Key Parameters:
Apix: Pixel size in Angstroms/pixel (0.01-6.0)
Region: Size of FFT analysis region (1-100%)
Resolution circles:
- Graphene: 2.13 Å
- Gold: 2.355 Å
- Ice: 3.661 Å
- Custom: User-defined resolution
Analysis Features:
- Interactive FFT region selection
- Resolution circle overlay
- Automatic pixel size detection
- Radial averaging
- Click-to-measure distances
Output:
- Processed FFT image
- Radial intensity profile
- Calculated pixel size
"""
print(help_text)
# Create the main UI using page_sidebar for proper Shiny styling
app_ui = ui.page_fillable(
google_analytics(id="G-87KWVDCHHL"),
# ui.sidebar(
# # App title and description in sidebar
# ui.h1("Magnification Calibration", style="font-size: 24px; font-weight: bold; margin-bottom: 15px; color: #333;"),
# ui.p("This tool helps calibrate electron microscopes by analyzing test specimen images.",
# style="font-size: 13px; color: #666; margin-bottom: 10px; line-height: 1.4;"),
# # Add some basic help text
# ui.div(
# ui.h4("Quick Start:", style="font-size: 16px; font-weight: bold; margin-bottom: 10px;"),
# ui.tags.ol(
# ui.tags.li("Select input method (URL or Upload)"),
# ui.tags.li("Choose region and calculate FFT"),
# ui.tags.li("Analyze resolution patterns"),
# style="font-size: 12px; line-height: 1.4; margin-left: 15px;"
# ),
# style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-top: 20px;"
# ),
# open="closed"
# ),
# Add custom CSS for enhanced styling
ui.tags.head(
ui.tags.style("""
/* Image container styles */
.image-output {
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
#padding: 5px;
#margin-bottom: 5px;
width: 100%;
min-height: 300px;
flex: 1;
scrollbar-width: auto;
scrollbar-color: rgba(0, 0, 0, 0.3) transparent;
}
.image-output::-webkit-scrollbar {
width: 12px;
height: 12px;
}
.image-output::-webkit-scrollbar-track {
background: transparent;
}
.image-output::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.3);
border-radius: 2px;
border: 2px solid transparent;
}
.image-output img {
height: auto;
width: auto;
max-width: none;
max-height: none;
margin-bottom: 8px;
}
/* Footer styles */
.card-footer {
height: 40px;
padding: 8px;
background-color: rgba(0, 0, 0, 0.03);
border-top: 1px solid rgba(0, 0, 0, 0.125);
display: flex;
align-items: center;
flex-shrink: 0;
margin-top: 0;
width: 100%;
}
/* Make Plotly widgets fill their containers */
.js-plotly-plot {
height: 100% !important;
width: 100% !important;
}
/* Ensure cards with Plotly widgets use full height */
.card .output_widget {
height: 100%;
min-height: 400px;
}
/* Ensure 2x2 grid layout cards have consistent heights */
.layout-columns > .card {
min-height: 500px;
height: auto;
}
/* Style for the data table container */
.data-table-container {
max-height: 400px;
overflow-y: auto;
border: 1px solid #dee2e6;
border-radius: 0.375rem;
}
.data-table-container table {
width: 100%;
font-size: 0.875rem;
}
.data-table-container th {
background-color: #f8f9fa;
position: sticky;
top: 0;
z-index: 10;
}
"""),
ui.tags.script("""
// Custom JavaScript to ensure only one shape at a time for image display
document.addEventListener('DOMContentLoaded', function() {
// Function to clear all shapes except the latest one (only for image display)
function clearPreviousShapes() {
const plots = document.querySelectorAll('.js-plotly-plot');
plots.forEach(plot => {
// Only clear shapes for image display (not FFT display)
// Check if this is the image display plot by looking for specific characteristics
if (plot.layout && plot.layout.shapes && plot.layout.shapes.length > 1) {
// Check if this is likely the image display (has drawrect mode)
const isImageDisplay = plot.layout.dragmode === 'drawrect' ||
plot.layout.modebar && plot.layout.modebar.add &&
plot.layout.modebar.add.includes('drawrect');
if (isImageDisplay) {
// Keep only the last shape for image display
const lastShape = plot.layout.shapes[plot.layout.shapes.length - 1];
plot.layout.shapes = [lastShape];
Plotly.relayout(plot, {shapes: [lastShape]});
}
// Don't clear shapes for FFT display - allow multiple circles
}
});
}
// Listen for shape drawing events using MutationObserver
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
const plots = document.querySelectorAll('.js-plotly-plot');
plots.forEach(plot => {
if (plot.layout && plot.layout.shapes && plot.layout.shapes.length > 1) {
setTimeout(clearPreviousShapes, 50);
}
});
}
});
});
// Start observing
observer.observe(document.body, {
childList: true,
subtree: true
});
// Also listen for click events on plots
document.addEventListener('click', function(e) {
if (e.target.closest('.js-plotly-plot')) {
setTimeout(clearPreviousShapes, 100);
}
});
});
""")
),
# App title
ui.h1("Magnification Calibration",
style="text-align: center; font-size: 28px; font-weight: bold; margin: 10px 0; color: #333; border-bottom: 2px solid #007bff; padding-bottom: 5px;"),
# Primary analysis section - always visible
ui.div(
{"style": "margin-bottom: 10px;"},
ui.layout_columns(
ui.card(
ui.card_header("Original Image"),
# Accordion panel with controls
ui.accordion(
ui.accordion_panel(
"Input Image",
# Input method selection with conditional panels
ui.div(
{"style": "display: flex; gap: 10px; margin-bottom: 5px; width: 100%;"},
# Left side: Radio buttons and inputs
ui.div(
{"style": "flex: 4; display: flex; flex-direction: column; gap: 5px;"},
ui.input_radio_buttons(
"input_method",
"Method:",
choices=["URL", "Upload (.mrc,.tiff,.png)"],
selected="URL",
inline=True
),
# Conditional input for URL
ui.panel_conditional(
"input.input_method === 'URL'",
ui.input_text(
"download_url",
"Download URL:",
value="https://raw.githubusercontent.com/jianglab/magCalApp/008ab91715945e3a52355ed2be64bb8bc027cc13/test_image/130k-Pixel0.75A.tiff",
placeholder="Enter image URL",
width="100%"
)
),
# Conditional input for Upload
ui.panel_conditional(
"input.input_method === 'Upload (.mrc,.tiff,.png)'",
ui.input_file("upload", None, accept=["image/*", ".mrc", ".tif", ".png"], multiple=True)
)
),
# Right side: Upload files table (only visible when Upload is selected)
ui.panel_conditional(
"input.input_method === 'Upload (.mrc,.tiff,.png)'",
ui.div(
{"style": "flex: 6; overflow-y: auto; padding: 2px; min-height: 0; max-height: 170px;"},
ui.output_data_frame("upload_files_table"),
)
)
),
ui.div(
{"style": "display: flex; justify-content: flex-start; align-items: flex-start; gap: 100px; width: 100%;"},
ui.div(
{"style": "display: flex; flex-direction: column; gap: 5px;"},
ui.tags.label("Nominal Pixel Size", {"for": "nominal_apix", "style": "margin-bottom: 0","width":"120px"}),
ui.input_numeric("nominal_apix", None, value=1.00, min=0.01, max=10.0, step=0.01, width="160px"),
),
ui.div(
{"style": "display: flex; flex-direction: column; gap: 5px;"},
ui.tags.label("Test Specimen:", {"for": "resolution_type", "style": "margin-bottom: 0"}),
ui.div(
{"style": "display: flex; align-items: flex-start; gap: 10px;"},
ui.input_select("resolution_type", None,
choices=["Graphene (2.13 Å)", "Gold (2.355 Å)", "Ice (3.661 Å)", "Custom"],
selected="Graphene (2.13 Å)",
width="180px"),
ui.panel_conditional(
"input.resolution_type == 'Custom'",
ui.input_numeric("custom_resolution", "Custom Res (Å):", value=3.0, min=0.1, max=10.0, step=0.01, width="240px")
)
)
)
),
open="closed"
),
open=False,
multiple=False
),
output_widget("image_display"),
ui.div(
{"style": "display: flex; gap: 5px; padding: 5px; justify-content: center;"},
#ui.input_action_button("clear_drawn_region", "Clear Selection", class_="btn-secondary"),
ui.input_action_button("calc_fft", "Calc FFT", class_="btn-primary"),
),
# ui.div(
# {"class": "card-footer"},
# "Use box selection tool to drag and select regions (you'll see red dots), then click 'Calc FFT' to analyze.",
# ),
full_screen=True,
),
# Right column: FFT and Result cards stacked vertically
# ui.div(
# {"style": "display: flex; flex-direction: column; gap: 8px; height: 100%;"},
ui.div(
{"style": "height: 850px;"},
ui.card(
ui.card_header("FFT Analysis"),
ui.div(
{"style": "height: 778px; overflow: hidden;"},
ui.navset_tab(
ui.nav_panel(
ui.tooltip(
"1D Radial Profile",
"Radially averaged power spectrum analysis with NuFFT interpolation for enhanced resolution detection",
placement="top"
),
ui.div(
{"style": "height: 100%; display: flex; gap: 8px;"},
# Left: Main content area with NuFFT power curve and heatmap
ui.div(
{"style": "height: 100%; display: flex; flex-direction: column; flex: 1;"},
# Top: Power curve plot (60% height) - shows first for quick interaction
output_widget("nufft_power_curve"),
output_widget('nufft_heatmap')
# ui.div(
# {"style": "flex: 6; display: flex; flex-direction: column; min-height: 0;"},
# ui.div(
# {"style": "flex: 1; display: flex; align-items: center; justify-content: center; min-height: 0;"},
# output_widget("nufft_power_curve")
# )
# ),
# # Bottom: NuFFT focused heatmap (40% height) - shows after click
# ui.div(
# {"style": "flex: 4; display: flex; align-items: center; justify-content: center; min-height: 0; border-top: 1px solid #dee2e6;"},
# output_widget("nufft_heatmap")
# )
),
# Right: Controls spanning entire height
ui.div(
{"style": "display: flex; flex-direction: column; justify-content: flex-start; width: 240px; padding: 5px; flex-shrink: 0;"},
ui.input_checkbox("nufft_log_y", "Log Scale", value=False),
# ui.input_checkbox("nufft_use_mean_profile", "Use Average Profile", value=False),
# ui.input_checkbox("nufft_smooth", "Smooth Signal", value=False),
# ui.input_checkbox("nufft_detrend", "Detrend Signal", value=False),
# ui.div(
# {"style": "margin-bottom: 5px;"},
# ui.panel_conditional(
# "input.nufft_smooth",
# ui.input_slider("nufft_window_size", "Window Size", min=1, max=11, value=3, step=2),
# ),
# ),
ui.div(
{"style": "margin-bottom: 5px;"},
ui.input_slider("nufft_r_sampling_freq", "Radial Sampling Frequency (per pixel)", min=0.1, max=10, value=5, step=0.1),
),
ui.div(
{"style": "margin-bottom: 5px;"},
ui.input_slider("nufft_theta_sampling_freq", "Angular Sampling Frequency (per degree)", min=0.1, max=5, value=2, step=0.1),
),
ui.div(
{"style": "margin-bottom: 5px;"},
ui.input_slider("nufft_display_range", "Display Range (%)", min=1, max=10, value=3, step=0.5),
),
# ui.input_action_button("nufft_find_apix", "Find Apix", class_="btn-primary"),
)
)
),
ui.nav_panel(
"2D Spectrum",
ui.div(
{"style": "height: 100%; display: flex; flex-direction: row; gap: 8px;"},
# FFT display - flex: 1 to take all available space
ui.div(
{"style": "flex: 1; min-height: 0; display: flex; align-items: stretch; justify-content: stretch; width: 100%;"},
ui.div(
{"style": "width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;"},
output_widget("fft_with_circle")
)
),
# Controls on the right
ui.div(
{"style": "display: flex; flex-direction: column; justify-content: flex-start; width: 270px; gap:8px; padding: 8px; flex-shrink: 0;"},
ui.div(
{"style": "flex: 0;"},
ui.input_slider("contrast", "Contrast", min=0.1, max=5.0, value=1.0, step=0.1, width="100%")
),
ui.input_action_button("detect_peaks", "Detect Peaks", class_="btn-primary", style="flex-shrink: 0; width: 100%;"),
ui.input_action_button("clear_overlay", "Clear Overlay", class_="btn-secondary", style="flex-shrink: 0; width: 100%;"),
ui.div(
{"style": "margin-top: 8px; padding: 6px; background-color: #f8f9fa; border-radius: 5px; font-size: 1em; line-height: 1.3; overflow-wrap: break-word; word-break: break-word;"},
ui.output_text("tilt_output")
)
)
)
),
# ui.nav_panel(
# "DFT",
# ui.div(
# {"style": "height: 100%; display: grid; grid-template-columns: 1fr 200px; gap: 15px;"},
# # Left: Main content area with polar heatmap and radial profile
# ui.div(
# {"style": "height: 100%; display: flex; flex-direction: column;"},
# # Top: Polar Heat Map (70% height)
# ui.div(
# {"style": "flex: 7; display: flex; align-items: center; justify-content: center; min-height: 0;"},
# output_widget("fft_polar_heatmap")
# ),
# # Bottom: Radial Profile (30% height)
# ui.div(
# {"style": "flex: 3; display: flex; align-items: center; justify-content: center; min-height: 0; border-top: 1px solid #dee2e6;"},
# output_widget("fft_1d_plot")
# )
# ),
# # Right: Controls spanning entire height
# ui.div(
# {"style": "display: flex; flex-direction: column; justify-content: flex-start; width: 100%; padding: 10px;"},
# ui.input_checkbox("log_y", "Log Scale", value=False),
# ui.input_checkbox("use_mean_profile", "Use Average Profile", value=False),
# ui.input_checkbox("smooth", "Smooth Signal", value=False),
# ui.input_checkbox("detrend", "Detrend Signal", value=False),
# ui.div(
# {"style": "margin-bottom: 10px;"},
# ui.panel_conditional(
# "input.smooth",
# ui.input_slider("window_size", "Window Size", min=1, max=11, value=3, step=2),
# ),
# ),
# ui.div(
# {"style": "margin-bottom: 10px;"},
# ui.input_checkbox("super_resolution", "Super Resolution", value=True),
# ui.panel_conditional(
# "input.super_resolution",
# ui.input_slider("gaussian_window", "Gaussian Window (pixels)", min=1, max=21, value=5, step=2),
# ),
# ),
# ui.input_action_button("find_max", "Find Max", class_="btn-primary"),
# )
# )
# )
)
),
full_screen=True,
#style="flex: 1; min-height: 400px;"
)
),
# Result card (bottom)
ui.card(
ui.card_header("Result"),
ui.div(
{"style": "padding: 8px; display: flex;flex-direction: column; align-items: left; gap: 10px; min-height: 80px;"},
# Apix slider
#ui.div(
#{"style": "flex: 5; display: flex; align-items: flex-end; gap: 5px;"},
ui.tags.label("Pixel Size (Å/px):", {"for": "apix_slider", "style": "margin: 0; white-space: nowrap;"}),
ui.input_slider("apix_slider", None, min=0.01, max=2.0, value=1.0, step=0.0001, width="100%"),
# ui.div(
# {"style": "flex: 1; display: flex; align-items: flex-end;"},
# ui.input_slider("apix_slider", None, min=0.01, max=2.0, value=1.0, step=0.0001, width="100%")
# ),
#),
# Apix exact input and Set button
ui.div(
{"style": "display: flex; align-items: baseline; gap: 5px; justify-content:center; flex-direction:row"},
# ui.div(
#{"style": "display: flex; align-items: center; justify:center;background: #e9ecef; border: 10px;"},
ui.input_text("apix_exact_str", None, value="1.0",width="120px"),
#),
ui.input_action_button(
"apix_set_btn",
"Set",
class_="btn-primary",
),
# ui.div(
# {"style": "display: flex; align-items: center; height: 100%;"},
# ui.input_text("apix_exact_str", None, value="1.0", width="120px"),
# ),
# ui.div(
# {"style": "display: flex; align-items: center; height: 100%;"},
# ui.input_action_button(
# "apix_set_btn",
# "Set",
# class_="btn-primary",
# style="height:100%; display:flex; align-items:center; justify-content:center; padding:0 12px;"
# ),
# ),
),
ui.input_action_button("add_to_table", "Add to Table", class_="btn-success")#, style="height: 38px; width: 100%;max-width: 200px; display: flex; align-items: center; justify-content: center;"),
),
# style="flex: 1 2 2 1 2;min-height: 100px;"
),
#),
col_widths=[4,6,2],
),
),
# Secondary analysis section - scrollable below
ui.div(
{"style": "margin-top: 10px;"},
ui.card(
ui.card_header(
ui.tooltip(
"Statistics",
"Table tracks all calibrated pixel size results across multiple regions and magnifications. Click Download CSV to save the result table",
placement="top"
)
),
# Use row layout: table+buttons on left (55%), plot on right (45%), both full height
ui.layout_columns(
# Left column: Table and controls (55% width, 100% height)
ui.div(
{"style": "display: flex; flex-direction: column; height: 500px;"},
ui.div(
{"style": "flex: 1; overflow-y: auto; padding: 5px; min-height: 0;"},
ui.output_data_frame("region_table"),
),
ui.div(
{"style": "flex-shrink: 0; display: flex; gap: 5px; padding: 5px; justify-content: center; align-items: center; flex-wrap: wrap; border-top: 1px solid #dee2e6;"},
# ui.div(
# {"style": "display: flex; gap: 5px; align-items: center;"},
# #ui.input_action_button("random_generate", "Random Generate", class_="btn-info"),
# ui.div(
# {"style": "display: flex; flex-direction: column; align-items: center;"},
# ui.div(
# {"style": "font-size: 10px; color: #666; margin-bottom: 2px;"},
# "Count"
# ),
# ui.input_numeric("random_count", None, value=5, min=1, max=100, step=1, width="70px"),
# ),
# ui.div(
# {"style": "display: flex; flex-direction: column; align-items: center;"},
# ui.div(
# {"style": "font-size: 10px; color: #666; margin-bottom: 2px;"},
# "Size %"
# ),
# ui.input_numeric("region_size_percent", None, value=0.2, min=0.1, max=1.0, step=0.1, width="70px"),
# ),
# ),
ui.input_action_button("delete_selected", "Delete Selected", class_="btn-danger"),
ui.input_action_button("clear_table", "Clear Table", class_="btn-secondary"),
ui.download_button("download_csv", "Download CSV", class_="btn-primary"),
),
),
# Right column: Plot (45% width, 100% height)
ui.div(
{"style": "height: 500px; padding: 5px; display: flex; flex-direction: column;"},
ui.div(
{"style": "flex: 1; min-height: 0;"},
output_widget("apix_centered_by_nominal_plot"),
),
),
col_widths=[7, 5], # 58.3%/41.7% split (closest to 55%/45% with integer grid)
),
full_screen=True,
),
fillable=True,
)
)
size = 360
# ---------- Helper Functions ----------
# ---------- Server ----------
def server(input: Inputs, output: Outputs, session: Session):
# Central reactive state for FFT panel
fft_state = reactive.Value({
'mode': 'Resolution Ring',
'resolution_radius': None,
'resolution_click_x': None,
'resolution_click_y': None,
'lattice_points': [],
'ellipse_params': None,
'tilt_info': None,
'zoom_factor': 1.0,
'drawn_circles': [], # List of drawn circles on FFT image
'current_measurement': None # Current line measurement data
})
# Separate reactive values for FFT image rendering to avoid unnecessary re-renders
fft_markers = reactive.Value({
'mode': 'Resolution Ring',
'resolution_click_x': None,
'resolution_click_y': None,
'lattice_points': [],
'ellipse_params': None,
'zoom_factor': 1.0
})
# --- Single source of truth for apix ---
apix_master = reactive.Value(1.0)
# Effect to update fft_markers when relevant parts of fft_state change
@reactive.Effect
@reactive.event(fft_state)
def _():
"""Update fft_markers when relevant parts of fft_state change."""
state = fft_state.get()
fft_markers.set({
'mode': state['mode'],
'resolution_click_x': state['resolution_click_x'],
'resolution_click_y': state['resolution_click_y'],
'lattice_points': state['lattice_points'].copy(),
'ellipse_params': state['ellipse_params'],
'zoom_factor': state['zoom_factor']
})
# Flag to prevent duplicate image downloads during initialization
startup_download_completed = reactive.Value(False)
# Handle file upload and populate upload table
@reactive.Effect
@reactive.event(input.upload)
def _():
"""Handle multiple file upload and populate the upload table."""
files = input.upload()
if files is None or len(files) == 0:
# Clear the uploaded files data if no files
uploaded_files_data.set([])
return
# Process each uploaded file
files_info = []
for i, file_info in enumerate(files):
# Extract nominal apix from filename, default to 1.0 if unclear
filename = file_info['name']
nominal_apix = extract_nominal(filename)
files_info.append({
'index': i,
'name': filename,
'nominal_apix': nominal_apix,
'file_info': file_info # Store the full file info for later use
})
# Update the uploaded files data
uploaded_files_data.set(files_info)
# Auto-select the first file
if files_info:
selected_file_index.set(0)
# Set the nominal apix from the first file
nominal_apix_value.set(files_info[0]['nominal_apix']) # Store in reactive value FIRST
nominal_apix_ui_synced.set(False) # Mark as not yet synced
ui.update_numeric("nominal_apix", value=files_info[0]['nominal_apix'])
# Handle table row selection for file switching
@reactive.Effect
def _():
"""Handle file selection from upload table."""
try:
# Get the data frame selection from upload_files_table
selected_rows = input.upload_files_table_selected_rows()
if selected_rows and len(selected_rows) > 0:
# Update selected file index based on table selection
new_index = selected_rows[0]
if new_index != selected_file_index.get():
selected_file_index.set(new_index)
# Update nominal apix from selected file
files_data = uploaded_files_data.get()
if files_data and new_index < len(files_data):
selected_file = files_data[new_index]
nominal_apix_value.set(selected_file['nominal_apix']) # Store in reactive value FIRST
nominal_apix_ui_synced.set(False) # Mark as not yet synced
ui.update_numeric("nominal_apix", value=selected_file['nominal_apix'])
except Exception as e:
print(f"Error handling table selection: {e}")
# Remove fft_1d_data since we're no longer using static markers
# Add reactive value to cache the base FFT image
cached_fft_image = reactive.Value(None)
# Add reactive values to cache NuFFT data
cached_nufft_heatmap_data = reactive.Value(None)
cached_nufft_power_data = reactive.Value(None)
# Add plot zoom state
plot_zoom = reactive.Value({
'x_range': None,
'y_range': None
})
# Shared x-axis range for heatmap and 1D profile
shared_x_range = reactive.Value(None)
# Track which plot triggered the range change to avoid loops
range_update_source = reactive.Value(None)
# Add reactive values for raw data and region
raw_image_data = reactive.Value({
'img': None,
'data': None
})
# Add reactive values for image display
image_data = reactive.Value(None)
image_apix = reactive.Value(1.0)
image_filename = reactive.Value(None)
nominal_apix_value = reactive.Value(0.75) # Default nominal apix for initial calculation
nominal_apix_ui_synced = reactive.Value(False) # Track if UI has been updated with extracted value
# Add reactive values for original and binned image data
original_image_data = reactive.Value(None)
binned_image_data = reactive.Value(None)
# Add reactive value for image zoom state
image_zoom_state = reactive.Value({
'x_range': None,
'y_range': None,
'is_zoomed': False,
'drawn_region': None # Store drawn rectangle coordinates
})
# Add reactive value to trigger FFT calculations
fft_trigger = reactive.Value(0)
# Add reactive value to store the 1D plot FigureWidget for in-place updates
fft_1d_widget = reactive.Value(None)
# Add reactive value to store the FFT FigureWidget for in-place overlay updates
fft_widget = reactive.Value(None)
# Add reactive value to store the NuFFT power curve FigureWidget for click handling
nufft_power_widget = reactive.Value(None)
# Add reactive value to store the NuFFT heatmap FigureWidget for click handling
nufft_heatmap_widget = reactive.Value(None)
# Add reactive value to store the clicked position on NuFFT power curve for green line
#nufft_click_position = reactive.Value(None)
# Smart heatmap control: track clicked frequency for focused heatmap rendering
nufft_clicked_frequency = reactive.Value(None)
nufft_show_focused_heatmap = reactive.Value(False)
# Flag to prevent NuFFT recalculation when apix is updated from power curve clicks
apix_updating_from_nufft_click = reactive.Value(False)
# Add reactive value to store all drawn shapes
drawn_shapes = reactive.Value([])
# Add separate reactive value to store box coordinates directly
box_coordinates = reactive.Value(None)
# Add separate reactive value for lattice points to avoid FFT re-renders
lattice_points_storage = reactive.Value([])
# Add separate reactive value for tilt information to avoid FFT re-renders
tilt_info_storage = reactive.Value(None)
# Add separate reactive values for dual tilt information
tilt_info_green_storage = reactive.Value(None)
tilt_info_red_storage = reactive.Value(None)
# Add separate reactive value for ellipse parameters to avoid FFT re-renders
ellipse_params_storage = reactive.Value(None)
# Add separate reactive value for tuned markers (red circles from local maxima)
tuned_markers_storage = reactive.Value([])
# Add separate reactive value for tuned resolution ring
tuned_resolution_radius = reactive.Value(None)
# Add separate reactive value for current mode to avoid FFT re-renders
current_mode_storage = reactive.Value('Resolution Ring')
# Add reactive value to trigger only overlay updates (not base FFT re-render)
overlay_update_trigger = reactive.Value(0)
# Add reactive value that only changes when base FFT image changes
base_fft_trigger = reactive.Value(0)
# Add reactive value to trigger autoscale on FFT calculation (not contrast changes)
autoscale_trigger = reactive.Value(0)
# Add reactive value to force complete FFT widget refresh
fft_widget_refresh_trigger = reactive.Value(0)
# Add reactive values for uploaded files management
uploaded_files_data = reactive.Value([]) # List of file info dicts
selected_file_index = reactive.Value(0) # Currently selected file index
# Helper function to extract nominal value from filename
def extract_nominal(filename):
"""Extract nominal apix value from filename.
Examples:
- '390k-nominal0.36.tiff' -> 0.36
- '150k-nominal0.97.tiff' -> 0.97
- '130k-Pixel0.75A.tiff' -> 0.75
- 'test1.25image.mrc' -> 1.25
Returns 1.0 if extraction fails or if ambiguous (multiple values found).
"""
import re
if not isinstance(filename, str):
return 1.0
# Try different patterns in order of specificity
patterns = [
r"nominal(\d+\.\d+)", # nominal0.36, nominal1.25
r"pixel(\d+\.\d+)a?", # Pixel0.75A, pixel1.0
r"apix(\d+\.\d+)", # apix0.5, apix1.2
r"(\d+\.\d+)a(?:ngstrom)?", # 0.75A, 1.5angstrom
r"(\d+\.\d+)(?=\D|$)" # Any X.XX format (less specific, use last)
]
found_values = []
# Try each pattern
for pattern in patterns:
matches = re.findall(pattern, filename, re.IGNORECASE)
for match in matches:
try:
value = float(match)
# Only consider reasonable apix values (0.1 to 5.0)
if 0.1 <= value <= 5.0:
found_values.append(value)
except ValueError:
continue
# Return the first reasonable value found, or 1.0 if none/ambiguous
if len(found_values) == 1:
return found_values[0]
elif len(found_values) > 1:
# If multiple values, prefer the first one from a more specific pattern
return found_values[0]
else:
return 1.0
# Add reactive value to store the region analysis table data
region_table_data = reactive.Value(pd.DataFrame({
'Filename': [],
'Region Size': [],
'Region Location': [],
'Pixel Size': [],
'Nominal': [],
'Average Pixel Size': []
}))
# Add reactive value to store the region and parameters used for current FFT calculation
fft_calculation_state = reactive.Value({
'region': None,
'apix': None,
'resolution_type': None,
'custom_resolution': None
})
# Add separate reactive state for NuFFT calculations
nufft_calculation_state = reactive.Value({
'region': None,
'apix': None,
'resolution_type': None,
'custom_resolution': None
})
# Track if NuFFT calculation has been requested
nufft_calculation_requested = reactive.Value(False)
# Track FFT widget creation to prevent duplicates
fft_widget_last_created = reactive.Value(None)
# Update 1D plot when cached FFT image changes (removed base_fft_trigger to prevent double render)
@reactive.Effect
@reactive.event(cached_fft_image)
def _():
"""Update 1D plot when the base FFT image changes."""
# Also update 1D plot widget if it exists
widget = fft_1d_widget.get()
if widget is not None and len(widget.data) > 0:
# Get updated plot data using stored calculation state
plot_data = fft_1d_data()
if plot_data is not None:
# Update the trace data in-place
with widget.batch_update():
widget.data[0].x = plot_data['x_data']
widget.data[0].y = plot_data['y_data']
widget.data[0].name = plot_data['profile_label']
# Update y-axis title based on log_y setting
if input.log_y():
widget.layout.yaxis.title.text = "Log(FFT intensity)"
else:
widget.layout.yaxis.title.text = "FFT intensity"
# Initialize Fit button state
@reactive.Effect
def _():
"""Initialize Fit button state."""
is_disabled = input.label_mode() != "Lattice Point"
# Tune Markers now works in both modes
ui.update_action_button("fit_markers", disabled=is_disabled, session=session)
ui.update_action_button("estimate_tilt", disabled=is_disabled, session=session)
# Update Estimate Tilt button state based on ellipse fitting
# @reactive.Effect
# @reactive.event(fft_state)
# def _():
# """Update Estimate Tilt button state based on ellipse fitting."""
# current_state = fft_state.get()
# if current_state['mode'] == 'Lattice Point':
# # Enable Estimate Tilt only if ellipse is fitted
# has_ellipse = current_state['ellipse_params'] is not None
# ui.update_action_button("estimate_tilt", disabled=not has_ellipse, session=session)
# --- All events update apix_master ---
@reactive.Effect
@reactive.event(input.apix_slider)
def _():
click_flag = apix_updating_from_nufft_click.get()
if click_flag:
# Skip updates when apix is being set from NuFFT click
return
apix_master.set(input.apix_slider())
# Clear 1D plot clicked position when apix changes from slider
#plot_1d_click_pos.set({'x': None, 'y': None})
@reactive.Effect
@reactive.event(input.apix_set_btn)
def _():
try:
val = float(input.apix_exact_str())
if 0.001 <= val <= 6.0:
click_flag = apix_updating_from_nufft_click.get()
if click_flag:
# Skip updates when apix is being set from NuFFT click
return
#apix_master.set(val)
ui.update_slider("apix_slider", value=val, session=session)
ui.update_text("apix_exact_str", value=str(round(val, 4)), session=session)
# Clear 1D plot clicked position when apix changes from Set button
#plot_1d_click_pos.set({'x': None, 'y': None})
except Exception:
pass