-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompute.py
More file actions
2078 lines (1717 loc) · 76.8 KB
/
compute.py
File metadata and controls
2078 lines (1717 loc) · 76.8 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
"""
Computation functions for the Magnification Calibration Tool.
This module contains all the mathematical and image processing calculations
used by the main application.
"""
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
import mrcfile
from pathlib import Path
from scipy.optimize import least_squares
import math
from skimage.transform import resize_local_mean
import plotly.graph_objects as go
import plotly.express as px
try:
from finufft import nufft2d2
FINUFFT_AVAILABLE = True
except ImportError:
FINUFFT_AVAILABLE = False
from scipy.stats import median_abs_deviation
from shiny import ui
from shiny.express import expressify
@expressify
def google_analytics(id):
if id is None or not len(id):
return
ui.head_content(
ui.HTML(
f"""
<script async src="https://www.googletagmanager.com/gtag/js?id={id}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){{dataLayer.push(arguments);}}
gtag('js', new Date());
gtag('config', '{id}');
</script>
"""
)
)
def fit_ellipse_fixed_center(points, center=(0, 0)):
"""
Fit an ellipse to points with fixed center using least squares.
Args:
points: List of (x, y) tuples
center: (cx, cy) center coordinates
Returns:
(a, b, theta): semi-major axis, semi-minor axis, rotation angle (radians)
"""
cx, cy = center
points = np.array(points)
# Transform points to center
x = points[:, 0] - cx
y = points[:, 1] - cy
# Standard ellipse equation: (x/a)^2 + (y/b)^2 = 1
# For rotated ellipse: ((x*cos(theta) + y*sin(theta))/a)^2 + ((-x*sin(theta) + y*cos(theta))/b)^2 = 1
def ellipse_residuals(params):
a, b, theta = params
if a <= 0 or b <= 0:
return np.inf * np.ones(len(x))
# Rotate points
cos_t, sin_t = np.cos(theta), np.sin(theta)
x_rot = x * cos_t + y * sin_t
y_rot = -x * sin_t + y * cos_t
# Calculate residuals
residuals = (x_rot / a)**2 + (y_rot / b)**2 - 1
return residuals
# Initial guess: use bounding box
x_range = np.max(x) - np.min(x)
y_range = np.max(y) - np.min(y)
a_init = max(x_range, y_range) / 2
b_init = min(x_range, y_range) / 2
theta_init = 0
# Fit using least squares
try:
result = least_squares(ellipse_residuals, [a_init, b_init, theta_init],
bounds=([0.1, 0.1, -np.pi/2], [np.inf, np.inf, np.pi/2]))
a, b, theta = result.x
return a, b, theta
except:
# Fallback to simple bounding box
return a_init, b_init, theta_init
def normalize(magnitude, contrast=2.0):
"""
Normalize FFT magnitude data for display.
Args:
magnitude: FFT magnitude array
contrast: Number of standard deviations to include in range
Returns:
Normalized array (0-255 uint8)
"""
mean = np.mean(magnitude)
std = np.std(magnitude)
m1 = np.max(magnitude)
# Adjust clip max based on contrast value
clip_max = min(m1, mean + contrast * std)
clip_min = 0
magnitude_clipped = np.clip(magnitude, clip_min, clip_max)
normalized = 255 * (magnitude_clipped - clip_min) / (clip_max - clip_min + 1e-8)
return normalized
def normalize_image(img: np.ndarray, contrast=2.0, use_percentiles=False, low_percentile=1.0, high_percentile=99.0) -> np.ndarray:
"""
Normalize image data using either mean/std or percentile-based clipping.
Args:
img: Input image array
contrast: Number of standard deviations to include in range (if not using percentiles)
use_percentiles: If True, use percentile-based clipping instead of mean/std
low_percentile: Lower percentile for clipping (0-100)
high_percentile: Upper percentile for clipping (0-100)
Returns:
Normalized image array (0-255 uint8)
"""
# Convert to float32 for calculations
img_float = img.astype(np.float32)
if use_percentiles:
# Use percentile-based clipping to remove outliers
clip_min = np.percentile(img_float, low_percentile)
clip_max = np.percentile(img_float, high_percentile)
else:
# Use mean ± contrast * std
mean = np.mean(img_float)
std = np.std(img_float)
clip_min = max(0, mean - contrast * std)
clip_max = min(img_float.max(), mean + contrast * std)
# Clip and normalize to 0-255 range
img_clipped = np.clip(img_float, clip_min, clip_max)
# Avoid division by zero
range_val = clip_max - clip_min
if range_val < 1e-8:
return np.full_like(img_clipped, 128, dtype=np.uint8)
img_normalized = 255 * (img_clipped - clip_min) / range_val
return img_normalized.astype(np.uint8)
def read_mrc_as_image(mrc_path: str) -> Image.Image:
"""
Read an MRC file and convert it to a PIL Image.
Args:
mrc_path: Path to the MRC file
Returns:
PIL Image object
"""
with mrcfile.open(mrc_path) as mrc:
# Get the data and convert to float32
data = mrc.data.astype(np.float32)
# Create PIL Image (normalization will be done later)
return Image.fromarray(data.astype(np.uint8))
def load_image(path: Path) -> tuple[Image.Image, np.ndarray]:
"""
Load an image file or MRC file and return as PIL Image and raw data.
Automatically normalizes bright images for proper display.
Args:
path: Path to the image or MRC file
Returns:
Tuple of (PIL Image object, raw numpy array)
"""
if path.suffix.lower() == '.mrc':
with mrcfile.open(str(path)) as mrc:
data = mrc.data.astype(np.float32)
# Use percentile-based normalization for MRC files to handle outliers
normalized_data = normalize_image(data, use_percentiles=True, low_percentile=1.0, high_percentile=99.0)
return Image.fromarray(normalized_data), data
else:
img = Image.open(path)
raw_data = np.array(img.convert("L")).astype(np.float32)
# Check if the image is very bright (e.g., from projection images)
# If the image has values much higher than typical 8-bit range, normalize it
if raw_data.max() > 1000 or raw_data.std() > 1000:
print(f"Detected bright image (max: {raw_data.max():.1f}, std: {raw_data.std():.1f}). Applying percentile-based normalization...")
# Use percentile-based normalization to remove outliers on both ends
normalized_data = normalize_image(raw_data, use_percentiles=True, low_percentile=0.5, high_percentile=99.5)
return Image.fromarray(normalized_data), raw_data
else:
return img, raw_data
def fft_image_with_matplotlib(region: np.ndarray, contrast=2.0, return_array=False):
"""
Compute FFT of a region and return as PIL Image.
Args:
region: Input image array
contrast: Contrast parameter for normalization
return_array: Whether to return array instead of image
Returns:
PIL Image of FFT
"""
# Validate region size to prevent FFT errors
if region.size == 0 or region.shape[0] == 0 or region.shape[1] == 0:
raise ValueError(f"Invalid region size for FFT: {region.shape}")
f = np.fft.fft2(region)
fshift = np.fft.fftshift(f)
magnitude = np.abs(fshift)
normalized = normalize(magnitude, contrast)
fig, ax = plt.subplots(figsize=(4, 4), dpi=100)
ax.imshow(normalized, cmap='gray')
ax.axis('off')
buf = BytesIO()
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
buf.seek(0)
plt.close(fig)
return Image.open(buf)
def compute_fft_image_region(cropped: Image.Image, contrast=2.0) -> Image.Image:
"""
Compute FFT image from a cropped region.
Args:
cropped: PIL Image to process
contrast: Contrast parameter for normalization
Returns:
PIL Image of FFT
"""
arr = np.array(cropped.convert("L")).astype(np.float32)
return fft_image_with_matplotlib(arr, contrast)
def compute_average_fft(cropped: Image.Image, apix: float = 1.0) -> Image.Image:
"""
Compute the 1D rotational average of the 2D FFT from a cropped image.
Args:
cropped: A PIL.Image object (grayscale or RGB).
apix: Pixel size in Ångstrom per pixel.
Returns:
A PIL.Image containing the 1D plot of average FFT intensity vs. 1/resolution.
"""
arr = np.array(cropped.convert("L")).astype(np.float32)
f = np.fft.fft2(arr)
fshift = np.fft.fftshift(f)
magnitude = np.abs(fshift)
# Compute radial coordinates
cy, cx = np.array(magnitude.shape) // 2
y, x = np.indices(magnitude.shape)
r = np.sqrt((x - cx)**2 + (y - cy)**2)
r = r.astype(np.int32)
# Compute radial average
radial_sum = np.bincount(r.ravel(), magnitude.ravel())
radial_count = np.bincount(r.ravel())
radial_profile = radial_sum / (radial_count + 1e-8)
# Convert to spatial frequency
freqs = np.arange(len(radial_profile)) / (arr.shape[0] * apix)
inverse_resolution = freqs # in 1/Å
# Determine index range for 1/3.7 to 1/2
x_min, x_max = 1 / 3.7, 1 / 2.0
mask = (inverse_resolution >= x_min) & (inverse_resolution <= x_max)
# Plot
fig, ax = plt.subplots(dpi=100)
ax.plot(inverse_resolution[mask], np.log1p(radial_profile[mask]))
ax.set_xlim(x_min, x_max)
ax.set_ylim(radial_profile[mask].min(), radial_profile[mask].max())
ax.set_xlabel("1 / Resolution (1/Å)")
ax.set_ylabel("Log(Average FFT intensity)")
ax.set_title("1D FFT Radial Profile")
ax.grid(True)
# Save to PIL.Image
buf = BytesIO()
plt.tight_layout()
plt.savefig(buf, format='png')
plt.close(fig)
buf.seek(0)
return Image.open(buf)
def calculate_apix_from_distance(distance_pixels: float, resolution: float, size: int) -> float:
"""
Calculate apix from distance in pixels.
Args:
distance_pixels: Distance from center in pixels
resolution: Resolution in Angstroms
size: Image size in pixels
Returns:
Apix value in Å/pixel, or None if invalid
"""
if distance_pixels <= 0:
return None
return (distance_pixels * resolution) / size
def calculate_distance_from_apix(apix_value: float, resolution: float, size: int) -> float:
"""
Calculate distance in pixels from apix value.
Args:
apix_value: Apix value in Å/pixel
resolution: Resolution in Angstroms
size: Image size in pixels
Returns:
Distance from center in pixels, or None if invalid
"""
if apix_value <= 0:
return None
return (apix_value * size) / resolution
def calculate_tilt_angle(small_axis: float, large_axis: float) -> float:
"""
Calculate tilt angle from ellipse axes.
Args:
small_axis: Semi-minor axis length
large_axis: Semi-major axis length
Returns:
Tilt angle in radians
"""
if large_axis <= 0:
return 0.0
return math.acos(small_axis / large_axis)
def get_resolution_info(resolution_type: str, custom_resolution: float = None) -> tuple[float, str]:
"""
Get resolution value and color based on resolution type.
Args:
resolution_type: Type of resolution (Graphene, Gold, Ice, Custom)
custom_resolution: Custom resolution value if type is Custom
Returns:
Tuple of (resolution_value, color)
"""
if resolution_type == "Graphene (2.13 Å)":
return 2.13, "red"
elif resolution_type == "Gold (2.355 Å)":
return 2.355, "orange"
elif resolution_type == "Ice (3.661 Å)":
return 3.661, "blue"
elif resolution_type == "Custom":
return custom_resolution, "green"
return None, None
def resolution_to_radius(res_angstrom: float, image_size: int, apix: float) -> float:
"""
Calculate radius in pixels from resolution in Angstroms.
Args:
res_angstrom: Resolution in Angstroms
image_size: Image size in pixels
apix: Pixel size in Å/pixel
Returns:
Radius in pixels
"""
return (image_size * apix) / res_angstrom
def get_image(filename: str, target_apix: float = None, low_pass_angstrom: float = 0, high_pass_angstrom: float = 0) -> tuple[np.ndarray, float, float]:
"""
Load and process an image file (MRC, TIFF, PNG, etc.) with optional filtering.
Args:
filename: Path to the image file
target_apix: Target pixel size in Angstroms (if None, use original)
low_pass_angstrom: Low-pass filter in Angstroms (0 = no filter)
high_pass_angstrom: High-pass filter in Angstroms (0 = no filter)
Returns:
Tuple of (processed_data, target_apix, original_apix)
"""
# Load the image
if filename.lower().endswith('.mrc'):
with mrcfile.open(filename) as mrc:
original_apix = round(float(mrc.voxel_size.x), 4)
data = mrc.data.squeeze()
else:
# For other formats, assume 1 Å/pixel if not specified
original_apix = 1.0
img = Image.open(filename)
data = np.array(img.convert("L")).astype(np.float32)
# If no target apix specified, use original
if target_apix is None:
target_apix = original_apix
ny, nx = data.shape
# Resize if target apix is different
if abs(target_apix - original_apix) > 1e-6:
new_ny = int(ny * original_apix / target_apix + 0.5) // 2 * 2
new_nx = int(nx * original_apix / target_apix + 0.5) // 2 * 2
data = resize_local_mean(image=data, output_shape=(new_ny, new_nx))
# Apply filters if specified
if low_pass_angstrom > 0 or high_pass_angstrom > 0:
# Simple frequency domain filtering
f = np.fft.fft2(data)
fshift = np.fft.fftshift(f)
# Create frequency mask
cy, cx = np.array(fshift.shape) // 2
y, x = np.indices(fshift.shape)
r = np.sqrt((x - cx)**2 + (y - cy)**2)
# Low-pass filter
if low_pass_angstrom > 0:
low_pass_freq = 2 * target_apix / low_pass_angstrom
low_pass_mask = r <= low_pass_freq
fshift = fshift * low_pass_mask
# High-pass filter
if high_pass_angstrom > 0:
high_pass_freq = 2 * target_apix / high_pass_angstrom
high_pass_mask = r >= high_pass_freq
fshift = fshift * high_pass_mask
# Inverse FFT
f_ishift = np.fft.ifftshift(fshift)
data = np.real(np.fft.ifft2(f_ishift))
return data, target_apix, original_apix
def plot_image(image_data: np.ndarray, title: str, apix: float, plot_height: int = None, plot_width: int = None) -> 'plotly.graph_objects.Figure':
"""
Create a Plotly heatmap figure for displaying image data using plotly.express.imshow.
"""
# Normalize the image data using percentile-based clipping for robust display
# This ensures images with different intensity ranges display correctly
normalized_data = normalize_image(image_data, use_percentiles=True, low_percentile=1.0, high_percentile=99.0)
fig = px.imshow(
normalized_data,
color_continuous_scale="gray",
aspect="equal", # Force square aspect ratio
origin="upper",
labels=dict(x="", y="", color=""),
)
# Hide axes and colorbar
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
fig.update_coloraxes(showscale=False)
# Remove title if not provided
if title and title.strip():
fig.update_layout(title=title)
else:
fig.update_layout(title=None)
# Set autosize and margins
fig.update_layout(
autosize=True,
width=plot_width,
height=plot_height,
margin=dict(l=0, r=0, t=0, b=0),
plot_bgcolor="white",
)
# Enable zoom and selection interactions
fig.update_layout(
dragmode='zoom',
modebar=dict(
add=['zoom', 'pan', 'reset+autorange', 'select2d', 'lasso2d']
)
)
return fig
def create_fft_1d_plotly_figure(plot_data: dict, resolution: float, region: Image.Image,
size: int, zoom_state: dict, shared_x_range=None) -> 'plotly.graph_objects.Figure':
"""
Create a Plotly figure for the 1D FFT radial profile.
Args:
plot_data: Dictionary containing plot data from compute_fft_1d_data
resolution: Current resolution value
region: Current image region
size: Image size constant
zoom_state: Current zoom state dictionary
Returns:
Plotly Figure object
"""
if plot_data is None:
return go.Figure()
# Create plotly figure
fig = go.Figure()
# Add main trace with custom hover text
hover_text = []
for i, x_val in enumerate(plot_data['x_data']):
# Check if x_val is spatial frequency or radius
if 'target_resolution' in plot_data:
# This is from non-uniform FFT, x_val is spatial frequency (1/Å)
if x_val > 0:
resolution_val = 1 / x_val
resolution_str = f"{resolution_val:.2f} Å"
freq_str = f"{x_val:.4f} Å⁻¹"
# Calculate corresponding apix for the target resolution
if region is not None:
region_size = region.size[0] if hasattr(region, 'size') else region.shape[0]
# For non-uniform FFT, we need to estimate the equivalent radius
# Using the target resolution from plot_data
target_res = plot_data.get('target_resolution', resolution_val)
equivalent_radius = (region_size * plot_data.get('nominal_apix', 1.0)) / target_res
apix_value = (equivalent_radius * resolution_val) / region_size
apix_str = f"{apix_value:.3f} Å/px"
else:
apix_str = "N/A"
else:
resolution_str = "∞ Å"
freq_str = f"{x_val:.4f} Å⁻¹"
apix_str = "N/A"
# Create hover info with spatial frequency, resolution, and apix
hover_info = f"Spatial frequency: {freq_str}<br>Resolution: {resolution_str}<br>Apix: {apix_str}"
else:
# This is from traditional FFT, x_val is radius in pixels
if resolution is not None and x_val > 0:
if region is not None:
region_size = region.size[0] # Unbinned region size
# x_val is in unbinned FFT pixel coordinates
fft_radius = x_val
# Calculate apix using the correct formula for unbinned coordinates
apix_value = (fft_radius * resolution) / region_size
apix_str = f"{apix_value:.3f}"
else:
apix_str = "N/A"
else:
apix_str = "N/A"
# Create hover info with radius and apix
hover_info = f"Radius: {x_val:.1f} pixels<br>Apix: {apix_str} Å/px"
hover_text.append(hover_info)
fig.add_trace(go.Scatter(
x=plot_data['x_data'],
y=plot_data['y_data'],
mode='lines',
name=plot_data['profile_label'],
line=dict(color='blue', width=2),
hovertemplate='%{text}<extra></extra>',
text=hover_text
))
# Set axis limits based on shared range, zoom state, or defaults
if shared_x_range is not None:
xlim = shared_x_range
elif zoom_state['x_range'] is not None and zoom_state['y_range'] is not None:
xlim = zoom_state['x_range']
ylim = zoom_state['y_range']
else:
xlim = (plot_data['x_min'], plot_data['x_max'])
# Set y limits if not already set
if 'ylim' not in locals():
# Calculate y limits
y_min = plot_data['y_data'].min()
y_max = plot_data['y_data'].max()
if y_max > y_min:
y_range = y_max - y_min
if y_range > 0:
ylim = (y_min - y_range * 0.1, y_max + y_range * 0.1)
else:
ylim = (y_min, y_max * 1.1)
else:
if y_max > 0:
ylim = (y_max * 0.9, y_max * 1.1)
else:
ylim = (-0.1, 0.1)
# Update layout with hover functionality
# Set x-axis title and formatting based on data type
if 'target_resolution' in plot_data:
x_axis_title = "Spatial frequency (1/Res)"
# Create custom tick values and labels for 1/Res format
x_min, x_max = xlim
# Generate reasonable tick positions
n_ticks = 6 # Number of ticks
tick_vals = np.linspace(x_min, x_max, n_ticks)
tick_text = []
for val in tick_vals:
if val > 0:
res = 1 / val
tick_text.append(f"1/{res:.2f}")
else:
tick_text.append("1/∞")
xaxis_config = dict(
range=xlim,
showgrid=True,
matches='x',
tickvals=tick_vals,
ticktext=tick_text,
tickmode='array'
)
else:
x_axis_title = "Radius (pixels)"
xaxis_config = dict(range=xlim, showgrid=True, matches='x')
fig.update_layout(
title="1D FFT Radial Profile",
xaxis_title=x_axis_title,
yaxis_title=plot_data['y_axis_title'],
xaxis=xaxis_config,
yaxis=dict(range=ylim, showgrid=True),
showlegend=True,
legend=dict(x=0.02, y=0.02, xanchor='left', yanchor='bottom'),
height=200,
width=650, # Fixed width to match other plots
margin=dict(l=60, r=20, t=60, b=60),
autosize=False,
hovermode="x unified"
)
return fig
def compute_fft_polar_heatmap_data(region: Image.Image, apix: float, resolution_type: str = None,
custom_resolution: float = None, use_for_range: bool = True) -> dict:
"""
Calculate polar heatmap data for FFT profile near radius of interest.
Args:
region: Image region to analyze
apix: Pixel size in Å/pixel (used for radius range calculation)
resolution_type: Type of resolution for position calculation
custom_resolution: Custom resolution value
use_for_range: Whether to use this apix for range calculation (vs just returning info)
Returns:
Dictionary containing polar heatmap data
"""
# Compute FFT and get power spectrum
arr = np.array(region.convert("L")).astype(np.float32)
# Validate array size
if arr.size == 0 or arr.shape[0] == 0 or arr.shape[1] == 0:
raise ValueError(f"Invalid region size for FFT: {arr.shape}")
f = np.fft.fft2(arr)
fshift = np.fft.fftshift(f)
pwr = np.abs(fshift)
cy, cx = np.array(pwr.shape) // 2
# Get expected radius based on resolution
if resolution_type and resolution_type != "Custom":
resolution_map = {
"Graphene (100)": 2.13,
"Graphene (110)": 1.23,
"Gold (111)": 2.35,
"Gold (200)": 2.04,
"Gold (220)": 1.44
}
resolution = resolution_map.get(resolution_type, 2.13)
else:
resolution = custom_resolution if custom_resolution else 2.13
# Calculate expected radius in pixels using unbinned coordinates
# Use the actual region size for accurate calculations
region_size = arr.shape[0]
expected_radius = resolution_to_radius(resolution, region_size, apix)
# Match the 1D FFT range: 10% to 75% of total radius
total_radius = min(cy, cx)
r_min = max(1, int(total_radius * 0.1)) # Start from 10% of total radius
r_max = int(total_radius * 0.75) # End at 75% of total radius
# Create angular and radial coordinates
angles = np.linspace(0, 360, 360, endpoint=False) # 0-360 degrees
radii = np.arange(r_min, r_max + 1)
# Create the heatmap data (angles x radii for correct axis orientation)
heatmap_data = np.zeros((len(angles), len(radii)))
for i, angle in enumerate(angles):
for j, r in enumerate(radii):
# Convert polar to cartesian
theta = np.radians(angle)
x = cx + r * np.cos(theta)
y = cy + r * np.sin(theta)
# Bilinear interpolation for sub-pixel accuracy
x0, x1 = int(np.floor(x)), int(np.ceil(x))
y0, y1 = int(np.floor(y)), int(np.ceil(y))
# Check bounds
if (x0 >= 0 and x1 < pwr.shape[1] and y0 >= 0 and y1 < pwr.shape[0]):
# Bilinear interpolation weights
wx = x - x0
wy = y - y0
# Interpolate
intensity = (1-wx)*(1-wy)*pwr[y0,x0] + wx*(1-wy)*pwr[y0,x1] + \
(1-wx)*wy*pwr[y1,x0] + wx*wy*pwr[y1,x1]
heatmap_data[i, j] = intensity
return {
'heatmap_data': heatmap_data,
'angles': angles,
'radii': radii,
'expected_radius': expected_radius,
'resolution': resolution
}
def compute_fft_1d_data(region: Image.Image, apix: float, use_mean_profile: bool = False,
log_y: bool = False, smooth: bool = False, window_size: int = 3,
detrend: bool = False, resolution_type: str = None,
custom_resolution: float = None) -> dict:
"""
Calculate the data needed for the 1D FFT plot.
Args:
region: Image region to analyze
apix: Pixel size in Å/pixel
use_mean_profile: Whether to use mean or max profile
log_y: Whether to use log scale for y-axis
smooth: Whether to apply smoothing
window_size: Window size for smoothing
detrend: Whether to detrend the signal
resolution_type: Type of resolution for position calculation
custom_resolution: Custom resolution value
Returns:
Dictionary containing plot data
"""
# Compute FFT and get power spectrum
arr = np.array(region.convert("L")).astype(np.float32)
# Validate array size to prevent FFT errors
if arr.size == 0 or arr.shape[0] == 0 or arr.shape[1] == 0:
raise ValueError(f"Invalid region size for FFT: {arr.shape}")
f = np.fft.fft2(arr)
fshift = np.fft.fftshift(f)
pwr = np.abs(fshift) # Power spectrum
if use_mean_profile:
# Compute radial average profile
cy, cx = np.array(pwr.shape) // 2
y, x = np.indices(pwr.shape)
r = np.sqrt((x - cx)**2 + (y - cy)**2)
r = r.astype(np.int32)
radial_sum = np.bincount(r.ravel(), pwr.ravel())
radial_count = np.bincount(r.ravel())
pwr_1d = radial_sum / (radial_count + 1e-8)
profile_label = "FFT radial average"
else:
# Calculate radial max profile - max value at each radius
cy, cx = np.array(pwr.shape) // 2
y, x = np.indices(pwr.shape)
r = np.sqrt((x - cx)**2 + (y - cy)**2)
r = r.astype(np.int32)
# Find max value at each radius
max_radial = np.zeros(r.max() + 1)
for radius in range(r.max() + 1):
mask = (r == radius)
if np.any(mask):
max_radial[radius] = np.max(pwr[mask])
pwr_1d = max_radial
profile_label = "FFT radial max"
# Use radius in pixels as x-axis
radius_pixels = np.arange(len(pwr_1d))
# Set x-axis limits to start from 10% of the total radius
x_min = int(len(pwr_1d) * 0.1) # Start from 10% of total radius
x_max = int(len(pwr_1d) * 0.75) # Keep the upper limit
mask = (radius_pixels >= x_min) & (radius_pixels <= x_max)
# Plot data
y_data = pwr_1d[mask]
# Ensure we have valid data
if len(y_data) == 0 or np.all(y_data == 0):
# Fallback: create a simple plot with some data
y_data = np.ones_like(radius_pixels[mask])
if log_y:
y_data = np.log1p(y_data) # log1p is safe for positive values
y_axis_title = "Log(FFT intensity)"
else:
y_axis_title = "FFT intensity"
# Apply smoothing to y_data using a moving average
if smooth:
kernel = np.ones(window_size) / window_size
# Determine padding amount for mode='same'
pad_amount = (len(kernel) - 1) // 2
# Pad the signal with 'reflect' mode
padded_y_data = np.pad(y_data, pad_width=pad_amount, mode='reflect')
# Perform convolution with the padded signal
y_data = np.convolve(padded_y_data, kernel, mode='valid')
y_data = y_data - y_data.min()
# Detrend the signal by fitting and subtracting a linear baseline
if detrend:
# Fit a first-degree polynomial to get trend
m, b = np.polyfit(radius_pixels[mask], y_data, 1)
# Compute and subtract baseline
baseline = m * radius_pixels[mask] + b
y_data = y_data - baseline
# Shift back to positive values
y_data = y_data - y_data.min()
# Calculate expected resolution positions for hover information
resolution_positions = {}
resolution, _ = get_resolution_info(resolution_type, custom_resolution)
if resolution is not None:
if resolution_type == "Graphene (2.13 Å)":
radius_213 = (arr.shape[0] * apix) / 2.13
if x_min <= radius_213 <= x_max:
resolution_positions['graphene'] = radius_213
elif resolution_type == "Gold (2.355 Å)":
radius_235 = (arr.shape[0] * apix) / 2.355
if x_min <= radius_235 <= x_max:
resolution_positions['gold'] = radius_235
elif resolution_type == "Ice (3.661 Å)":
radius_366 = (arr.shape[0] * apix) / 3.661
if x_min <= radius_366 <= x_max:
resolution_positions['ice'] = radius_366
elif resolution_type == "Custom":
radius_custom = (arr.shape[0] * apix) / custom_resolution
if x_min <= radius_custom <= x_max:
resolution_positions['custom'] = radius_custom
# Use unbinned coordinates for accurate apix calculations
return {
'x_data': radius_pixels[mask],
'y_data': y_data,
'profile_label': profile_label,
'y_axis_title': y_axis_title,
'x_min': x_min,
'x_max': x_max,
'arr_shape': arr.shape,
'resolution_positions': resolution_positions
}
def bin_image(image_data: np.ndarray, target_size: int = 1000) -> np.ndarray:
"""
Bin an image to approximately target_size x target_size pixels.
Args:
image_data: Input image array
target_size: Target size for the binned image
Returns:
Binned image array
"""
h, w = image_data.shape
# Calculate binning factor to get close to target size
bin_factor = max(1, int(min(h, w) / target_size))
# Calculate new dimensions
new_h = h // bin_factor
new_w = w // bin_factor
# Use resize_local_mean for high-quality downsampling
binned_data = resize_local_mean(image=image_data, output_shape=(new_h, new_w))
return binned_data
def get_image_with_binning(filename: str, target_size: int = 1000, target_apix: float = None,
low_pass_angstrom: float = 0, high_pass_angstrom: float = 0) -> tuple[np.ndarray, float, float, np.ndarray]:
"""
Load and process an image file with binning for display.
Args:
filename: Path to the image file
target_size: Target size for binned image (default 1000)
target_apix: Target pixel size in Angstroms (if None, use original)
low_pass_angstrom: Low-pass filter in Angstroms (0 = no filter)
high_pass_angstrom: High-pass filter in Angstroms (0 = no filter)
Returns:
Tuple of (original_data, binned_data, target_apix, original_apix)
"""
# Load the original image
if filename.lower().endswith('.mrc'):
with mrcfile.open(filename) as mrc:
original_apix = round(float(mrc.voxel_size.x), 4)
original_data = mrc.data.squeeze()
else:
# For other formats, assume 1 Å/pixel if not specified
original_apix = 1.0
img = Image.open(filename)
original_data = np.array(img.convert("L")).astype(np.float32)
# If no target apix specified, use original
if target_apix is None:
target_apix = original_apix
# Apply filters to original data if specified
if low_pass_angstrom > 0 or high_pass_angstrom > 0:
# Simple frequency domain filtering
f = np.fft.fft2(original_data)
fshift = np.fft.fftshift(f)
# Create frequency mask
cy, cx = np.array(fshift.shape) // 2
y, x = np.indices(fshift.shape)
r = np.sqrt((x - cx)**2 + (y - cy)**2)
# Low-pass filter
if low_pass_angstrom > 0:
low_pass_freq = 2 * target_apix / low_pass_angstrom
low_pass_mask = r <= low_pass_freq
fshift = fshift * low_pass_mask
# High-pass filter
if high_pass_angstrom > 0:
high_pass_freq = 2 * target_apix / high_pass_angstrom
high_pass_mask = r >= high_pass_freq
fshift = fshift * high_pass_mask
# Inverse FFT
f_ishift = np.fft.ifftshift(fshift)
original_data = np.real(np.fft.ifft2(f_ishift))
# Create binned version for display
binned_data = bin_image(original_data, target_size)
return original_data, binned_data, target_apix, original_apix
def extract_region_from_original(original_data: np.ndarray, binned_data: np.ndarray,
x_range: tuple, y_range: tuple, target_size: int = 1000) -> np.ndarray:
"""
Extract a region from the original image based on zoom coordinates from binned image.
Args:
original_data: Original full-resolution image data
binned_data: Binned image data used for display
x_range: (x_min, x_max) in binned image coordinates
y_range: (y_min, y_max) in binned image coordinates
target_size: Target size for FFT calculation
Returns:
Extracted region as numpy array
"""
orig_h, orig_w = original_data.shape
binned_h, binned_w = binned_data.shape
# Calculate scale factors