-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTNTvisualizer.m
3422 lines (3091 loc) · 147 KB
/
TNTvisualizer.m
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
% TrackNTrace: A simple and extendable MATLAB framework for single-molecule localization and tracking
%
% Copyright (C) 2016 Simon Christoph Stein, scstein@phys.uni-goettingen.de
% Copyright (C) 2020, Jan Christoph Thiele, christoph.thiele@phys.uni-goettingen.de
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
%
function [h_main, movie] = TNTvisualizer(movieOrTNTfile, candidateDataOrTNTfile, candidateParams, refinementData, refinementParams, trackingData, trackingParams, postprocData, postprocParams, FPS, is_blocking, firstFrame)
% Visualizer for movies and TrackNTrace results.
%
% COMMON USAGEs:
% (x) TNTvisualizer();
% Opens a dialog to choose a movie or TNT file from a completed TNT
% run. When choosing a TNT file, the corresponding movie is loaded
% automatically along all results from the evaluation.
% (x) [~,movie] = TNTvisualizer();
% Same as above, but the loaded movie is returned.
% (x) [~,movie] = TNTvisualizer(PathToTNTfile);
% Load TNT file. This loads the corresponding movie and all results from the evaluation.
% (x) TNTvisualizer(movie);
% Visualize movie already loaded in MATLAB.
% (x) [~,movie] = TNTvisualizer(PathToMovie);
% Same as above, but movie is loaded from disk first.
% (x) TNTvisualizer(movie, PathToTNTfileOrStruct);
% Visualize already loaded movie along with evaluated data from
% specified TNT file. Make sure the movie fits to the evaluated data.
% (x) [~,movie] = TNTvisualizer(PathToMovie, PathToTNTfileOrStruct);
% Same as above, but movie is loaded from disk first.
% [ Full USAGE: [GUIhandle, movie] = TNTvisualizer(movieOrTNTfile, candidateDataOrTNTfile, candidateParams, refinementData, refinementParams, trackingData, trackingParams, FPS, is_blocking, firstFrame) ]
%
% Input:
% movieOrTNTfile:
% EITHER: 3D matrix (rows,cols,frames) with intensity values.
% OR: FLIM movie: {intensity (rows,cols,frames), lifetime (rows,cols,frames)}
% OR: Filepath to TIF movie -> Loads movie
% OR: Filepath to TNT file. -> Loads movie and evaluation
% OR: Struct like TNT file. -> Loads movie and evaluation
% candidateDataOrTNTfile:
% EITHER: 1D cell array, where cell{F} is a 2D matrix with dimensions
% N(F)x(2+PC) saving the data of frame F. N(F) is the number
% of candidates detected in frame F and the columns are
% 'x','y' plus PC arbitrary additional parameters.
% OR: Filepath to TNT file. -> Loads evaluated data
% (movie must have been given as the first parameter).
% OR: Struct like TNT file.
% candidateParams:
% 1D cell array with (2+PC) strings containing the names of the parameters
% (columns of each cell) of candidateData (above).
% refinementData:
% 1D cell array, where cell{F} is a 2D matrix with dimensions
% N(F)x(3+PF) saving the data of frame F. N(F) is the number
% of fitted emitters detected in frame F and the columns are
% 'x','y','z' position plus PF arbitrary additional parameters.
% refinementParams:
% 1D cell array with (3+PF) strings containing the names of the parameters
% (columns of each cell) of refinementData (above).
% trackingData:
% 2D matrix with dimensions Nx(5+PT). N is the number of all positions
% tracked positions. The columns are 'TrackID','frame','x','y','z'
% plus PT arbitrary additional parameters.
% trackingParams:
% 1D cell array with (5+PT) strings containing the names of the parameters
% (columns) of trackingData (above).
% FPS:
% Frames per second the visualizer plays set to use for playback on
% startup.
% is_blocking:
% If true, the GUI blocks MATLAB execution until it closes.
% firstFrame:
% Index of first frame. This is used for displaying the true index
% (with respect to the full movie) of a frame if only a certain interval
% of a movie was processed by TrackNTrace.
% Example: If frame 201 to 250 from some movie were processed. Setting
% firstFrame=201 shows 'Fr. 10/50 (210 in movie)' if the 10th processed
% frame is shown.
%
% Inputs can be left empty [] for default values. If the first or second
% argument is a struct it is checked for the fields FPS, is_blocking,
% and title.
%
% Output:
% h_main:
% Handle to the visualizer figure / GUI.
% movie:
% The visualized movie. Useful if movie was loaded by the visualizer.
%
% Author: Simon Christoph Stein
% E-Mail: scstein@phys.uni-goettingen.de
% Date: 2016
% Author: Jan Christoph Thiele
% Date: 2020
%
% CT, 2019:
% - Added handeling of FLIM data
% - Added file export
% - Added tabbed GUI
% CT, 2020:
% - file preview
% - advanced filtering
% - reconstruction
% - drift correction
%
% Add all paths required to run TNT
addPathsVisualizer();
% Check MATLAB version
MATLABversion = strsplit(version,'.');
if(str2double(MATLABversion(1))>=8 && str2double(MATLABversion(2))>=6) % Use 'drawback nocallbacks' for MATLAB 2015b (8.6.x) and later
MATLAB_2015b_or_newer = true;
try movieOrTNTfile = controllib.internal.util.hString2Char(movieOrTNTfile); catch, end % Convert strings to char arrays
try candidateDataOrTNTfile = controllib.internal.util.hString2Char(candidateDataOrTNTfile); catch, end % Convert strings to char arrays
else
MATLAB_2015b_or_newer = false;
end
% Show filechooser dialog to choose movie / TNT file if started without input arguments.
importMode = false;
importFormats = {};
importPlugin = [];
if nargin==0 || ~(isnumeric(movieOrTNTfile)||iscell(movieOrTNTfile))
% If we do not have a movie, prompt for file intput
filename = 0;
path = '';
if nargin==0
% no input
movieOrTNTfile = '';
elseif nargin==1 && ischar(movieOrTNTfile) && exist(movieOrTNTfile,'dir')
% input is folder
if ~endsWith(movieOrTNTfile,filesep)
movieOrTNTfile(end+1) = filesep;
end
end
if exist(movieOrTNTfile,'file')==2
[path,filename,ex] = fileparts(movieOrTNTfile);
filename = [filename ex];
path = [path filesep];
else
[filename, path] = selectFile();
end
if isfloat(filename)
importMode = true;
movieOrTNTfile = '';
else
movieOrTNTfile = [path,filename];
end
end
% -- Preparing the GUI --
h_main = openfig(['subfun',filesep,'TNTvisualizer_Layout.fig'],'new','invisible');
set(h_main,'Renderer','painters');
% set(h_main,'handleVisibility','on'); % Make figure visible to Matlab (might not be the case)
set(h_main,'handleVisibility','off');
set(h_main,'CloseRequestFcn',@onAppClose); % Executed on closing for cleanup
set(h_main,'Toolbar','figure'); % Add toolbar needed for zooming
set(h_main,'DoubleBuffer', 'on') % Helps against flickering
set(h_main,'FileName',''); % Set FileName to empty. This prevents that the user replaces TNTvisualizer_Layout.fig when pressing save.
h_all = guihandles(h_main); % Get handles of all GUI objects
% -- Turn off axes-specific toolbar and enable figure toolbar (for 2019a)
if ~verLessThan('matlab','9.5')
addToolbarExplorationButtons(h_main) % Add the axes controls back to the figure toolbar
h_all.axes.Toolbar.Visible = 'off'; % Hide the integrated axes toolbar
h_all.axes.Toolbar = []; % Remove the axes toolbar data
try %#ok<TRYNC>
tbar_removeList = {'DataManager.Linking','Standard.OpenInspector','Exploration.Rotate','Exploration.Brushing','Standard.EditPlot'};
tbar = findall( h_main, 'tag', 'FigureToolBar');
tbarbuttons = findall(tbar);
delete(tbarbuttons(arrayfun(@(el)isgraphics(el)&&isprop(el,'tag')&&any(strcmp(el.Tag,tbar_removeList)),tbarbuttons)));
end
end
% -- Datacursor --
dcm_obj = datacursormode(h_main);
% defaultDatatipFunction = get(dcm_obj,'UpdateFcn');
set(dcm_obj,'Enable','on');
% -- Scalebar --
try
sb_obj = TNTscalebar(h_all.axes,'Visible','off');
TNTscalebar.addToogle(h_main);
catch
% TNTscalebar requires a newer matlab version
sb_obj = [];
end
% -- Setup and input parsing --
% These variables are accessed/modified across different functions of the GUI
allFramesCandidateData = []; % Computed on demand for histogram plots
allFramesRefinementData = []; % Computed on demand for histogram plots
use_flim = false; % Plot FLIM image
cm_maps = {@cmap_heat,'hot','gray','jet','hsv',@cmap_isoluminant65,@cmap_isoluminant75,@cmap_isoluminant70r,@cmap_rainbow_bgyrm};% List of available colormaps
cm_names = {'heat','hot','B/W','jet','hsv','iso65','iso75','iso70r','Rainbow'};
cm_ind = 1; % Default colormap
cm_ind_inactive = 7; % Default colormap for FLIM
cm_invert = false; % invert colormap
img_gamma = 1; % Gamma factor for plotting
mode = 'movie'; % 'movie' 'candidate'/'refinement'/'tracking'
traj_lifetime = 0; % Trajectories are kept for display for traj_lifetime after the particles last appearance
nr_track_colors = 20; % Size of colorpool to color tracks
traj_displayLength = inf; % Tracking data is displayed for the last traj_displayLength frames only (with respect to the current frame).
movie = []; % Set by parse_inputs_and_setup depending on 'movieOrTNTfile'
movieLT = []; % Set by parse_inputs_and_setup depending on 'movieOrTNTfile'
candidateData = {}; % Set by parse_inputs_and_setup depending on 'candidateDataOrTNTfile'
id_tracks = []; % Unique ids for the tracks. If tracks are numbered continously from 1 to N, this is identical to the track index.
cell_traj = {}; % Each cell saves the data for one track. Is initialized by parse_inputs_and_setup.
n_tracks = 0;
titlename = ''; % (file)name to display in the window title
metadata = struct([]); % meta data for the file. Can contain fields: pixelsize (nm), framerate (1/s), filename
% TNTdata = struct([]); % Keep TNTdata
parse_inputs_and_setup(nargin);
if importMode
set(h_all.panel_tabs,'Visible','off');
set(h_all.panel_tabgroup,'Title','General options');
set(h_all.button_preview,'Callback',@generatePreview);
set(h_all.button_selectFile,'Callback',@callback_selectFile);
set(h_all.button_SendToTNT,'Callback',@callback_sendToTNT);
set(h_all.edit_firstFrame,'Callback',{@callback_IntEdit,1,inf});
set(h_all.edit_lastFrame,'Callback',{@callback_IntEdit,1,inf});
set(h_all.edit_binFrame,'Callback',{@callback_IntEdit,1,inf});
set(h_all.cbx_useTimegate, 'Callback', @callback_toggleTimegate);
set(h_all.edit_tgStart, 'Callback', {@callback_IntEdit,0,inf});
set(h_all.edit_tgEnd, 'Callback', {@callback_IntEdit,0,inf});
set(h_all.button_showTCSPC, 'Callback', @callback_showTCSPC);
% disable player GUI
set(findall(h_all.panel_player,'Enable','on','Type','UIControl','-not','Style','text'),'Enable','off');
else
createTabs(h_all.panel_tabgroup,h_all.panel_tabs); % Create tabbed UI
h_all = guihandles(h_main); % Get handles of all GUI objects. Refresh.
end
set(h_main,'Position',[1 1 0 1].*get(h_main,'Position')+[0 0 1 0].*(get(h_all.panel_tabgroup,'Position') *[2; 0; 1; 0])); % Adjust with
movegui(h_main,'center');
tracksVisibleInFrame = {}; % tracksVisibleInFrame{frame} is list of all track numbers visible in frame 'frame'
nr_VisibleTracksInFrame = []; % Number of visible tracks in each frame.
maxNr_visibleTracksInFrame = 0; % Maximum number of tracks concurrently visible in one frame
compute_tracksVisibleInFrame(); % Sets tracksVisibleInFrame, nr_VisibleTracksInFrame and maxNr_visibleTracksInFrame.
% Set up vars for filters
candidateDataUnfiltered = candidateData;
refinementDataUnfiltered = refinementData;
trackingDataUnfiltered = trackingData;
postprocDataUnfiltered = postprocData;
candidateDataFilter = cellfun(@(d)true(size(d,1),1),candidateDataUnfiltered,'UniformOutput',false);
refinementDataFilter = cellfun(@(d)true(size(d,1),1),refinementDataUnfiltered,'UniformOutput',false);
trackingDataFilter = true(size(trackingDataUnfiltered,1),1);
postprocDataFilter = true(size(postprocDataUnfiltered,1),1);
% Drift correction
driftcalc = zeros(size(movie,3),2); % Might be empty if movie was empty
driftcand = driftcalc;
driftref = driftcalc;
drifttrack = driftcalc;
driftpost = driftcalc;
% Reconstruction
reconstruction_maxPrecision = inf; % nm, Accept all
reconstruction_clusterMinMember = 0; % Disable clustering
reconstruction_clusterMaxDistance = 50; % nm
% MIET conversion
mietcurve = struct();
% ---------------------------
% Show the GUI!
% (We start invisible in case a movie is loaded during parse_inputs_and_setup)
set(h_main,'visible','on');
set(h_main,'CurrentAxes',h_all.axes);
% axes(h_all.axes); % Select axis for drawing plots. In some versions this also forces visablity.
% -- Setup UI elements --
set(h_all.toptext,'ButtonDownFcn',@callback_Goto); % For text elements this unfortunately only fires for right clicks.
% Buttons
set(h_all.button_movieMode,'Callback', {@callback_changeMode,'movie'});
set(h_all.button_candidateMode,'Callback', {@callback_changeMode,'candidate'});
set(h_all.button_refinementMode,'Callback', {@callback_changeMode,'refinement'});
set(h_all.button_trackingMode,'Callback', {@callback_changeMode,'tracking'});
set(h_all.button_postprocMode,'Callback', {@callback_changeMode,'postproc'});
set(h_all.but_play,'Callback',@playCallback);
set(h_all.but_contrast,'Callback',@contrastCallback);
set(h_all.but_autocontrast,'Callback',@autocontrastCallback);
set(h_all.but_autocontrast,'TooltipString',sprintf('Set contrast automatically.\n The used algorithm can be selected in the popup menu to the right.\n Press and hold "Shift" key during playback to adjust contrast automatically for each frame.\n In FLIM mode, press "Ctrl" key to adjust intensity contrast.'));
set(h_all.popup_autocontrast, 'TooltipString', sprintf('Algorithm used for autocontrast.\n Spots: Emphasize highest 25%% intensity values.\n Min/Max: Spans all values.\n 98%% range: Cuts the lower and upper 1%% of intensities. '));
set(h_all.popup_export, 'TooltipString', sprintf('These options export an RGB image of either the current frame or the whole stack with the current display options (colormap, contrast/limits, zoom).\n The images contain the markers for the localisations/tracks and for single frames also any set datatips.\n - Tiff (Stack)\n - Gif (Stack); Note: the GIF''s playback speed is set to the current FPS.\n - Tiff (Frame)\n - Png (Frame)\n\nThese options export the raw data (intensity / fast lifetime) with the native resolution and scale and without any overlay.\n - Tiff (Stack, int)\n - Tiff (Stack, tau)\n - Workspace (int)\n - Workspace (tau)\n'));
set(h_all.but_distribution,'Callback',@distributionCallback);
set(h_all.but_2d_distribution,'Callback',@distribution2DCallback);
set(h_all.but_weighted_distribution,'Callback',@distributionWeightedCallback);
% Slider
% Enableing/disabling is done in loadMovie()
hLstn = addlistener(h_all.slider,'ContinuousValueChange',@updateSlider); %#ok<NASGU> % Add event listener for continous update of the shown slider value
% Edit fields
set(h_all.edit_FPS,'String',sprintf('%.1f',FPS), 'Callback', @fpsCallback);
set(h_all.edit_distributionBins, 'Callback', {@callback_IntEdit,1,inf});
setNum(h_all.edit_distributionBins, 50, true);
set(h_all.edit_distributionRange,'Callback',{@callback_FloatEdit,0,100});
setNum(h_all.edit_distributionRange,100);
set(h_all.cb_distribution_allFrames,'Value',true);
set(h_all.edit_gamma,'Callback',@gammaCallback);
setNum(h_all.edit_gamma,img_gamma);
% Checkbox
set(h_all.cb_invert, 'Value', cm_invert, 'Callback',@setColormap);
set(h_all.cb_flim, 'Value', use_flim, 'Callback',@flimCallback);
% Popupmenu
set(h_all.button_export, 'Callback', @exportCallback);
set(h_all.popup_distribution, 'String', 'No data');
set(h_all.popup_distribution_second, 'String', 'No data');
set(h_all.popup_filterParam, 'String', 'No data');
set(h_all.popup_reconstruct_mean, 'String', 'No data');
createColormapPopup(h_all.popup_colormap, cm_maps, cm_names);
set(h_all.popup_colormap, 'Callback', @setColormap);
set(h_all.popup_colormap, 'Value', cm_ind);
% Filtering panel
set(h_all.but_applyFilter, 'Callback', @applyFilter);
set(h_all.but_filterInsert, 'Callback', @callback_filter_insertParam);
set(h_all.but_showList, 'Callback', @showList);
set(h_all.but_exportList, 'Callback', @exportList);
set(h_all.but_exportWS, 'Callback', @exportWS);
set(h_all.but_resetFilter, 'Callback', @resetFilter);
% Reconstruction panel
set(h_all.but_reconstruct,'Callback',@callback_reconstruct);
set(h_all.but_reconstruct_mean,'Callback',{@callback_reconstruct,true});
set(h_all.but_reconstruct_options,'Callback',@callback_reconstruction_options);
set(h_all.edit_reconstruct_res,'Callback',{@callback_FloatEdit,1,1e3});
set(h_all.edit_reconstruct_pixelsize,'Callback',{@callback_FloatEdit,1,1e4});
set(h_all.edit_reconstruct_locprec,'Callback',{@callback_FloatEdit,0,1e4,'includeNaN'}); % Allow nan
% if isfield(metadata,'pixelsize')&&~isempty(metadata.pixelsize)&&~isnan(metadata.pixelsize)
% if metadata.pixelsize < 1 % Guess that it's in um
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize*1e3);
% else % Guess that it's in nm
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize);
% end
% % Try to replace guess
% if isfield(metadata,'pixelsize_unit')&&ischar(metadata.pixelsize_unit)
% switch strtrim(metadata.pixelsize_unit)
% case 'nm'
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize);
% case [char(181) 'm']
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize*1e3);
% case 'mm' % not really microscopy anymore ;)
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize*1e6);
% case 'cm'
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize*1e7);
% case 'm'
% set(h_all.edit_reconstruct_pixelsize,'Value',metadata.pixelsize*1e9);
% end
% end
% end
% Drift panel
set(h_all.but_drift_calc,'Callback',@calcDrift);
set(h_all.but_drift_apply,'Callback',{@callback_applyDrift,true});
set(h_all.but_drift_reset,'Callback',{@callback_applyDrift,false});
set(h_all.but_drift_show,'Callback',@callback_showDrift);
set(h_all.edit_drift_res,'Callback',{@callback_FloatEdit,1,inf});
set(h_all.edit_drift_rmax,'Callback',{@callback_FloatEdit,0.01,100});
set(h_all.edit_drift_seg,'Callback',{@callback_IntEdit,1,100000});
set(h_all.but_drift_export,'Callback',@callback_exportDrift);
set(h_all.but_drift_import,'Callback',@callback_importDrift);
% MIET panel
set(h_all.but_MIET_apply,'Callback',@callback_applyMIETcurve);
set(h_all.but_MIET_show,'Callback',@callback_showMIETcurve);
set(h_all.but_MIET_file,'Callback',@callback_importMIETcurve);
% -- Candidate UI elements --
% -- Refinement UI elements --
% -- Tracking UI elements --
set(h_all.edit_lifetime,'String',sprintf('%i',traj_lifetime), 'Callback', @callback_TrajLifetime);
set(h_all.edit_colors,'String',sprintf('%i',nr_track_colors), 'Callback', @callback_trackColors);
set(h_all.edit_trajDisplayLength,'String',sprintf('%i', traj_displayLength), 'Callback', @callback_dispLength);
% -- Timer -> this controls playing the movie --
h_all.timer = timer(...
'ExecutionMode', 'fixedDelay', ... % Run timer repeatedly
'Period', round(1/FPS*1000)/1000, ... % Initial period is 1 sec. Limited to millisecond precision
'TimerFcn', @onTimerUpdate, ...
'StartFcn', @onTimerStart, ...
'StopFcn', @onTimerStop); % Specify callback
% Store handles to the plot objects (which is faster)
% Handles are set on first use (mostly in plotFrame)
linehandles = -1*ones(maxNr_visibleTracksInFrame,1); % Note: Size can increase dynamically if more lines are needed.
linehandleNr_to_TrackNr = -1*ones(maxNr_visibleTracksInFrame,1); % Stores which track the linehandle is assigned to
dothandle_fit = -1;
dothandle_cand = -1;
imagehandle = -1;
% Draw the marker color depending on background color
track_colors = [];
marker_color = [];
marker_fill_color = [];
drawColors(nr_track_colors);
% -- Variables for playback --
timePerFrame = round(1/FPS*1000)/1000; % limit to millisecond precision
elapsed_time = 0;
frame = 1;
%% initPlot
% Plot first frame to get limits right
% Set x,y,color limits
xl = [];
yl = [];
zl = [];
zl_alpha = [];
initPlot();
%%
% -- Change into the right mode (candidate/refinement/tracking) --
callback_changeMode();
% h_all.axes.HandleVisibility = 'callback'; % Prevents overplotting from outside
% For is_blocking==true we stop scripts/functions
% calling the GUI until the figure is closed
if(is_blocking)
uiwait(h_main);
drawnow; % makes figure disappear instantly (otherwise it looks like it is existing until script finishes)
end
% --- Nested Functions ---
% Change visualizer into the chosen mode 'movie' 'candidate','refinement','tracking'
% and display its relevant content.
% If "modus" input is given, the mode is set to "modus". Its
% implemented this way to use one callback for all buttons selecting the modes.
function callback_changeMode(~,~,modus)
% Note: nargin>2 is true if callback was invoked by a button
% (and not from a direct call in this file)
if nargin>2
% Do nothing if the current modes button is pressed again
if strcmp(modus,mode)
return
end
mode = modus;
end
DEFAULT_COLOR = [0.941,0.941,0.941]; % Default color of buttons.
SELECTED_COLOR = [0.65, 0.9, 0]; % Color of selected button.
%Reset button colors
set(h_all.button_movieMode,'BackgroundColor', DEFAULT_COLOR);
set(h_all.button_candidateMode,'BackgroundColor', DEFAULT_COLOR);
set(h_all.button_refinementMode,'BackgroundColor', DEFAULT_COLOR);
set(h_all.button_trackingMode,'BackgroundColor', DEFAULT_COLOR);
set(h_all.button_postprocMode,'BackgroundColor', DEFAULT_COLOR);
% Set all mode specific panels invisible
% set(h_all.panel_tracking,'Visible','off');
% set(h_all.panel_histogram,'Visible','off');
set(h_all.panel_tabgroup,'Visible','off');
isTimerOn = strcmp(get(h_all.timer, 'Running'), 'on');
if isTimerOn
stop(h_all.timer);
end
% Delete all graphics objects, except the movie frame and invalidate all handles
resetGraphics();
% Delete active datatip
% WARNING this also deletes other hggroup objects associated with the figure which are also invisible and draggable.
delete(findall(h_main,'Type','hggroup','HandleVisibility','off','Draggable','on'));
% Mode specific changes (setting datatip function, highlight buttons etc.)
switch mode
case 'movie'
set(dcm_obj,'UpdateFcn',{@modeSpecificDatatipFunction});
set(h_all.button_movieMode,'BackgroundColor', SELECTED_COLOR);
set(h_all.popup_distribution, 'String', 'No data');
set(h_all.popup_distribution_second, 'String', 'No data');
set(h_all.popup_filterParam, 'String', 'No data');
set(h_all.popup_reconstruct_mean, 'String', 'No data');
case 'candidate'
set(dcm_obj,'UpdateFcn',{@modeSpecificDatatipFunction});
set(h_all.button_candidateMode,'BackgroundColor', SELECTED_COLOR);
set(h_all.popup_distribution, 'String', candidateParams);
set(h_all.popup_distribution_second, 'String', candidateParams);
set(h_all.popup_reconstruct_mean, 'String', candidateParams);
set(h_all.popup_filterParam, 'String', matlab.lang.makeValidName(candidateParams));
% set(h_all.panel_histogram,'Visible','on');
set(h_all.panel_tabgroup,'Visible','on');
set(h_all.but_MIET_apply,'Enable','off');
case 'refinement'
set(dcm_obj,'UpdateFcn',{@modeSpecificDatatipFunction});
set(h_all.button_refinementMode,'BackgroundColor', SELECTED_COLOR);
set(h_all.popup_distribution, 'String', refinementParams);
set(h_all.popup_distribution_second, 'String', refinementParams);
set(h_all.popup_reconstruct_mean, 'String', refinementParams);
set(h_all.popup_filterParam, 'String', matlab.lang.makeValidName(refinementParams));
% set(h_all.panel_histogram,'Visible','on');
set(h_all.panel_tabgroup,'Visible','on');
set(h_all.but_MIET_apply,'Enable','off');
case 'tracking'
initializeLinehandles(); %Initializes all needed line handles, if this is uncommented, linehandles are created on the fly
set(dcm_obj,'UpdateFcn',{@modeSpecificDatatipFunction});
set(h_all.button_trackingMode,'BackgroundColor', SELECTED_COLOR);
set(h_all.popup_distribution, 'String', trackingParams);
set(h_all.popup_distribution_second, 'String', trackingParams);
set(h_all.popup_reconstruct_mean, 'String', trackingParams);
set(h_all.popup_filterParam, 'String', matlab.lang.makeValidName(trackingParams));
% set(h_all.panel_histogram,'Visible','on');
% set(h_all.panel_tracking,'Visible','on');
set(h_all.panel_tabgroup,'Visible','on');
set(h_all.but_MIET_apply,'Enable','off');
case 'postproc'
set(dcm_obj,'UpdateFcn',{@modeSpecificDatatipFunction});
set(h_all.button_postprocMode,'BackgroundColor', SELECTED_COLOR);
set(h_all.popup_distribution, 'String', postprocParams);
set(h_all.popup_distribution_second, 'String', postprocParams);
set(h_all.popup_reconstruct_mean, 'String', postprocParams);
set(h_all.popup_filterParam, 'String', matlab.lang.makeValidName(postprocParams));
% set(h_all.panel_histogram,'Visible','on');
set(h_all.panel_tabgroup,'Visible','on');
if isstruct(mietcurve) && isfield(mietcurve,'z_theo') && any(strcmp(postprocParams,'lt-tau'))
set(h_all.but_MIET_apply,'Enable','on');
end
otherwise
error('Unkown mode ''%s''!', mode);
end
if importMode
set(h_all.panel_tabgroup,'Visible','on');
end
% Select first histogram entry (There should always be a first entry!)
% If not set, this runs into problems if selecting entry X in some
% mode and there are less then X parameters when the mode is switched.
set(h_all.popup_distribution, 'Value', 1);
set(h_all.popup_distribution_second, 'Value', 1);
set(h_all.popup_filterParam, 'Value', 1);
set(h_all.popup_reconstruct_mean, 'Value', max([1 find(strcmp(get(h_all.popup_reconstruct_mean, 'String'),'lt-tau'),1)]));
% Resize GUI
resizeGUIforMode();
% Replot
updateFrameDisplay();
if isTimerOn
start(h_all.timer);
end
end
% Delete all graphics objects, except the movie frame and invalidate all handles
function resetGraphics()
allHandles = get(h_all.axes,'Children');
if imagehandle ~= -1 % Remove image handle from list
allHandles(allHandles==imagehandle) = [];
end
delete(allHandles);
dothandle_fit = -1;
dothandle_cand = -1;
linehandles = -1*ones(maxNr_visibleTracksInFrame,1);
end
% Update size of GUI, show mode specific panels
function resizeGUIforMode()
units = 'characters';
BOTTOM_SPACING = 0.5;
% Get position of last element in GUI (mode dependent)
if importMode
if strcmpi(get(h_all.panel_importOptions,'Visible'),'on')
lowestUI = h_all.panel_importOptions;
else
lowestUI = h_all.panel_tabgroup;
end
else
switch mode
case 'movie'
lowestUI = h_all.panel_player;
case {'candidate','refinement','tracking','postproc'}
lowestUI = h_all.panel_tabgroup;
end
end
set(lowestUI,'Units',units);
pos = get(lowestUI,'Position');
diff_height = pos(2)-BOTTOM_SPACING;
if abs(diff_height)>0.1
% Only set positions when they change.
% Remove colorbar if exist, since the automatic resizeing
% is disabled when the axis position is changed.
hasCB = isappdata(h_all.axes,'LayoutPeers') && ~isempty(findobj(h_all.axes.Parent,'Tag','Colorbar'));
if hasCB
colorbar(h_all.axes,'off');
drawnow; % To update the axes position
end
set(h_main,'Units',units);
win_pos = get(h_main,'Position');
win_top_pos = win_pos(2)+win_pos(4); % Save top position
% To resize the figure properly, we first need to move all objects
% inside.. (Matlab ..)
% Except the legend which is a child of the figure (not the axes)
% but is nevertheless positioned relative to the axes.
all_uiObjects = findobj(get(h_main,'Children'),'flat','-not',{'Tag','legend','-or','Tag','Colorbar'});
for iObj = 1:numel(all_uiObjects)
try %#ok<TRYNC>
set(all_uiObjects(iObj),'Units',units);
pos = get(all_uiObjects(iObj),'Position');
pos(2) = pos(2) - diff_height;
set(all_uiObjects(iObj),'Position',pos);
end
end
win_pos(4) = win_pos(4)-diff_height; % Set new window height
win_pos(2) = win_top_pos-win_pos(4); % Keeps the top position constant
set(h_main,'Position', win_pos);
% Reset units back to normalized, so figure resizes "properly" (cough..)
set(h_main,'Units','normalized');
for iObj = 1:numel(all_uiObjects)
try %#ok<TRYNC>
set(all_uiObjects(iObj),'Units','normalized');
end
end
% Restore colorbar
if hasCB
colorbar(h_all.axes);
end
else
set(lowestUI,'Units','normalized');
end
end
% Custom function for datacursor which shows data relevant to the
% current mode when clicking the currently plotted data.
function txt = modeSpecificDatatipFunction(~,event_obj)
% Customizes text of data tips
pos = get(event_obj,'Position');
graphObjHandle = get(event_obj,'Target'); % The target object (line/image) of the cursor
if(isgraphics(graphObjHandle,'image')) % Image is selected
txt = {['X: ',num2str(pos(1))],...
['Y: ',num2str(pos(2))],...
['Intensity: ', num2str(movie(pos(2),pos(1),frame))]};
if ~isempty(movieLT)
txt = [txt,...
{['\tau_{fast}: ', num2str(movieLT(pos(2),pos(1),frame),3) ' ns']}];
end
else % Plotted position is selected
I = get(event_obj, 'DataIndex');
txt = {};
switch mode
case 'movie' % -> Image is selected handled above
case 'candidate'
% Plot all parameters available for selected datapoint in the datacursor window
for iPar=1:numel(candidateParams)
txt = [txt, {[candidateParams{iPar},': ', num2str(candidateData{frame}(I,iPar))]}]; %#ok<AGROW>
end
case 'refinement'
% Plot all parameters available for selected datapoint in the datacursor window
for iPar=1:numel(refinementParams)
txt = [txt, {[refinementParams{iPar},': ', num2str(refinementData{frame}(I,iPar))]}]; %#ok<AGROW>
end
case 'tracking'
handleNr = linehandles==graphObjHandle; % Find lineobject for the selected point
TrackNr = linehandleNr_to_TrackNr(handleNr);
PointData = cell_traj{TrackNr}(I,:); % Data of the selected point
TrackID = sprintf('%i',id_tracks(TrackNr)); % Get track ID from its index (in case TracIDs go from 1 to N without missing numbers, TrackNr==TrackID)
% Plot all parameters available for selected datapoint in the datacursor window
txt = [txt, {['TrackID: ', TrackID]}];
for iPar=2:numel(trackingParams)
txt = [txt, {[trackingParams{iPar},': ', num2str(PointData(iPar-1))]}]; %#ok<AGROW>
end
case 'postproc'
ind_frame = find(postprocData(:,2) == frame);
PointData = postprocData(ind_frame(I),:); % Data of the selected point
% Plot all parameters available for selected datapoint in the datacursor window
for iPar=1:numel(postprocParams)
txt = [txt, {[postprocParams{iPar},': ', num2str(PointData(iPar))]}]; %#ok<AGROW>
end
otherwise
error('Unsupported mode ''%s'' for datatip function.',mode)
end
end
end
% Get numeric value of edit field
function value = getNum(hObj)
value = str2double(get(hObj,'String'));
end
% Set numeric value of edit field
function setNum(hObj,value,isInteger)
% value = num2str(value);
if nargin<3 || isempty(isInteger)
isInteger = false;
end
if isInteger
set(hObj,'String',sprintf('%i',value));
else
set(hObj,'String',sprintf('%.2f',value));
end
end
% % Callback for edit fields containing floats. Checks if a correct
% % number was entered and restricts it to the given bounds.
% function callback_FloatEdit(hObj,~, minVal, maxVal)
% if nargin<3 || isempty(minVal);
% minVal=-inf;
% end
% if nargin<4 || isempty(maxVal);
% maxVal=inf;
% end
%
% % Check if a valid number was entered
% value = str2double(get(hObj, 'String'));
% if isempty(value)
% set(hObj,'ForegroundColor','r');
% set(hObj,'String','INVALID');
% uicontrol(hObj);
% else
% value = max(minVal,value);
% value = min(maxVal,value);
% set(hObj,'ForegroundColor','k');
% set(hObj,'String',sprintf('%.2f',value));
% end
% end
%
% % Callback for edit fields containing integer values. Checks if a correct
% % number was entered and restricts it to the given bounds.
% function callback_intEdit(hObj,~, minVal,maxVal)
% if nargin<3 || isempty(minVal);
% minVal=0;
% end
% if nargin<4 || isempty(maxVal);
% maxVal=inf;
% end
%
% value = round(str2double(get(hObj,'String')));
% if isempty(value)
% set(hObj,'ForegroundColor','r');
% set(hObj,'String','INVALID');
% uicontrol(hObj);
% else
% value = max(minVal,value);
% value = min(maxVal,value);
% set(hObj,'ForegroundColor','k');
% set(hObj,'String',sprintf('%i',value));
% end
% end
% The main function of the application. This plays the movie if the timer is running
function onTimerUpdate(~, ~)
% Progress frame counter, clip at length of movie and stop at last frame.
frame = frame+1;
if(frame >= size(movie,3))
frame = size(movie,3);
updateTopText();
stop(h_all.timer);
end
set(h_all.slider,'Value',frame);
updateTopText()
% Skip frame if computer is too slow drawing
if elapsed_time > timePerFrame
elapsed_time = elapsed_time - timePerFrame;
return;
end
tic_start = tic;
updateFrameDisplay();
elapsed_time = elapsed_time + toc(tic_start)- timePerFrame;
end
% Resets the measured elapsed time since last drawn frame when the timer starts
function onTimerStart(~, ~)
set(h_all.but_play,'String','Pause');
elapsed_time = 0;
end
function onTimerStop(~, ~)
set(h_all.but_play,'String','Play');
updateFrameDisplay();
end
% Sets the limits and plots the first frame
function initPlot()
frame = 1;
elapsed_time = 0;
if isempty(movie)
set(h_all.text_noPreview,'Visible','on');
else
set(h_all.text_noPreview,'Visible','off');
xl = [0.5,size(movie,2)+0.5];
yl = [0.5,size(movie,1)+0.5];
firstImg = movie(:,:,1).^img_gamma;
zl = [min(firstImg(:)), max(firstImg(:))];
if ~isempty(movieLT)
firstImg = movieLT(:,:,1);
zl_alpha = [min(firstImg(:)), max(firstImg(:))];% remeber zl when switching to FLIM
if zl_alpha(1)==zl_alpha(2)
zl_alpha = zl_alpha + [0 1];
end
end
if zl(1)==zl(2)
zl = zl + [0 1];
end
plotFrame(frame);
xlim(h_all.axes,xl);
ylim(h_all.axes,yl);
if use_flim
zl_temp = zl;
zl = zl_alpha;
zl_alpha = zl_temp;
end
caxis(h_all.axes,zl);
if ~isempty(movieLT)
alim(h_all.axes,zl_alpha);
end
end
updateTopText();
% Update scalebar and pixelsize in reconstruction tab
if ~isempty(sb_obj) && ~isempty(metadata) && isstruct(metadata)
if isfield(metadata,'pixelsize') && ~isempty(metadata.pixelsize)
sb_obj.Pixelsize = metadata.pixelsize;
else
sb_obj.Pixelsize = 1;
end
if isfield(metadata,'pixelsize_unit') && ~isempty(metadata.pixelsize_unit)
sb_obj.Unit = [' ',metadata.pixelsize_unit];
else
sb_obj.Unit = '';
end
if isfield(metadata,'pixelsize')&&~isempty(metadata.pixelsize)&&~isnan(metadata.pixelsize)
if isfield(metadata,'pixelsize_unit')&&ischar(metadata.pixelsize_unit)
switch strtrim(metadata.pixelsize_unit)
case 'nm'
rec_pixelsize = metadata.pixelsize;
case [char(181) 'm']
rec_pixelsize = metadata.pixelsize*1e3;
case 'mm' % not really microscopy anymore ;)
rec_pixelsize = metadata.pixelsize*1e6;
case 'cm'
rec_pixelsize = metadata.pixelsize*1e7;
case 'm'
rec_pixelsize = metadata.pixelsize*1e9;
end
else
if metadata.pixelsize < 1 % Guess that it's in um
rec_pixelsize = metadata.pixelsize*1e3;
else % Guess that it's in nm
rec_pixelsize = metadata.pixelsize;
end
end
callback_FloatEdit(h_all.edit_reconstruct_pixelsize,[],rec_pixelsize,rec_pixelsize,false,'%.1f')
end
end
% Prepare FLIM
try
set(h_all.axes,'Alphamap',linspace(0,1,256));% Increase resolution of alpha to 8 bit
catch
set(get(h_all.axes,'ColorSpace'),'Alphamap',linspace(0,1,256));
end
end
% Call to display the current frame as selected by the 'frame' variable
% Also this sets and saves the axis states (e.g. for zooming);
function updateFrameDisplay()
% Needed to minimize interference with other figures the user
% brings into focus. It can be that the images are not plotted to
% the GUI then but to the selected figure window
% set(0,'CurrentFigure',h_main);
% Delete active datatip
% WARNING this also deletes other hggroup objects associated with the figure which are also invisible and draggable.
delete(findall(h_main,'Type','hggroup','HandleVisibility','off','Draggable','on'));
plotFrame(frame);
% Adjust contrast continously if shift key is pressed
modifiers = get(h_main,'currentModifier');
shiftIsPressed = ismember('shift',modifiers);
if(shiftIsPressed)
autocontrastCallback([],[]);
end
% Important! Or Matlab will skip drawing entirely for high FPS
if(MATLAB_2015b_or_newer)
drawnow nocallbacks;
else
drawnow expose update;
end
end
% Plots contents of the frame with the input index iF
function plotFrame(iF)
% Draw frame iF of the movie
if imagehandle == -1
imagehandle = imagesc(h_all.axes,movie(:,:,iF).^img_gamma);
axis(h_all.axes,'image');
setColormap();
return % setColormap() internally calls plotFrame(frame)
end
if use_flim
set(imagehandle,'CData',movieLT(:,:,iF));
set(imagehandle,'AlphaData',movie(:,:,iF).^img_gamma);
else
set(imagehandle,'CData',movie(:,:,iF).^img_gamma);
end
% Draw mode dependent data
switch mode
case 'movie'
% Nothing additional to draw.
case 'candidate'
if iF>numel(candidateData) || isempty(candidateData{iF})
if dothandle_cand ~= -1 % Skip uninitialized handles (must be drawn once)
set(dothandle_cand,'xdata',[],'ydata',[]);
end
return % Jump empty frames
end
% Plot markers of candidates
hold(h_all.axes,'on');
if dothandle_cand == -1 % Draw unitialized handles
dothandle_cand = plot(h_all.axes,candidateData{iF}(:,1), candidateData{iF}(:,2), 's','Color',marker_color,'MarkerSize',5,'MarkerFaceColor', marker_fill_color','DisplayName','Localization');
else % For initialized handles set their data (MUCH faster than plot)
set(dothandle_cand,'xdata',candidateData{iF}(:,1),'ydata',candidateData{iF}(:,2));
end
hold(h_all.axes,'off');
case 'refinement'
if iF>numel(refinementData) || isempty(refinementData{iF})
if dothandle_fit ~= -1 % Skip uninitialized handles (must be drawn once)
set(dothandle_fit,'xdata',[],'ydata',[]);
end
return % Jump empty frames
end
% Plot markers of fitted positions
hold(h_all.axes,'on');
if dothandle_fit == -1 % Draw unitialized handles
dothandle_fit = plot(h_all.axes,refinementData{iF}(:,1), refinementData{iF}(:,2), 'o','Color',marker_color,'MarkerSize',5,'MarkerFaceColor', marker_fill_color ,'Linewidth',1,'DisplayName','Localization');
else % For initialized handles set their data (MUCH faster than plot)
set(dothandle_fit,'xdata',refinementData{iF}(:,1),'ydata',refinementData{iF}(:,2));
end
hold(h_all.axes,'off');
case 'tracking'
% Draw the tracks of currently visible particles
hold(h_all.axes,'on');
handleNr = 1;
for iTr = tracksVisibleInFrame{iF}
% Plot trajectories a) only the last traj_displayLength positions AND b) up to the current frame
mask_toPlot = ((cell_traj{iTr}(:,1)>iF-traj_displayLength) & cell_traj{iTr}(:,1)<=iF);
% We use the next free linehandle. If there is no
% free handle left, we create a new one on the fly.
if (handleNr>numel(linehandles) || linehandles(handleNr) == -1)
linehandles(handleNr) = plot(h_all.axes,cell_traj{iTr}(mask_toPlot, 2), cell_traj{iTr}(mask_toPlot, 3), '.-','Color',track_colors(iTr,:),'Linewidth',1,'DisplayName',sprintf('Track %.0f',handleNr));
linehandleNr_to_TrackNr(handleNr) = iTr;
handleNr = handleNr+1;
else