-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhi3d.py
1647 lines (1480 loc) · 79.8 KB
/
hi3d.py
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
"""
MIT License
Copyright (c) 2020-2024 Wen Jiang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
def import_with_auto_install(packages, scope=locals()):
if isinstance(packages, str): packages=[packages]
for package in packages:
if package.find(":")!=-1:
package_import_name, package_pip_name = package.split(":")
else:
package_import_name, package_pip_name = package, package
try:
scope[package_import_name] = __import__(package_import_name)
except ImportError:
import subprocess
subprocess.call(f'pip install {package_pip_name}', shell=True)
scope[package_import_name] = __import__(package_import_name)
required_packages = "streamlit numpy scipy bokeh trackpy kneebow".split()
import_with_auto_install(required_packages)
import streamlit as st
import numpy as np
np.bool8 = bool # fix for bokeh 2.4.3
from scipy.ndimage import map_coordinates
import math, random
import gc
gc.enable()
#from memory_profiler import profile
#@profile(precision=4)
def main():
title = "HI3D: Helical indexing using the cylindrical projection of a 3D map"
st.set_page_config(page_title=title, layout="wide")
hosted, host = is_hosted(return_host=True)
if hosted and host in ['heroku']:
st.error(f"This app hosted on Heroku will be unavailable starting November 28, 2022 [when Heroku discontinues free hosting service](https://blog.heroku.com/next-chapter). Please switch to [the same app hosted elsewhere](https://helical-indexing-hi3d.streamlit.app)")
st.title(title)
if "input_mode" not in st.session_state: # only run once at the start of the session
parse_query_parameters()
if is_hosted():
max_map_size = mem_quota()/2 # MB
max_map_dim = int(pow(max_map_size*pow(2, 20)/4, 1./3.)//10*10) # pixels in any dimension
stop_map_size = mem_quota()*0.75 # MB
else:
max_map_size = -1 # no limit
max_map_dim = -1
if max_map_size>0:
warning_map_size = f"Due to the resource limit ({mem_quota():.1f} MB memory cap) of the hosting service, the maximal map size should be {max_map_size:.1f} MB ({max_map_dim}x{max_map_dim}x{max_map_dim} voxels) or less to avoid crashing the server process"
msg_hint = f"There are a few things you can try: \n"
msg_hint+= f"· Ensure the map is vertical along Z-axis and centered in XY plane \n"
msg_hint+= f"· Change \"Axial step size\" to a larger value (1 → 2 or 3 Å) for large rise structures or a smaller value (1 → 0.2 Å) for small rise structures (for example, amyloids) \n"
msg_hint+= f"· Change \"Peak width\" and \"Peak height\" to approximate the size/shape of the peaks in the autocorrelation image \n"
msg_hint+= f"· Manually inspect the autocorrelation image at the center of the screen, use mouse hover tips to reveal the corresponding twist/rise values at the pixel under the mouse pointer \n"
col1, col2, col3, col4 = st.columns((1.0, 3.2, 0.6, 1.15))
msg_empty = col2.empty()
with col1:
with st.expander(label="README", expanded=False):
st.write("This Web app considers a biological helical structure as a 2D crystal that has been rolled up into a cylindrical tube while preserving the original lattice. The indexing process is thus to computationally reverse this process: the 3D helical structure is first unrolled into a 2D image using cylindrical projection, and then the 2D lattice parameters are automatically identified from which the helical parameters (twist, rise, and cyclic symmetry) are derived. The auto-correlation function (ACF) of the cylindrical projection is used to produce a lattice with sharper peaks. Two distinct lattice identification methods, one for generical 2D lattices and one specifically for helical lattices, are used to find a consistent solution. \n \nTips: play with the rmin/rmax, #peaks, axial step size parameters if consistent helical parameters cannot be obtained with the default parameters. Use a larger axial step size (for example 2Å) for a structure with large rise. Use a smaller axial step size (for example 0.2Å) for a structure (such Tau fibril) with small rise.")
data = None
da_auto = 1.0
dz_auto = 1.0
input_modes = {0:"upload", 1:"url", 2:"emd-xxxxx"}
help = "Only maps in MRC (.mrc) or CCP4 (.map) format are supported. Compressed maps (.gz) will be automatically decompressed"
if max_map_size>0: help += f". {warning_map_size}"
input_mode = st.radio(label="How to obtain the input map:", options=list(input_modes.keys()), format_func=lambda i:input_modes[i], index=2, horizontal=True, help=help, key="input_mode")
is_emd = False
emdb_ids_all, emdb_ids_helical, methods = get_emdb_ids()
if input_mode == 0: # "upload a MRC file":
label = "Upload a map in MRC or CCP4 format"
help = None
if max_map_size>0: help = warning_map_size
fileobj = st.file_uploader(label, type=['mrc', 'map', 'map.gz'], help=help, key="file_upload")
if fileobj is not None:
emd_id = extract_emd_id(fileobj.name)
is_emd = emd_id is not None and emd_id in emdb_ids_helical
data, map_crs, apix = get_3d_map_from_uploaded_file(fileobj)
nz, ny, nx = data.shape
if nz<32:
st.warning(f"The uploaded file {fileobj.name} ({nx}x{ny}x{nz}) is not a 3D map")
data = None
elif input_mode == 1: # "url":
url_default = get_emdb_map_url("emd-10499")
help = "An online url (http:// or ftp://) or a local file path (/path/to/your/structure.mrc)"
if max_map_size>0: help += f". {warning_map_size}"
url = st.text_input(label="Input the url of a 3D map:", value=url_default, help=help, key="url")
emd_id = extract_emd_id(url)
is_emd = emd_id is not None and emd_id in emdb_ids_helical
data, map_crs, apix = get_3d_map_from_url(url.strip())
nz, ny, nx = data.shape
if nz<32:
st.warning(f"{url} points to a file ({nx}x{ny}x{nz}) that is not a 3D map")
data = None
elif input_mode == 2:
if not emdb_ids_all:
st.warning("failed to obtained a list of helical structures in EMDB")
return
url = "https://www.ebi.ac.uk/emdb/search/*%20AND%20structure_determination_method:%22helical%22?rows=10&sort=release_date%20desc"
st.markdown(f'[All {len(emdb_ids_helical)} helical structures in EMDB]({url})')
emd_id_default = "emd-10499"
help = "Randomly select another helical structure in EMDB"
if max_map_size>0: help += f". {warning_map_size}"
button_clicked = st.button(label="Change EMDB ID", help=help)
if button_clicked:
import random
st.session_state.emd_id = 'emd-' + random.choice(emdb_ids_helical)
help = None
if max_map_size>0: help = warning_map_size
label = "Input an EMDB ID (emd-xxxxx):"
emd_id = st.text_input(label=label, value=emd_id_default, key='emd_id', help=help)
emd_id = emd_id.lower().split("emd-")[-1]
if emd_id not in emdb_ids_all:
import random
msg = f"EMD-{emd_id} is not a valid EMDB entry. Please input a valid id (for example, a randomly selected valid id 'emd-{random.choice(emdb_ids_helical)}')"
st.warning(msg)
return
elif emd_id not in emdb_ids_helical:
msg= f"EMD-{emd_id} is in EMDB but annotated as a '{methods[emdb_ids_all.index(emd_id)]}' structure, not a helical structure"
st.warning(msg)
params = get_emdb_parameters(emd_id)
if params is None:
msg = f"EMD-{emd_id}: could not retrieve information"
st.warning(msg)
return
resolution = params['resolution']
msg = f'[EMD-{emd_id}](https://www.ebi.ac.uk/emdb/entry/EMD-{emd_id}) | resolution={resolution}Å'
if max_map_size>0 and params and "nz" in params and "ny" in params and "nx" in params:
nz = params["nz"]
ny = params["ny"]
nx = params["nx"]
map_size = nz*ny*nx*4 / pow(2, 20)
if map_size>stop_map_size:
msg_map_too_large = f"As the map size ({map_size:.1f} MB, {nx}x{ny}x{nz} voxels) is too large for the resource limit ({mem_quota():.1f} MB memory cap) of the hosting service, HI3D will stop analyzing it to avoid crashing the server. Please bin/crop your map so that it is {max_map_size} MB ({max_map_dim}x{max_map_dim}x{max_map_dim} voxels) or less, and then try again. Please check the [HI3D web site](https://jiang.bio.purdue.edu/hi3d) to learn how to run HI3D on your local computer with larger memory to support large maps"
msg_empty.warning(msg_map_too_large)
st.stop()
if params and is_amyloid(params, cutoff=6):
dz_auto = 0.2
if params and "twist" in params and "rise" in params:
msg += f" \ntwist={params['twist']}° | rise={params['rise']}Å"
if "csym" in params: msg += f" | c{params['csym']}"
else:
msg += " \n*helical params not available*"
st.markdown(msg)
data, map_crs, apix = get_emdb_map(emd_id)
if data is None:
st.warning(f"Failed to download [EMD-{emd_id}](https://www.ebi.ac.uk/emdb/entry/EMD-{emd_id})")
return
is_emd = emd_id in emdb_ids_helical
if data is None:
return
if map_crs != [1, 2, 3]:
map_crs_to_xyz = {1:'x', 2:'y', 3:'z'}
xyz = ','.join([map_crs_to_xyz[int(i)] for i in map_crs])
label = f":red[Change map axes order from {xyz} to:]"
st.text_input(label=label, value="x,y,z", max_chars=5, help=f"Cryo-EM field assumes that the map axes are in the order of x,y,z (e.g. MRC/CCP4 header fields mapc=1, mapr=2, maps=3). However, you map header has a different order {xyz} (mapc={map_crs[0]}, mapr={map_crs[1]}, maps={map_crs[2]})", key="target_map_axes_order")
try:
target_map_axes_order = st.session_state.target_map_axes_order.lower().split(",")
assert len(target_map_axes_order) == 3
xyz_to_map_crs = {'x':1, 'y':2, 'z':3}
target_map_crs = [xyz_to_map_crs[a] for a in target_map_axes_order]
except:
st.warning(f"Incorrect value {st.session_state.target_map_axes_order}. I will use the default value x,y,z")
target_map_crs = [1, 2, 3]
data = change_mrc_map_crs_order(data=data, current_order=map_crs, target_order=target_map_crs)
nz, ny, nx = data.shape
st.markdown(f'{nx}x{ny}x{nz} voxels | {round(apix,4):g} Å/voxel')
if max_map_size>0:
map_size = nz*ny*nx*4 / pow(2, 20)
if map_size>stop_map_size:
msg_map_too_large = f"As the map size ({map_size:.1f} MB, {nx}x{ny}x{nz} voxels) is too large for the resource limit ({mem_quota():.1f} MB memory cap) of the hosting service, HI3D will stop analyzing it to avoid crashing the server. Please bin/crop your map so that it is {max_map_size} MB ({max_map_dim}x{max_map_dim}x{max_map_dim} voxels) or less, and then try again. Please check the [HI3D web site](https://jiang.bio.purdue.edu/hi3d) to learn how to run HI3D on your local computer with larger memory to support large maps"
msg_empty.warning(msg_map_too_large)
st.stop()
elif map_size>max_map_size:
reduce_map_size = st.checkbox(f"Reduce map size to < {max_map_size} MB", value=True, key="reduce_map_size")
if reduce_map_size:
data_small, bin = minimal_grids(data, max_map_dim)
del data
data = data_small * 1.0
del data_small
apix *= bin
nz, ny, nx = data.shape
st.markdown(f'{nx}x{ny}x{nz} voxels | {round(apix,4):g} Å/voxel')
else:
msg = f"{warning_map_size}. If this map ({map_size:.1f}>{max_map_size } MB) indeed crashes the server process, please reduce the map size by binning the map or cropping the empty padding space around the structure, and then try again. If the crashing persists, please check the [HI3D web site](https://jiang.bio.purdue.edu/hi3d) to learn how to run HI3D on your local computer with larger memory to support large maps"
msg_empty.warning(msg)
vmin, vmax = data.min(), data.max()
if vmin == vmax:
st.warning(f"The map is blank: min={vmin} max={vmax}. Please provide a meaningful 3D map")
st.stop()
axis_mapping = {3:'X/Y', 2:'X', 1:'Y', 0:'Z'}
section_axis = st.radio(label="Display a section along this axis:", options=list(axis_mapping.keys()), format_func=lambda i:axis_mapping[i], index=0, horizontal=True, key="section_axis")
mapping = {0:nz, 1:ny, 2:nx, 3:min(nx,ny)}
n = mapping[section_axis]
section_index = st.slider(label="Choose a section to display:", min_value=-n//2, max_value=n-n//2-1, value=0, step=1)
section_index += n//2
container_image = st.container()
expanded = False if is_emd else True
with st.expander(label="Transform the map", expanded=expanded):
do_threshold = st.checkbox("Threshold the map", value=False, key="do_threshold")
if do_threshold:
data_min, data_max = float(data.min()), float(data.max())
background = np.mean(data[[0,1,2,-3,-2,-1],[0,1,2,-3,-2,-1]])
thresh_auto = (data_max-background) * 0.2 + background
thresh = st.number_input(label="Minimal voxel value:", min_value=data_min, max_value=data_max, value=float(round(thresh_auto,6)), step=float((data_max-data_min)/1000.), format="%g", key="thresh")
else:
thresh = None
if thresh is not None:
data = data * 1.0
data[data<thresh] = 0
do_transform = st.checkbox("Center & verticalize", value= not (is_emd or is_hosted()), key="do_transform")
if do_transform:
with st.form("do_transform_form"):
rotx_auto, shifty_auto = auto_vertical_center(np.sum(data, axis=2))
roty_auto, shiftx_auto = auto_vertical_center(np.sum(data, axis=1))
if "rotx" in st.session_state: rotx_auto = st.session_state.rotx
if "roty" in st.session_state: roty_auto = st.session_state.roty
if "shiftx" in st.session_state: shiftx_auto = st.session_state.shiftx/apix # unit: pixel
if "shifty" in st.session_state: shifty_auto = st.session_state.shifty/apix # unit: pixel
rotx = st.number_input(label="Rotate map around X-axis (°):", min_value=-90., max_value=90., value=round(rotx_auto,2), step=1.0, format="%g", key="rotx")
roty = st.number_input(label="Rotate map around Y-axis (°):", min_value=-90., max_value=90., value=round(roty_auto,2), step=1.0, format="%g", key="roty")
shiftx = st.number_input(label="Shift map along X-axis (Å):", min_value=-nx//2*apix, max_value=nx//2*apix, value=round(min(max(-nx//2*apix, shiftx_auto*apix), nx//2*apix), 2), step=1.0, format="%g", key="shiftx") # unit: Å
shifty = st.number_input(label="Shift map along Y-axis (Å):", min_value=-ny//2*apix, max_value=ny//2*apix, value=round(min(max(-ny//2*apix, shifty_auto*apix), ny//2*apix), 2), step=1.0, format="%g", key="shifty") # unit: Å
shiftz = st.number_input(label="Shift map along Z-axis (Å):", min_value=-nz//2*apix, max_value=nz//2*apix, value=0.0, step=1.0, format="%g", key="shiftz")
st.form_submit_button("Submit")
else:
rotx, roty, shiftx, shifty, shiftz = 0., 0., 0., 0., 0.
if section_axis == 3:
image = np.zeros((nz, max(ny, nx)), dtype=data.dtype)
image_x = np.squeeze(np.take(data, indices=[section_index], axis=2))
image_y = np.squeeze(np.take(data, indices=[section_index], axis=1))
image[:, :ny//2] = image_x[:, :ny//2]
image[:, -nx//2:] = image_y[:, nx//2:]
image[:, ny//2-1] = np.max(image)
else:
image = np.squeeze(np.take(data, indices=[section_index], axis=section_axis))
h, w = image.shape
if thresh is not None or rotx or roty or shiftx or shifty or shiftz:
data = transform_map(data, shift_x=shiftx/apix, shift_y=-shifty/apix, shift_z=-shiftz/apix, angle_x=-rotx, angle_y=-roty)
if section_axis == 3:
image2 = np.squeeze(np.take(data, indices=[section_index], axis=2))
image2_y = np.squeeze(np.take(data, indices=[section_index], axis=1))
image2[:, ny//2:]= image2_y[:, nx//2:]
image2[:, ny//2-1] = 0
else:
image2 = np.squeeze(np.take(data, indices=[section_index], axis=section_axis))
with container_image:
tooltips = [("x", "$x"), ('y', '$y'), ('val', '@image')]
fig1 = generate_bokeh_figure(image, apix, apix, title=f"Original", title_location="below", plot_width=None, plot_height=None, x_axis_label=None, y_axis_label=None, tooltips=tooltips, show_angle_tooltip=True, show_axis=False, show_toolbar=False, crosshair_color="white", aspect_ratio=w/h)
fig2 = generate_bokeh_figure(image2, apix, apix, title=f"Transformed", title_location="below", plot_width=None, plot_height=None, x_axis_label=None, y_axis_label=None, tooltips=tooltips, show_angle_tooltip=True, show_axis=False, show_toolbar=False, crosshair_color="white", aspect_ratio=w/h)
from bokeh.plotting import figure
x = (np.arange(0, w)-w//2) * apix
ymax = np.max(image2, axis=0)
ymean = np.mean(image2, axis=0)
fig4 = figure(x_axis_label=None, y_axis_label=None, x_range=fig2.x_range, aspect_ratio=3)
fig4.line(x, ymax, line_width=2, color='red', legend_label="max")
fig4.line(-x, ymax, line_width=2, color='red', line_dash="dashed", legend_label="max flipped")
fig4.line(x, ymean, line_width=2, color='blue', legend_label="mean")
fig4.line(-x, ymean, line_width=2, color='blue', line_dash="dashed", legend_label="mean flipped")
fig4.xaxis.visible = False
fig4.yaxis.visible = False
fig4.legend.visible=False
fig4.toolbar_location = None
ymax = np.max(image, axis=0)
ymean = np.mean(image, axis=0)
fig3 = figure(x_axis_label=None, y_axis_label=None, x_range=fig1.x_range, aspect_ratio=3)
fig3.line(x, ymax, line_width=2, color='red', legend_label="max")
fig3.line(-x, ymax, line_width=2, color='red', line_dash="dashed", legend_label="max flipped")
fig3.line(x, ymean, line_width=2, color='blue', legend_label="mean")
fig3.line(-x, ymean, line_width=2, color='blue', line_dash="dashed", legend_label="mean flipped")
fig3.xaxis.visible = False
fig3.yaxis.visible = False
fig3.legend.visible=False
fig3.toolbar_location = None
# create a linked crosshair tool among the figures
from bokeh.models import CrosshairTool
crosshair = CrosshairTool(dimensions="both")
crosshair.line_color = 'red'
fig1.add_tools(crosshair)
fig2.add_tools(crosshair)
crosshair = CrosshairTool(dimensions="height")
crosshair.line_color = 'red'
fig1.add_tools(crosshair)
fig2.add_tools(crosshair)
fig3.add_tools(crosshair)
fig4.add_tools(crosshair)
from bokeh.layouts import column
fig_image = column([fig3, fig1, fig2, fig4], sizing_mode='scale_width')
st.bokeh_chart(fig_image, use_container_width=True)
del fig_image, image, image2
else:
with container_image:
tooltips = [("x", "$x"), ('y', '$y'), ('val', '@image')]
fig_image = generate_bokeh_figure(image, 1, 1, title=f"Original", title_location="below", plot_width=None, plot_height=None, x_axis_label=None, y_axis_label=None, tooltips=tooltips, show_axis=False, show_toolbar=False, crosshair_color="white", aspect_ratio=w/h)
st.bokeh_chart(fig_image, use_container_width=True)
del fig_image, image
rad_plot = st.empty()
with st.expander(label="Select radial range", expanded=False):
radprofile = compute_radial_profile(data)
rad = np.arange(len(radprofile)) * apix
rmin_auto, rmax_auto = estimate_radial_range(radprofile, thresh_ratio=0.1)
rmin = st.number_input('Minimal radius (Å)', value=round(rmin_auto*apix,1), min_value=0.0, max_value=round(nx//2*apix,1), step=1.0, format="%g", key="rmin")
rmax = st.number_input('Maximal radius (Å)', value=round(rmax_auto*apix,1), min_value=0.0, max_value=round(nx//2*apix,1), step=1.0, format="%g", key="rmax")
if rmax<=rmin:
st.warning(f"rmax(={rmax}) should be larger than rmin(={rmin})")
return
with st.expander(label="Download data", expanded=False):
import pandas as pd
st.download_button(
label="Radial profile",
data=pd.DataFrame(np.hstack((rad.reshape(len(rad), 1), radprofile.reshape(len(rad), 1))), columns=["radius (Å)", "density"]).round(6).to_csv().encode('utf-8'),
file_name='radial_profile.csv',
mime='text/csv',
)
from bokeh.plotting import figure
tools = 'box_zoom,crosshair,hover,pan,reset,save,wheel_zoom'
tooltips = [("r", "@x{0.0}Å"), ("val", "@y{0.0}"),]
fig_radprofile = figure(title="density radial profile", x_axis_label="r (Å)", y_axis_label="pixel value", tools=tools, tooltips=tooltips, aspect_ratio=2)
fig_radprofile.line(rad, radprofile, line_width=2, color='red')
del rad, radprofile
from bokeh.models import Span
rmin_span = Span(location=rmin, dimension='height', line_color='green', line_dash='dashed', line_width=3)
rmax_span = Span(location=rmax, dimension='height', line_color='green', line_dash='dashed', line_width=3)
fig_radprofile.add_layout(rmin_span)
fig_radprofile.add_layout(rmax_span)
fig_radprofile.yaxis.visible = False
with rad_plot:
st.bokeh_chart(fig_radprofile, use_container_width=True)
del fig_radprofile
with st.expander(label="Server info", expanded=False):
server_info_empty = st.empty()
#server_info = f"Host: {get_hostname()} \n"
#server_info+= f"Account: {get_username()}"
server_info = f"Uptime: {up_time():.1f} s \n"
server_info+= f"Mem (total): {mem_info()[0]:.1f} MB \n"
server_info+= f"Mem (quota): {mem_quota():.1f} MB \n"
server_info+= "Mem (used): {mem_used:.1f} MB"
server_info_empty.markdown(server_info.format(mem_used=mem_used()))
share_url = st.checkbox('Show sharable URL', value=False, help="Include relevant parameters in the browser URL to allow you to share the URL and reproduce the plots", key="share_url")
if share_url:
show_qr = st.checkbox('Show QR code of the URL', value=False, help="Display the QR code of the sharable URL", key="show_qr")
else:
show_qr = False
hide_streamlit_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
with col3:
da = st.number_input('Angular step size (°)', value=da_auto, min_value=0.1, max_value=10., step=0.1, format="%g", help="Set the azimuthal angle step size for the computation of the cylindric projection", key="da")
dz = st.number_input('Axial step size (Å)', value=dz_auto, min_value=0.1, max_value=10., step=0.1, format="%g", help="Set the axial step size for the computation of the cylindric projection. Use a smaller step size (such as 0.2 Å) for a helical structure with small rise (such as a protein fibril with rise ~2.3-2.4 Å or ~4.7-4.8 Å)", key="dz")
peak_width = st.number_input('Peak width (°)', value=max(1.0, da*9.0), min_value=0.1, max_value=60.0, step=1.0, format="%g", help="Set the expected peak width (°) in the auto-correlation image", key="peak_width")
peak_height = st.number_input('Peak height (Å)', value=max(1.0, dz*9.0), min_value=0.1, max_value=30.0, step=1.0, format="%g", help="Set the expected peak height (Å) in the auto-correlation image", key="peak_height")
npeaks_empty = st.empty()
acf_2rounds = st.checkbox(label="ACF 2x", value=False, help="Compute ACF of ACF", key="acf_2rounds")
show_scf = st.checkbox(label="SCF", value=False, help="Use the self-correlation function (SCF) variant of ACF (e.g. |F|->sqrt(|F|)", key="show_scf")
#data = auto_masking(data)
#data = minimal_grids(data)
cylproj = cylindrical_projection(data, da=da, dz=dz/apix, dr=1, rmin=rmin/apix, rmax=rmax/apix, interpolation_order=1)
del data
server_info_empty.markdown(server_info.format(mem_used=mem_used()))
cylproj_work = cylproj
draw_cylproj_box = False
st.subheader("Display:")
show_cylproj = st.checkbox(label="Cylindrical projection", value=True, help="Display the cylindric projection", key="show_cylproj")
if show_cylproj:
nz, na = cylproj.shape
ang_min = st.number_input('Minimal angle (°)', value=-180., min_value=-180.0, max_value=180., step=1.0, format="%g", help="Set the minimal azimuthal angle of the cylindric projection to be included to compute the auto-correlation function", key="ang_min")
ang_max = st.number_input('Maximal angle (°)', value=180., min_value=-180.0, max_value=180., step=1.0, format="%g", help="Set the maximal azimuthal angle of the cylindric projection to be included to compute the auto-correlation function. If this angle is smaller than *Minimal angle*, the angular range will be *Minimal angle* to 360 and -360 to *Maximal angle*", key="ang_max")
z_min = st.number_input('Minimal z (Å)', value=round(-nz//2*dz,1), min_value=round(-nz//2*dz,1), max_value=round(nz//2*dz,1), step=1.0, format="%g", help="Set the minimal axial section of the cylindric projection to be included to compute the auto-correlation function", key="z_min")
z_max = st.number_input('Maximal z (Å)', value=round(nz//2*dz,1), min_value=round(-nz//2*dz,1), max_value=round(nz//2*dz,1), step=1.0, format="%g", help="Set the maximal axial section of the cylindric projection to be included to compute the auto-correlation function", key="z_max")
if z_max<=z_min:
st.warning(f"'Maximal z'(={z_max}) should be larger than 'Minimal z'(={z_min})")
return
if not (ang_min==-180 and ang_max==180 and z_min==-nz//2*dz and z_max==nz//2*dz):
draw_cylproj_box = True
cylproj_work = cylproj * 1.0
if ang_min<ang_max:
if ang_min>-180.:
a0 = round(ang_min/da) + na//2
cylproj_work[:, 0:a0] = 0
if ang_max<180.:
a1 = round(ang_max/da)+ na//2
cylproj_work[:, a1:] = 0
else: # wrap around
if ang_min<180:
a0 = round(ang_min/da) + na//2
cylproj_work[:, a0:] = 0
if ang_max>-180:
a1 = round(ang_max/da)+ na//2
cylproj_work[:, 0:a1] = 0
if z_min>-nz//2*dz:
z0 = round(z_min/dz)+ nz//2
cylproj_work[0:z0, :] = 0
if z_max<nz//2*dz:
z1 = round(z_max/dz)+ nz//2
cylproj_work[z1:, :] = 0
cylproj_square = make_square_shape(cylproj_work)
del cylproj_work
show_acf = st.checkbox(label="ACF", value=True, help="Display the auto-correlation function (ACF)", key="show_acf")
if show_acf:
show_peaks_empty = st.empty()
acf = auto_correlation(cylproj_square, sqrt=show_scf, high_pass_fraction=1./cylproj_square.shape[0])
if acf_2rounds:
acf = auto_correlation(acf, sqrt=show_scf, high_pass_fraction=1./cylproj_square.shape[0])
del cylproj_square
peaks, masses = find_peaks(acf, da=da, dz=dz, peak_width=peak_width, peak_height=peak_height, minmass=1.0)
if peaks is not None:
npeaks_all = len(peaks)
try:
from kneebow.rotor import Rotor
rotor = Rotor()
rotor.fit_rotate( np.vstack((np.arange(len(masses)-3), masses.iloc[3:])).T )
npeaks_guess = min(npeaks_all, rotor.get_elbow_index()+3)
except:
npeaks_guess = npeaks_all
npeaks = int(npeaks_empty.number_input('# peaks to use', value=npeaks_guess, min_value=3, max_value=npeaks_all, step=2, help=f"The {npeaks_all} peaks detected in the auto-correlation function are sorted by peak quality. This input allows you to use only the best peaks instead of all {npeaks_all} peaks to determine the lattice parameters (i.e. helical twist, rise, and csym)", key="npeaks"))
show_arrow_empty = st.empty()
show_lattice_empty = st.empty()
server_info_empty.markdown(server_info.format(mem_used=mem_used()))
with col4:
if show_cylproj:
h, w = cylproj.shape
tooltips = [("angle", "$x°"), ('z', '$yÅ'), ('cylproj', '@image')]
fig_cylproj = generate_bokeh_figure(cylproj, da, dz, title=f"Cylindrical Projection ({w}x{h})", title_location="below", plot_width=None, plot_height=None, x_axis_label=None, y_axis_label=None, tooltips=tooltips, show_axis=False, show_toolbar=True, crosshair_color="white", aspect_ratio=w/h)
if draw_cylproj_box:
if ang_min<ang_max:
fig_cylproj.quad(left=ang_min, right=ang_max, bottom=z_min, top=z_max, line_color=None, fill_color='yellow', fill_alpha=0.5)
else:
fig_cylproj.quad(left=ang_min, right=180, bottom=z_min, top=z_max, line_color=None, fill_color='yellow', fill_alpha=0.5)
fig_cylproj.quad(left=-180, right=ang_max, bottom=z_min, top=z_max, line_color=None, fill_color='yellow', fill_alpha=0.5)
st.text("") # workaround for a layout bug in streamlit
st.bokeh_chart(fig_cylproj, use_container_width=True)
del fig_cylproj
del cylproj
if show_acf:
st.text("") # workaround for a streamlit layout bug
h, w = acf.shape
tooltips = [("twist", "$x°"), ('rise', '$yÅ'), ('acf', '@image')]
fig_acf = generate_bokeh_figure(acf, da, dz, title=f"Auto-Correlation ({w}x{h})", title_location="below", plot_width=None, plot_height=None, x_axis_label=None, y_axis_label=None, tooltips=tooltips, show_axis=False, show_toolbar=True, crosshair_color="white", aspect_ratio=w/h)
if peaks is not None:
show_peaks = show_peaks_empty.checkbox(label="Peaks", value=True, help=f"Mark the {len(peaks)} peaks detected in the auto-correlation function with yellow circles", key="show_peaks")
if show_peaks:
x = peaks[:npeaks, 0]
y = peaks[:npeaks, 1]
fig_acf.ellipse(x, y, width=peak_width, height=peak_height, line_width=1, line_color='yellow', fill_alpha=0)
st.bokeh_chart(fig_acf, use_container_width=True)
del fig_acf
if peaks is None:
msg_empty.warning("No peak was found from the auto-correlation image \n" + msg_hint)
return
elif len(peaks)<3:
msg_empty.warning(f"Only {len(peaks)} peaks were found. At least 3 peaks are required \n" + msg_hint)
return
twist_empty = st.empty()
rise_empty = st.empty()
csym_empty = st.empty()
button_refine_twist_rise = st.button("Refine twist/rise")
server_info_empty.markdown(server_info.format(mem_used=mem_used()))
with col2:
h, w = acf.shape
h2 = 900 # final plot height
w2 = int(round(w * h2/h))//2*2
x_axis_label="twist (°)"
y_axis_label="rise (Å)"
tooltips = [("twist", "$x°"), ('rise', '$yÅ'), ('acf', '@image')]
fig_indexing = generate_bokeh_figure(image=acf, dx=da, dy=dz, title="", title_location="above", plot_width=None, plot_height=None, x_axis_label=x_axis_label, y_axis_label=y_axis_label, tooltips=tooltips, show_axis=True, show_toolbar=True, crosshair_color="white", aspect_ratio=w/h)
# horizontal line along the equator
from bokeh.models import Arrow, VeeHead
fig_indexing.line([-w//2*da, (w//2-1)*da], [0, 0], line_width=2, line_color="yellow", line_dash="dashed")
trc1, trc2 = fitHelicalLattice(peaks[:npeaks], acf, da=da, dz=dz)
trc_mean = consistent_twist_rise_cn_sets([trc1], [trc2], epsilon=1.0)
success = True if trc_mean else False
if success:
twist_tmp, rise_tmp, cn = trc_mean[0]
twist_auto, rise_auto = refine_twist_rise(acf_image=(acf, da, dz), twist=twist_tmp, rise=rise_tmp, cn=cn)
csym_auto = cn
else:
twist_auto, rise_auto, csym_auto = trc1
msg = f"The two automated methods with default parameters have failed to obtain consistent helical parameters using {npeaks} peaks. The two solutions are: \n"
msg+= f"Twist per subunit:  {round(trc1[0],2):>6.2f} {round(trc2[0],2):>6.2f} ° \n"
msg+= f"Rise per subunit:  {round(trc1[1],2):>6.2f} {round(trc2[1]):>6.2f} Å \n"
msg+= f"Csym      :  c{int(trc1[2]):5}  c{int(trc2[2]):5} \n \n"
msg+= msg_hint
msg_empty.warning(msg)
twist_manual = twist_empty.number_input(label="Twist (°):", min_value=-180., max_value=180., value=float(round(twist_auto,2)), step=0.01, format="%g", help="Manually set the helical twist instead of automatically detecting it from the lattice in the auto-correlation function")
rise_manual = rise_empty.number_input(label="Rise (Å):", min_value=0., max_value=h*dz, value=float(round(rise_auto,2)), step=0.01, format="%g", help="Manually set the helical rise instead of automatically detecting it from the lattice in the auto-correlation function")
csym = int(csym_empty.number_input(label="Csym:", min_value=1, max_value=64, value=int(csym_auto), step=1, format="%d", help="Manually set the cyclic symmetry instead of automatically detecting it from the lattice in the auto-correlation function", key="csym"))
if button_refine_twist_rise:
twist, rise = refine_twist_rise(acf_image=(acf, da, dz), twist=twist_manual, rise=rise_manual, cn=csym)
else:
twist, rise = twist_manual, rise_manual
st.session_state.twist = twist
st.session_state.rise = rise
fig_indexing.title.text = f"twist={round(twist,2):g}° (pitch={round(360/abs(twist)*rise, 2):g}Å) rise={round(rise,2):g}Å csym=c{int(csym):d}"
fig_indexing.title.align = "center"
fig_indexing.title.text_font_size = "24px"
fig_indexing.title.text_font_style = "normal"
fig_indexing.xaxis.axis_label_text_font_size = "16pt"
fig_indexing.yaxis.axis_label_text_font_size = "16pt"
fig_indexing.xaxis.major_label_text_font_size = "12pt"
fig_indexing.yaxis.major_label_text_font_size = "12pt"
fig_indexing.hover[0].attachment = "vertical"
show_arrow = show_arrow_empty.checkbox(label="Arrow", value=True, help="Show an arrow in the central panel from the center to the first lattice point corresponding to the helical twist/rise", key="show_arrow")
if show_arrow:
fig_indexing.add_layout(Arrow(x_start=0, y_start=0, x_end=twist, y_end=rise, line_color="yellow", line_width=4, end=VeeHead(line_color="yellow", fill_color="yellow", line_width=2)))
show_lattice = show_lattice_empty.checkbox(label="Lattice", value=True, help="Show the helical twist/rise lattice in the central panel", key="show_lattice")
if show_lattice:
from bokeh.models import ColumnDataSource, Scatter
from bokeh.palettes import Category10
colors_avail = Category10[max(3, min(10, csym))]
colors = [colors_avail[si % len(colors_avail)] for si in range(csym)]
n = int(h/2*dz/rise)+1
n = np.arange(-n, n+1)
x = np.fmod(twist * n + np.max(n)*360, 360)
x[x>180] -= 360
y = rise * n
for si in range(csym):
xsym = np.fmod(x + 360/csym * si, 360)
xsym[xsym>180] -= 360
source = ColumnDataSource(dict(x=xsym, y=y))
scatter = Scatter(x='x', y='y', marker='circle', size=10, line_width=3, line_color=colors[si], fill_color=None)
fig_indexing.add_glyph(source, scatter)
from bokeh.models import CustomJS
from bokeh.events import MouseEnter
title_js = CustomJS(args=dict(title=title), code="""
document.title=title
""")
fig_indexing.js_on_event(MouseEnter, title_js)
st.text("") # workaround for a layout bug in streamlit
st.bokeh_chart(fig_indexing, use_container_width=True)
del fig_indexing
del acf
if share_url:
set_query_parameters()
if show_qr:
with col2:
qr_image = qr_code()
st.image(qr_image)
else:
st.query_params.clear()
with col2:
st.markdown("*Developed by the [Jiang Lab@Purdue University](https://jiang.bio.purdue.edu/HI3D). Report problems to [HI3D@GitHub](https://github.com/jianglab/hi3d/issues)*")
st.markdown("Please cite: *Sun, C., Gonzalez, B., & Jiang, W. (2022). Helical Indexing in Real Space. Scientific Reports, 12(1), 1–11. https://doi.org/10.1038/s41598-022-11382-7*")
server_info_empty.markdown(server_info.format(mem_used=mem_used()))
def generate_bokeh_figure(image, dx, dy, title="", title_location="below", plot_width=None, plot_height=None, x_axis_label='x', y_axis_label='y', tooltips=None, show_angle_tooltip=False, show_axis=True, show_toolbar=True, crosshair_color="white", aspect_ratio=None):
from bokeh.plotting import figure
h, w = image.shape
if aspect_ratio is None and (plot_width and plot_height):
aspect_ratio = plot_width/plot_height
tools = 'box_zoom,crosshair,pan,reset,save,wheel_zoom'
fig = figure(title_location=title_location,
frame_width=plot_width, frame_height=plot_height,
x_axis_label=x_axis_label, y_axis_label=y_axis_label,
x_range=(-w//2*dx, (w//2-1)*dx), y_range=(-h//2*dy, (h//2-1)*dy),
tools=tools, aspect_ratio=aspect_ratio)
fig.grid.visible = False
if title:
fig.title.text=title
fig.title.align = "center"
fig.title.text_font_size = "18px"
fig.title.text_font_style = "normal"
if not show_axis: fig.axis.visible = False
if not show_toolbar: fig.toolbar_location = None
source_data = dict(image=[image], x=[-w//2*dx], y=[-h//2*dy], dw=[w*dx], dh=[h*dy])
# add hover tool only for the image
from bokeh.models.tools import HoverTool, CrosshairTool
if tooltips is not None and show_angle_tooltip:
tooltips = tooltips + [("angle", '°')]
from bokeh.models import LinearColorMapper
color_mapper = LinearColorMapper(palette='Greys256') # Greys256, Viridis256
fig_image = fig.image(source=source_data, image='image', color_mapper=color_mapper, x='x', y='y', dw='dw', dh='dh')
image_hover = HoverTool(renderers=[fig_image], tooltips=tooltips)
fig.add_tools(image_hover)
# avoid the need for embedding angle image -> smaller fig object and less data to transfer
if tooltips is not None and show_angle_tooltip:
mousemove_callback_code = """
var x = cb_obj.x
var y = cb_obj.y
var angle = Math.atan2(y, x) * 180 / Math.PI - 90
if (angle < -180) angle += 360
angle = Math.round(angle*10)/10
hover.tooltips[hover.tooltips.length - 1][1] = angle.toString() + "°"
"""
from bokeh.models import CustomJS
from bokeh.events import MouseMove
mousemove_callback = CustomJS(args={"hover":fig.hover[0]}, code=mousemove_callback_code)
fig.js_on_event(MouseMove, mousemove_callback)
crosshair = [t for t in fig.tools if isinstance(t, CrosshairTool)]
if crosshair:
for ch in crosshair: ch.line_color = crosshair_color
return fig
@st.cache_data(persist='disk', max_entries=1, show_spinner=False)
def fitHelicalLattice(peaks, acf, da=1.0, dz=1.0):
if len(peaks) < 3:
#st.warning(f"WARNING: only {len(peaks)} peaks were found. At least 3 peaks are required")
return (None, None, peaks)
trc1s = []
trc2s = []
consistent_solution_found = False
nmax = len(peaks) if len(peaks)%2 else len(peaks)-1
for n in range(nmax, min(7, nmax)-1, -2):
trc1 = getHelicalLattice(peaks[:n])
trc2 = getGenericLattice(peaks[:n])
trc1s.append(trc1)
trc2s.append(trc2)
if consistent_twist_rise_cn_sets([trc1], [trc2], epsilon=1.0):
consistent_solution_found = True
break
if not consistent_solution_found:
for _ in range(100):
from random import randint, sample
if len(peaks)//2 > 5: # stronger peaks
n = randint(5, len(peaks)//2)
random_choices = sorted(sample(range(2*n), k=n))
else:
n = randint(3, len(peaks))
random_choices = sorted(sample(range(len(peaks)), k=n))
if 0 not in random_choices: random_choices = [0] + random_choices
peaks_random = peaks[random_choices]
trc1 = getHelicalLattice(peaks_random)
trc2 = getGenericLattice(peaks_random)
trc1s.append(trc1)
trc2s.append(trc2)
if consistent_twist_rise_cn_sets([trc1], [trc2], epsilon=1):
consistent_solution_found = True
break
if not consistent_solution_found:
trc_mean = consistent_twist_rise_cn_sets(trc1s, trc2s, epsilon=1)
if trc_mean:
_, trc1, trc2 = trc_mean
else:
trc1s = np.array(trc1s)
trc2s = np.array(trc2s)
trc1 = list(geometric_median(X=trc1s[:,:2])) + [int(np.median(trc1s[:,2]))]
trc2 = list(geometric_median(X=trc2s[:,:2])) + [int(np.median(trc2s[:,2]))]
twist1, rise1, cn1 = trc1
twist1, rise1 = refine_twist_rise(acf_image=(acf, da, dz), twist=twist1, rise=rise1, cn=cn1)
twist2, rise2, cn2 = trc2
twist2, rise2 = refine_twist_rise(acf_image=(acf, da, dz), twist=twist2, rise=rise2, cn=cn2)
return (twist1, rise1, cn1), (twist2, rise2, cn2)
def consistent_twist_rise_cn_sets(twist_rise_cn_set_1, twist_rise_cn_set_2, epsilon=1.0):
def angle_difference(angle1, angle2):
err = abs((angle1 - angle2) % 360)
if err > 180: err -= 360
err = abs(err)
return err
def angle_mean(angle1, angle2):
angles = np.deg2rad([angle1, angle2])
ret = np.rad2deg(np.arctan2( np.sin(angles).sum(), np.cos(angles).sum()))
return ret
def consistent_twist_rise_cn_pair(twist_rise_cn_1, twist_rise_cn_2, epsilon=1.0):
def good_twist_rise_cn(twist, rise, cn, epsilon=0.1):
if abs(twist)>epsilon:
if abs(rise)>epsilon: return True
elif abs(rise*360./twist/cn)>epsilon: return True # pitch>epsilon
else: return False
else:
if abs(rise)>epsilon: return True
else: return False
if twist_rise_cn_1 is None or twist_rise_cn_2 is None:
return None
twist1, rise1, cn1 = twist_rise_cn_1
twist2, rise2, cn2 = twist_rise_cn_2
if not good_twist_rise_cn(twist1, rise1, cn1, epsilon=0.1): return None
if not good_twist_rise_cn(twist2, rise2, cn2, epsilon=0.1): return None
if cn1==cn2 and abs(rise2-rise1)<epsilon and angle_difference(twist1, twist2)<epsilon:
cn = cn1
rise_tmp = (rise1+rise2)/2
twist_tmp = angle_mean(twist1, twist2)
return twist_tmp, rise_tmp, int(cn)
else:
return None
for twist_rise_cn_1 in twist_rise_cn_set_1:
for twist_rise_cn_2 in twist_rise_cn_set_2:
trc = consistent_twist_rise_cn_pair(twist_rise_cn_1, twist_rise_cn_2, epsilon=epsilon)
if trc: return (trc, twist_rise_cn_1, twist_rise_cn_2)
return None
@st.cache_data(persist='disk', max_entries=1, show_spinner=False)
def refine_twist_rise(acf_image, twist, rise, cn):
from scipy.optimize import minimize
if rise<=0: return twist, rise
cn = int(cn)
acf_image, da, dz = acf_image
ny, nx = acf_image.shape
try:
npeak = max(3, min(100, int(ny/2/abs(rise)/2)))
except:
npeak = 3
i = np.repeat(range(1, npeak), cn)
w = np.power(i, 1./2)
x_sym = np.tile(range(cn), npeak-1) * 360./cn
def score(x):
twist, rise = x
px = np.fmod(nx//2 + i * twist/da + x_sym + npeak*nx, nx)
py = ny//2 + i * rise/dz
v = map_coordinates(acf_image, (py, px))
score = -np.sum(v*w)
return score
res = minimize(score, (twist, rise), method='nelder-mead', options={'xatol': 1e-4, 'adaptive': True})
twist_opt, rise_opt = res.x
twist_opt = set_to_periodic_range(twist_opt, min=-180, max=180)
return twist_opt, rise_opt
@st.cache_data(persist='disk', max_entries=1, show_spinner=False)
def getHelicalLattice(peaks):
if len(peaks) < 3:
#st.warning(f"only {len(peaks)} peaks were found. At least 3 peaks are required")
return (0, 0, 1)
x = peaks[:, 0]
y = peaks[:, 1]
ys = np.sort(y)
vys = ys[1:] - ys[:-1]
vy = np.median(vys[np.abs(vys) > 1e-1])
j = np.around(y / vy)
nonzero = j != 0
if np.count_nonzero(nonzero)>0:
rise = np.median(y[nonzero] / j[nonzero])
if np.isnan(rise):
#st.warning(f"failed to detect rise parameter. all {len(peaks)} peaks are in the same row?")
return (0, 0, 1)
else:
#st.warning(f"failed to detect rise parameter. all {len(peaks)} peaks are on the equator?")
return (0, 0, 1)
cn = 1
js = np.rint(y / rise)
spacing = []
for j in sorted(list(set(js))):
x_j = x[js == j]
if len(x_j) > 1:
x_j.sort()
spacing += list(x_j[1:] - x_j[:-1])
if len(spacing):
best_spacing = max(0.01, np.median(spacing)) # avoid corner case crash
cn_f = 360. / best_spacing
expected_spacing = 360./round(cn_f)
if abs(best_spacing - expected_spacing)/expected_spacing < 0.05:
cn = int(round(cn_f))
js = np.rint(y / rise)
above_equator = js > 0
if np.count_nonzero(above_equator)>0:
min_j = js[above_equator].min() # result might not be right if min_j>1
vx = sorted(x[js == min_j] / min_j, key=lambda x: abs(x))[0]
x2 = np.reshape(x, (len(x), 1))
xdiffs = x2 - x2.T
y2 = np.reshape(y, (len(y), 1))
ydiffs = y2 - y2.T
selected = (np.rint(ydiffs / rise) == min_j) & (np.rint(xdiffs / vx) == min_j)
best_vx = np.mean(xdiffs[selected])
if best_vx > 180: best_vx -= 360
best_vx /= min_j
twist = best_vx
if cn>1 and abs(twist)>180./cn:
if twist<0: twist+=360./cn
elif twist>0: twist-=360./cn
if np.isnan(twist):
#st.warning(f"failed to detect twist parameter using {len(peaks)} peaks")
return (0, 0, 1)
else:
#st.warning(f"failed to detect twist parameter using {len(peaks)} peaks")
return (0, 0, 1)
return (twist, rise, int(cn))
@st.cache_data(persist='disk', max_entries=1, show_spinner=False)
def getGenericLattice(peaks):
if len(peaks) < 3:
#st.warning(f"only {len(peaks)} peaks were found. At least 3 peaks are required")
return (0, 0, 1)
from scipy.spatial import cKDTree as KDTree
mindist = 10 # minimal inter-subunit distance
minang = 15 # minimal angle between a and b vectors
epsilon = 0.5
def angle(v1, v2=None): # angle between two vectors, ignoring vector polarity
p = np.dot(v1, v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
p = np.clip(abs(p), 0, 1)
ret = np.rad2deg(np.arccos(p)) # 0<=angle<90
return ret
def distance(v1, v2):
d = math.hypot(v1[0] - v2[0], v1[1] - v2[1])
return d
def onEquator(v, epsilon=0.5):
# test if b vector is on the equator
if abs(v[1]) > epsilon: return 0
return 1
def pickTriplet(kdtree, index=-1):
'''
pick a point as the origin and find two points closest to the origin
'''
m, n = kdtree.data.shape # number of data points, dimension of each data point
if index < 0:
index = random.randint(0, m - 1)
origin = kdtree.data[index]
distances, indices = kdtree.query(origin, k=m)
first = None
for i in range(1, m):
v = kdtree.data[indices[i]]
#if onEquator(v - origin, epsilon=epsilon):
# continue
first = v
break
second = None
for j in range(i + 1, m):
v = kdtree.data[indices[j]]
#if onEquator(v - origin, epsilon=epsilon):
# continue
ang = angle(first - origin, v - origin)
dist = distance(first - origin, v - origin)
if dist > mindist and ang > minang:
second = v
break
return (origin, first, second)
def peaks2NaNbVaVbOrigin(peaks, va, vb, origin):
# first find indices of each peak using current unit cell vectors
A = np.vstack((va, vb)).transpose()
b = (peaks - origin).transpose()
x = np.linalg.solve(A, b)
NaNb = np.around(x)
# then refine unit cell vectors using these indices
good = np.abs(x-NaNb).max(axis=0) < 0.1 # ignore bad peaks
one = np.ones((1, (NaNb[:, good].shape)[1]))
A = np.vstack((NaNb[:, good], one)).transpose()
(p, residues, rank, s) = np.linalg.lstsq(A, peaks[good, :], rcond=-1)
va = p[0]
vb = p[1]
origin = p[2]
err = np.sqrt(sum(residues)) / len(peaks)
return {"NaNb": NaNb, "a": va, "b": vb, "origin": origin, "err": err}
kdt = KDTree(peaks)
bestLattice = None
minError = 1e30
for i in range(len(peaks)):
origin, first, second = pickTriplet(kdt, index=i)
if first is None or second is None: continue
va = first - origin
vb = second - origin
lattice = peaks2NaNbVaVbOrigin(peaks, va, vb, origin)
lattice = peaks2NaNbVaVbOrigin(peaks, lattice["a"], lattice["b"], lattice["origin"])
err = lattice["err"]
if err < minError:
dist = distance(lattice['a'], lattice['b'])
ang = angle(lattice['a'], lattice['b'])
if dist > mindist and ang > minang:
minError = err
bestLattice = lattice
if bestLattice is None:
# assume all peaks are along the same line of an arbitrary direction
# fit a line through the peaks
from scipy.odr import Data, ODR, unilinear
x = peaks[:, 0]
y = peaks[:, 1]
odr_data = Data(x, y)
odr_obj = ODR(odr_data, unilinear)
output = odr_obj.run()
x2 = x + output.delta # positions on the fitted line
y2 = y + output.eps
v0 = np.array([x2[-1]-x2[0], y2[-1]-y2[0]])
v0 = v0/np.linalg.norm(v0, ord=2) # unit vector along the fitted line
ref_i = 0
t = (x2-x2[ref_i])*v0[0] + (y2-y2[ref_i])*v0[1] # coordinate along the fitted line
t.sort()
spacings = t[1:]-t[:-1]
a = np.median(spacings[np.abs(spacings)>1e-1])
a = v0 * a
if a[1]<0: a *= -1
bestLattice = {"a": a, "b": a}
a, b = bestLattice["a"], bestLattice["b"]
minLength = max(1.0, min(np.linalg.norm(a), np.linalg.norm(b)) * 0.9)
vs_on_equator = []
vs_off_equator = []
maxI = 10
for i in range(-maxI, maxI + 1):
for j in range(-maxI, maxI + 1):
if i or j:
v = i * a + j * b
v[0] = set_to_periodic_range(v[0], min=-180, max=180)
if np.linalg.norm(v) > minLength:
if v[1]<0: v *= -1
if onEquator(v, epsilon=epsilon):
vs_on_equator.append(v)
else:
vs_off_equator.append(v)
twist, rise, cn = 0, 0, 1
if vs_on_equator: