Repository navigation
Expand file tree
/
Copy pathallplot.py
More file actions
1488 lines (1145 loc) · 43.5 KB
/
Copy pathallplot.py
File metadata and controls
1488 lines (1145 loc) · 43.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import marimo
__generated_with = "0.21.1"
app = marimo.App(width="columns", layout_file="layouts/allplot.grid.json")
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
mo.md(text=
'''
**THE ALLPLOT**\n
-----------------------\n
PQ = Picoquant related stuff i.e. TR-PL\n
HS = Photonetc. hyperspectral data with related stuff (images,videos etc.) to be implemented\n
JPK = JPK AFM stuff, basic formats for now with QI mode to be implemented\n
-----------------------\n
For now assumes JPK data was collected from a scanning region centered on the optics
''')
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""
**Load data**
PQ takes .ptu or .pqres files
HS takes .h5 files
JPK takes .jpk or .gwy files
""")
return
@app.cell(hide_code=True)
def _(connect_error_callout, mo):
mo.hstack(connect_error_callout,justify='start')
return
@app.cell(hide_code=True)
def _(dir_refresh):
dir_refresh
return
@app.cell(hide_code=True)
def _(
hs_file_dropdown,
hs_load,
hs_usr_dropdown,
hs_ws_dropdown,
jpk_file_dropdown,
jpk_load,
jpk_ws_dropdown,
mo,
pq_file_dropdown,
pq_load,
pq_ws_dropdown,
):
mo.vstack(
[
mo.md('''
Fast file browser
\n --------------------
'''),
mo.hstack([pq_ws_dropdown,pq_file_dropdown,pq_load],justify='start',align='stretch'),
mo.hstack([hs_usr_dropdown,hs_ws_dropdown,hs_file_dropdown,hs_load],justify='start',align='stretch'),
mo.hstack([jpk_ws_dropdown,jpk_file_dropdown,jpk_load],justify='start',align='stretch')
],gap=1,heights='equal'
)
return
@app.cell(hide_code=True)
def _(browser_load_button, browser_path, mo):
mo.vstack([
mo.md('''
Free file browser
\n ----------------
'''),
mo.hstack([browser_path,mo.md(' || '),browser_load_button],justify='start')
])
return
@app.cell(hide_code=True)
def _(free_filebrowser):
free_filebrowser
return
@app.cell(hide_code=True)
def _(clear_data_button, loaded_data_table, mo):
mo.vstack([loaded_data_table,clear_data_button])
return
@app.cell(hide_code=True)
def _(iaf_ax, mo):
mo.accordion(
{'Show data collection areas':mo.ui.matplotlib(axes=iaf_ax)}
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""
---------------
**Processing**
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""
Add processed afm channel
""")
return
@app.cell(hide_code=True)
def _(
afm_proccess_channel_dd,
afm_proccess_dd,
afm_process_button,
mo,
switch_align,
switch_floor,
switch_level,
):
mo.hstack([mo.hstack([afm_proccess_dd,afm_proccess_channel_dd],justify='start'),switch_level,switch_align,switch_floor,afm_process_button])
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""
Add guassian filtered channel
""")
return
@app.cell(hide_code=True)
def _(
gaus_filt_button,
gaus_filt_channel_dd,
gaus_filt_dd,
gaus_filt_sigma_input,
mo,
):
mo.hstack([mo.hstack([gaus_filt_dd,gaus_filt_channel_dd],justify='start'),gaus_filt_sigma_input,gaus_filt_button])
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
mo.md(text=
'''
---------------\n
**Plotting**
'''
)
""")
return
@app.cell(hide_code=True)
def _(mo):
num_plots = mo.ui.number(label='Number of images',start=1,step=1)
num_plots
return (num_plots,)
@app.cell(hide_code=True)
def _(mo):
mo.hstack([mo.hstack([mo.md('Select loaded data'),mo.md('Select Channel')],justify='start',gap=2),mo.hstack([mo.md('Select colormaps'),mo.md('Colorbar labels'),mo.md('Plot titles'),mo.md('Scalebar sizes (um)'),mo.md('Colorbar min and max')],justify='end',gap=2)])
return
@app.cell(hide_code=True)
def _(
mo,
plot_cbarlabel_list,
plot_cbarlims_max,
plot_cbarlims_min,
plot_channel_list,
plot_cmap_list,
plot_list,
plot_scalebar_list,
plot_title_list,
):
mo.hstack([mo.hstack([mo.vstack(plot_list),mo.vstack(plot_channel_list)],justify='start'),mo.hstack([mo.vstack(plot_cmap_list),mo.vstack(plot_cbarlabel_list),mo.vstack(plot_title_list),mo.vstack(plot_scalebar_list),mo.vstack(plot_cbarlims_min),mo.vstack(plot_cbarlims_max)],justify='start')],justify='start',align='stretch')
return
@app.cell(hide_code=True)
def _(mo):
same_area_switch = mo.ui.switch(label='Crop to same area')
same_area_switch
return (same_area_switch,)
@app.cell(hide_code=True)
def _(mo):
plot_button = mo.ui.run_button(label='Plot')
plot_button
return (plot_button,)
@app.cell
def _(plot_fig):
plot_fig
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""
---------------
The code
------------
""")
return
@app.cell
def _():
# allplot, to plot afm, trpl and pl maps all in one place with overlay options
# picoquant trpl = pq | photonetc hypserspectral = hs | jpk afm = jpk
# feature list:
# - analyse (fastflim) and plot pq TTTR data (ptu file) x
# - open and plot pq analysed data (pqres file) x
# - open and plot hs data, optional peak position analysis x
# - open and plot jpk data (any channel), with basic data correction (done but no longer doing data correction) (or am i?) x
# - open and plot pre-corrected afm images i.e. from gwyddion x
# - sample data collection area visualiser x
# - overlay any measurements (3d?) x
# - interactive ui, filebrowser x, app mode etc. x
# to do: binned h5 support, video plotting (from brians stuff?)?, custom file browser, qi things
# there was an error loading some pqres files from afm scanned data, but only some files, keep a eye on it
return
@app.cell
def _():
#initilisations, packages etc
import numpy as np
import matplotlib.pyplot as plt
import ptufile as ptu
import xarray
import h5py
import marimo as mo
from AFMReader.jpk import load_jpk
import AFMReader.gwy as gwy
import scipy as sp
from os import scandir
import tifffile
import asyncio
plt.style.use('default')
pq_filepath = 'C:\\Users\\MT-User\\Documents\\SPT Workspaces\\'
hs_filepath = '//IM000011115/data/'
jpk_filepath = '//ubuntu/jpkuser-data/' #sometimes can find through network name sometimes not:(
_mode = 'test'
if _mode == 'test':
pq_filepath = 'C:\\Users\\ac146901\\Documents\\nanoplot data\\test data'
hs_filepath = 'C:\\Users\\ac146901\\Documents\\nanoplot data\\test data'
jpk_filepath = 'C:\\Users\\ac146901\\Documents\\nanoplot data\\'
loaded_data = {}
return (
asyncio,
gwy,
h5py,
hs_filepath,
jpk_filepath,
load_jpk,
loaded_data,
mo,
np,
plt,
pq_filepath,
ptu,
scandir,
sp,
tifffile,
)
@app.cell
def _():
# file browsing functions and buttons here
return
@app.cell
def _(mo):
dir_refresh = mo.ui.run_button(label='Refresh folders')
return (dir_refresh,)
@app.cell
def _(dir_refresh):
if dir_refresh == True:
pass
connect_error_callout = []
return (connect_error_callout,)
@app.cell
def _(dir_refresh, mo, pq_filepath, scandir):
# pq folder browser
if dir_refresh == True:
pass
pq_ws_list = []
with scandir(path=pq_filepath) as _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and not _entry.is_file():
pq_ws_list.append(_entry.name)
pq_ws_list.sort(reverse=True)
pq_ws_dropdown = mo.ui.dropdown(options=pq_ws_list,label='PQ Workspace',searchable=True)
return (pq_ws_dropdown,)
@app.cell
def _(mo, pq_filepath, pq_ws_dropdown, scandir):
# pq file browser
pq_file_list = []
if pq_ws_dropdown.value is not None:
with scandir(path=pq_filepath+pq_ws_dropdown.value) as _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and _entry.is_file():
pq_file_list.append(_entry.name)
pq_file_list.sort(reverse=True)
pq_file_dropdown = mo.ui.dropdown(options=pq_file_list,label='PQ File',searchable=True)
return (pq_file_dropdown,)
@app.cell
def _(mo):
pq_load = mo.ui.run_button(label='Load PQ file')
return (pq_load,)
@app.cell
def _(connect_error_callout, dir_refresh, hs_filepath, mo, scandir):
# hs user browser
if dir_refresh == True:
pass
hs_usr_list = []
try:
_fl = scandir(path=hs_filepath)
except:
connect_error_callout.append(mo.callout(kind='warn',value='Warning: Could not connect to HS pc'))
else:
with _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and not _entry.is_file():
hs_usr_list.append(_entry.name)
hs_usr_list.sort(reverse=True)
hs_usr_dropdown = mo.ui.dropdown(options=hs_usr_list,label='HS User',searchable=True)
return (hs_usr_dropdown,)
@app.cell
def _(hs_filepath, hs_usr_dropdown, mo, scandir):
# hs folder browser
hs_ws_list = []
if hs_usr_dropdown.value is not None:
with scandir(path=hs_filepath+hs_usr_dropdown.value) as _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and not _entry.is_file():
hs_ws_list.append(_entry.name)
hs_ws_list.sort(reverse=True)
hs_ws_dropdown = mo.ui.dropdown(options=hs_ws_list,label='HS Workspace',searchable=True)
return (hs_ws_dropdown,)
@app.cell
def _(hs_filepath, hs_usr_dropdown, hs_ws_dropdown, mo, scandir):
# hs file browser
hs_file_list = []
if hs_ws_dropdown.value is not None:
with scandir(path=hs_filepath+hs_usr_dropdown.value+'/'+hs_ws_dropdown.value) as _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and _entry.is_file():
hs_file_list.append(_entry.name)
hs_file_list.sort(reverse=True)
hs_file_dropdown = mo.ui.dropdown(options=hs_file_list,label='HS File',searchable=True)
return (hs_file_dropdown,)
@app.cell
def _(hs_filepath, mo):
hs_file_browser_new = mo.ui.file_browser(label='select HS file',initial_path=hs_filepath)
return
@app.cell
def _(mo):
hs_load = mo.ui.run_button(label='Load HS file')
return (hs_load,)
@app.cell
def _(connect_error_callout, dir_refresh, jpk_filepath, mo, scandir):
# jpk folder browser
if dir_refresh == True:
pass
jpk_ws_list = []
try:
_fl = scandir(path=jpk_filepath)
except:
connect_error_callout.append(mo.callout(kind='warn',value='Warning: Could not connect to JPK pc'))
else:
with _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and not _entry.is_file():
jpk_ws_list.append(_entry.name)
jpk_ws_list.sort(reverse=True)
jpk_ws_dropdown = mo.ui.dropdown(options=jpk_ws_list,label='JPK Workspace',searchable=True)
return (jpk_ws_dropdown,)
@app.cell
def _(jpk_filepath, jpk_ws_dropdown, mo, scandir):
# jpk file browser
jpk_file_list = []
if jpk_ws_dropdown.value is not None:
with scandir(path=jpk_filepath+jpk_ws_dropdown.value) as _fl:
for _entry in _fl:
if not _entry.name.startswith('.') and _entry.is_file():
jpk_file_list.append(_entry.name)
jpk_file_list.sort(reverse=True)
jpk_file_dropdown = mo.ui.dropdown(options=jpk_file_list,label='JPK File',full_width=False,searchable=True)
return (jpk_file_dropdown,)
@app.cell
def _(mo):
jpk_load = mo.ui.run_button(label='Load JPK file')
return (jpk_load,)
@app.cell
def _(hs_filepath, jpk_filepath, mo, pq_filepath):
## Custom file browser stuff
browser_path = mo.ui.dropdown({'PQ':pq_filepath,'HS':hs_filepath,'JPK':jpk_filepath},label='Jump to folder',allow_select_none=False,value='PQ')
return (browser_path,)
@app.cell
def _(mo):
browser_load_button = mo.ui.run_button(label='Load selected files')
return (browser_load_button,)
@app.cell
def _(
browser_load_button,
free_filebrowser,
load_gwy_file,
load_hs_file,
load_jpk_file,
load_pqres_file,
load_ptu_file,
loaded_data,
mo,
set_table_refresh,
):
mo.stop(not browser_load_button.value)
for _file in free_filebrowser.value:
_filename = _file.name
_filepath = _file.path
if file_ext(_filename) == 'h5':
loaded_data[_filename] = load_hs_file(_filepath)
if file_ext(_filename) == 'ptu':
loaded_data[_filename] = load_ptu_file(_filepath)
if file_ext(_filename) == 'pqres':
loaded_data[_filename] = load_pqres_file(_filepath)
if file_ext(_filename) == 'jpk':
loaded_data[_filename] = load_jpk_file(_filepath)
if file_ext(_filename) == 'gwy':
loaded_data[_filename] = load_gwy_file(_filepath)
set_table_refresh(True)
return
@app.cell
def _(browser_path, dir_refresh, mo):
if dir_refresh == True:
pass
free_filebrowser = mo.ui.file_browser(initial_path=browser_path.value,label='choose files')
return (free_filebrowser,)
@app.cell
def _():
# Loading data ui section
return
@app.cell
def _(mo):
clear_data_button = mo.ui.run_button(label='Clear selected data')
return (clear_data_button,)
@app.cell
def _(mo):
table_refresh , set_table_refresh = mo.state(False) #state used to refresh the table when data is added or removed (True = refresh)
return set_table_refresh, table_refresh
@app.cell
def _(loaded_data, mo, table_refresh):
# building a table of data names and types on refresh
table_refresh
loaded_data_ui_list = []
for _data in loaded_data:
loaded_data_ui_list.append({'File Name':_data,'Data Type':type(loaded_data[_data]).__name__})
loaded_data_table = mo.ui.table(data=loaded_data_ui_list,label='Loaded Data')
return (loaded_data_table,)
@app.cell
def _(clear_data_button, loaded_data, loaded_data_table, mo):
# removing data when clear data is pressed
mo.stop(not clear_data_button.value) #not sure if this does anything
if clear_data_button.value == True:
for dname in loaded_data_table.value:
del loaded_data[dname['File Name']]
return
@app.cell
async def _(asyncio, clear_data_button, set_table_refresh):
# refreshing table after data is removed, has to be in a seperate cell without a reference to the table to stop it looping infintely
if clear_data_button.value == True:
await asyncio.sleep(1)
set_table_refresh(True)
return
@app.cell
def _(loaded_data, mo, np, plt, table_refresh):
# visualisiation of the imaging area for each measurement
table_refresh
def create_box(coords,**kwargs):
"""outputs a matplot rectangle patch based on measurement coordinates"""
box_size = [np.max(coords[0])-np.min(coords[0]),np.max(coords[1])-np.min(coords[1])]
box = (0-box_size[0]/2,0-box_size[1]/2,box_size[0],box_size[1])
return plt.Rectangle((box[0],box[1]),box[2],box[3],**kwargs)
imaging_area_fig, iaf_ax = plt.subplots()
iaf_size = 1000 #um
iaf_ax.set_aspect(1)
iaf_ax.set_xlim(-iaf_size/2,iaf_size/2)
iaf_ax.set_ylim(-iaf_size/2,iaf_size/2)
iaf_ax.set_xlabel('X (um)')
iaf_ax.set_ylabel('Y (um)')
for iaf_dname in loaded_data.keys():
if type(loaded_data[iaf_dname]).__name__ == 'jpk_data':
jpk_box = create_box(loaded_data[iaf_dname].coords,fill=False,ec='C0',ls='--',label='jpk image area: '+iaf_dname)
iaf_ax.add_patch(jpk_box)
elif type(loaded_data[iaf_dname]).__name__ == 'pq_data':
pq_box = create_box(loaded_data[iaf_dname].coords,fill=False,ec='C2',ls='--',label='pq image area: '+iaf_dname)
iaf_ax.add_patch(pq_box)
elif type(loaded_data[iaf_dname]).__name__ == 'hs_data':
hs_box = create_box(loaded_data[iaf_dname].coords,fill=False,ec='C1',ls='--',label='hs image area: '+iaf_dname)
iaf_ax.add_patch(hs_box)
iaf_ax.legend()
iaf_ax.scatter(0,0,marker='+',color='k')
mo.output.clear()
return (iaf_ax,)
@app.cell
def _():
# Data analysis section (afm image correction)
return
@app.cell
def _(mo):
switch_level = mo.ui.switch(label="Plane level (P)")
switch_align = mo.ui.switch(label="Align rows (A)")
switch_floor = mo.ui.switch(label="Floor (F)")
return switch_align, switch_floor, switch_level
@app.cell
def _(loaded_data, mo, table_refresh):
table_refresh
afm_proccess_dd = mo.ui.dropdown(loaded_data.keys())
return (afm_proccess_dd,)
@app.cell
def _(afm_proccess_dd, loaded_data, mo):
if afm_proccess_dd.value is not None:
afm_proccess_channel_dd = mo.ui.dropdown(loaded_data[afm_proccess_dd.value].channels)
else:
afm_proccess_channel_dd = mo.ui.dropdown([])
return (afm_proccess_channel_dd,)
@app.cell
def _(mo):
afm_process_button = mo.ui.run_button(label='Add')
return (afm_process_button,)
@app.cell
def _(
afm_proccess_channel_dd,
afm_proccess_dd,
afm_process_button,
floor,
loaded_data,
median_flatten,
mo,
np,
remove_tilt,
switch_align,
switch_floor,
switch_level,
):
mo.stop(not afm_process_button.value)
proccess_data = np.array(loaded_data[afm_proccess_dd.value].data[afm_proccess_channel_dd.value])
proccess_tag = []
if switch_level.value == True:
proccess_data = remove_tilt(proccess_data)
proccess_tag.append('P')
if switch_align.value == True:
proccess_data = median_flatten(proccess_data)
proccess_tag.append('A')
if switch_floor.value == True:
proccess_data = floor(proccess_data)
proccess_tag.append('F')
proccess_suffix = '_'.join(proccess_tag)
if switch_align.value or switch_level.value or switch_floor.value == True:
loaded_data[afm_proccess_dd.value].add_data(afm_proccess_channel_dd.value+'_'+proccess_suffix,proccess_data)
loaded_data[afm_proccess_dd.value].add_channel(afm_proccess_channel_dd.value+'_'+proccess_suffix)
return
@app.cell
def _(loaded_data, mo, table_refresh):
#gaussian filter
table_refresh
gaus_filt_dd = mo.ui.dropdown(loaded_data.keys())
return (gaus_filt_dd,)
@app.cell
def _(gaus_filt_dd, loaded_data, mo):
if gaus_filt_dd.value is not None:
gaus_filt_channel_dd = mo.ui.dropdown(loaded_data[gaus_filt_dd.value].channels)
else:
gaus_filt_channel_dd = mo.ui.dropdown([])
return (gaus_filt_channel_dd,)
@app.cell
def _(mo):
gaus_filt_button = mo.ui.run_button(label='Add')
gaus_filt_sigma_input = mo.ui.number(label='Sigma',value=2,step=1)
return gaus_filt_button, gaus_filt_sigma_input
@app.cell
def _(
gaus_filt_button,
gaus_filt_channel_dd,
gaus_filt_dd,
gaus_filt_sigma_input,
loaded_data,
mo,
np,
sp,
):
# guassian smoothing
mo.stop(not gaus_filt_button.value)
im_gaus_filt_raw = np.array(loaded_data[gaus_filt_dd.value].data[gaus_filt_channel_dd.value])
im_gaus_filter = sp.ndimage.gaussian_filter(im_gaus_filt_raw, sigma=gaus_filt_sigma_input.value)
loaded_data[gaus_filt_dd.value].add_data(gaus_filt_channel_dd.value + '_gaussian_filtered',im_gaus_filter)
loaded_data[gaus_filt_dd.value].add_channel(gaus_filt_channel_dd.value + '_gaussian_filtered')
return
@app.cell
def _():
# Plotting data section
return
@app.cell
def _(loaded_data, mo, num_plots, table_refresh):
table_refresh
plot_list = mo.ui.array([mo.ui.dropdown(loaded_data.keys())]*num_plots.value)
return (plot_list,)
@app.cell
def _(loaded_data, mo, num_plots, plot_list):
# updating channel select based on data type
plot_channel_list = ['']*num_plots.value # maybe someday move this so that it doesnt clear the list everytime
for index, plot_file in enumerate(plot_list):
if plot_file.value == None:
break
if type(loaded_data[plot_file.value]).__name__ == 'jpk_data':
plot_channel_list[index] = mo.ui.dropdown(loaded_data[plot_file.value].channels)
if type(loaded_data[plot_file.value]).__name__ == 'pq_data':
plot_channel_list[index] = mo.ui.dropdown(loaded_data[plot_file.value].data.keys())
if type(loaded_data[plot_file.value]).__name__ == 'hs_data':
plot_channel_list[index] = [mo.ui.dropdown(['Peak position','Wavelength']),mo.ui.number(start=400,stop=1000,step=2)]
return (plot_channel_list,)
@app.cell
def _(mo, num_plots):
colormap_list = ['viridis', 'plasma', 'inferno', 'magma','afmhot','Spectral_r', 'coolwarm']
plot_cmap_list = mo.ui.array([mo.ui.dropdown(colormap_list,allow_select_none=False,value='viridis')]*num_plots.value)
plot_cbarlabel_list = mo.ui.array([mo.ui.text(placeholder='cbar label')]*num_plots.value)
plot_title_list = mo.ui.array([mo.ui.text(placeholder='title')]*num_plots.value)
plot_scalebar_list = mo.ui.array([mo.ui.number(value=25)]*num_plots.value)
plot_cbarlims_min = mo.ui.array([mo.ui.text()]*num_plots.value)
plot_cbarlims_max = mo.ui.array([mo.ui.text()]*num_plots.value)
return (
plot_cbarlabel_list,
plot_cbarlims_max,
plot_cbarlims_min,
plot_cmap_list,
plot_scalebar_list,
plot_title_list,
)
@app.cell
def _(
grid_plot,
loaded_data,
mo,
np,
num_plots,
plot_button,
plot_cbarlabel_list,
plot_cbarlims_max,
plot_cbarlims_min,
plot_channel_list,
plot_cmap_list,
plot_list,
plot_scalebar_list,
plot_title_list,
same_area_switch,
):
mo.stop(not plot_button.value)
_plot_data = [0]*num_plots.value
_plot_coords = [0]*num_plots.value
_plot_colormaps = plot_cmap_list.value
_plot_titles = plot_title_list.value
_plot_cbarlabels = plot_cbarlabel_list.value
_plot_scalebar_sizes = plot_scalebar_list.value
_plot_clims = list(zip(lim_float(plot_cbarlims_min.value),lim_float(plot_cbarlims_max.value)))
for _idx, _plot_file in enumerate(plot_list):
if type(loaded_data[_plot_file.value]).__name__ == 'hs_data':
_plot_coords[_idx] = loaded_data[_plot_file.value].coords
if plot_channel_list[_idx][0].value == 'Peak position':
_plot_data[_idx] = loaded_data[_plot_file.value].mpm
else:
_wvl_idx = np.argwhere(loaded_data[_plot_file.value].wvls==plot_channel_list[_idx][1].value)
_plot_data[_idx] = np.flipud(loaded_data[_plot_file.value].data[_wvl_idx,:,:][0][0])
else:
_plot_data[_idx] = loaded_data[_plot_file.value].data[plot_channel_list[_idx].value]
_plot_coords[_idx] = loaded_data[_plot_file.value].coords
plot_fig = grid_plot(_plot_data,_plot_coords,cmaps=_plot_colormaps,colobarlabels=_plot_cbarlabels,titles=_plot_titles,scalebar_sizes=_plot_scalebar_sizes,same_area=same_area_switch.value,cbar_limits=_plot_clims)
return (plot_fig,)
@app.function
def lim_float(lims):
new_lims = []
for lim in lims:
if lim == '':
new_lims.append(None)
else:
new_lims.append(float(lim))
return new_lims
@app.function
def file_ext(filename):
rev = filename[::-1]
rev_cut = rev[:rev.find('.')]
return rev_cut[::-1]
@app.cell
def _(np, plt, same_area_function):
#grid plotting function
def grid_plot(data,coords,colobarlabels=None,cmaps=None,scalebar_sizes=25,scalebar_color='k',titles=None,cbar_ticks=None,cbar_limits=None,same_area=False):
""" Plots arbitrary number of images in a grid in order of the data given.
parameters:
- data (array of 2d data sets): list of data to plot
- coords (array of tuples (x,y)): coordinates to plot each data set in um
- colorbarlabels {optional} (array of str): label for each colobar
- cmaps {optional} (array of valid colormaps): colormap for each image
- scalebar_sizes {optional} (array of int or float): size for each scalebar
- scalebar_color {optional} (str, valid color): color for the scalebars
- titles {optional} (array of str): title for each subplot
- cbar_ticks {optional} (array of 1d arrays): colobar tick array for each colorbar
- cbar_limits {optional} (array of tuples (min,max)): min and max value for each colorbar
- same_area {optional} (bool): option to crop images to same area as smallest image
"""
num_images = len(data)
nrows = round(num_images/2+0.1)
if num_images == 1:
figsize = (6,5) #half width for only 1 image
ncols =1
else:
figsize = (12,5*nrows)
ncols = 2
if colobarlabels == None:
colobarlabels = ['']*num_images
if type(scalebar_sizes)==int or len(scalebar_sizes) == 1:
scalebar_sizes = np.ones(num_images,dtype=int)*scalebar_sizes
if cmaps == None:
cmaps = ['viridis']*num_images
if titles == None:
titles = ['']*num_images
if cbar_ticks == None:
cbar_ticks = [None]*num_images
if cbar_limits == None:
cbar_limits = []
for data_i in data:
cbar_limits.append((np.min(data_i),np.max(data_i)))
if same_area == True:
[xlims,ylims] = same_area_function(coords)
fig, empty_ax = plt.subplots(figsize=figsize,layout='constrained')
fig.clear()
for i in range(num_images):
X,Y = np.meshgrid(coords[i][0],coords[i][1])
ax = fig.add_subplot(nrows,ncols,i+1,aspect=1)
im = ax.pcolormesh(X,Y,data[i],cmap=cmaps[i],vmin=cbar_limits[i][0],vmax=cbar_limits[i][1])
ax.set_xticks([])
ax.set_yticks([])
if same_area == True:
ax.set_xlim(xlims[i])
ax.set_ylim(ylims[i])
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
if not scalebar_sizes[i] == 0:
scalebar = ax.add_patch(plt.Rectangle((xmin+0.05*(xmax-xmin),ymin+0.05*(ymax-ymin)),width=scalebar_sizes[i],height=0.025*(ymax-ymin),color=scalebar_color))
ax.text(scalebar.get_x(),scalebar.get_y()+scalebar.get_height()*1.3,f'{scalebar_sizes[i]}um',weight=600,color=scalebar_color)
fig.colorbar(im,label=colobarlabels[i],pad=0,ax=ax,ticks=cbar_ticks[i])
ax.set_title(titles[i])
fig.get_layout_engine().set(h_pad=0.2)
#plt.show()
return fig
return (grid_plot,)
@app.cell
def _(np):
def same_area_function(coords):
x_lengths = []
y_lengths = []
for i in coords:
x_lengths.append(np.max(i[0])-np.min(i[0]))
y_lengths.append(np.max(i[1])-np.min(i[1]))
areas = np.multiply(x_lengths,y_lengths)
smallest = np.argmin(areas)
x_lims = []
y_lims = []
for indx,k in enumerate(coords):
if indx == smallest:
x_lims.append([np.min(k[0]),np.max(k[0])])
y_lims.append([np.min(k[1]),np.max(k[1])])
else:
mid_x = np.max(k[0])/2
mid_y = np.max(k[1])/2
x_min = mid_x - x_lengths[smallest]/2
x_max = mid_x + x_lengths[smallest]/2
y_min = mid_y - y_lengths[smallest]/2
y_max = mid_y + y_lengths[smallest]/2
x_lims.append([x_min,x_max])
y_lims.append([y_min,y_max])
return [x_lims,y_lims]
return (same_area_function,)
@app.cell
def _(
load_pqres_file,
load_ptu_file,
loaded_data,
pq_file_dropdown,
pq_filepath,
pq_load,
pq_ws_dropdown,
set_table_refresh,
):
# Open and proccess lifetime data (ptu file)
# would be nice if we could open the analysed pqres file :( WE CAN!
if pq_load.value == True:
pq_workspace = pq_ws_dropdown.value+'/'
pq_filename = pq_file_dropdown.value
if file_ext(pq_filename) == 'ptu': # check if its a .ptu file
loaded_data[pq_filename] = load_ptu_file(pq_filepath+pq_workspace+pq_filename)
elif file_ext(pq_filename) == 'pqres': # or check if its pqres file
loaded_data[pq_filename] = load_pqres_file(pq_filepath+pq_workspace+pq_filename)
else:
print('Not a .ptu or .pqres file')
set_table_refresh(True)
return
@app.cell
def _(np, ptu):
def load_ptu_file(file):
"""loads ptu file int, calculates fast lifetime, and flips ud"""
pq_data_temp = ptu.PtuFile(file)
pq_data_array = pq_data_temp[0,:,:,0,:]
pq_intensity = pq_data_temp[0,:,:,0,::-1]
lt_hist = pq_data_temp.decode_histogram()[0,:]