forked from petersaj/neuropixels_trajectory_explorer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
neuropixels_trajectory_explorer.m
2751 lines (2146 loc) · 98.3 KB
/
neuropixels_trajectory_explorer.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
%% Neuropixels Trajector Explorer
% neuropixels_trajectory_explorer
% Andy Peters ([email protected])
%
% GUI for planning Neuropixels trajectories with the Allen CCF atlas
%
% Instructions for use:
% https://github.com/petersaj/neuropixels_trajectory_explorer
% TO DO 2.0 update:
% - recording connection
function neuropixels_trajectory_explorer
%% Checks and initialize
% Check MATLAB version
matlab_version = version('-date');
if str2num(matlab_version(end-3:end)) <= 2016
error('Neuropixels Trajectory Explorer requires MATLAB 2016 or later');
end
% Check for dependencies
% (npy-matlab to load in atlas)
if ~exist('readNPY','file')
error('"npy-matlab" code not found, download here and add to matlab path: https://github.com/kwikteam/npy-matlab')
end
if ~license('test','Statistics_Toolbox')
error('MATLAB statistics toolbox required (https://uk.mathworks.com/products/statistics.html)')
end
if ~license('test','Image_Toolbox')
error('MATLAB image processing toolbox required (https://uk.mathworks.com/products/image.html)')
end
% Initialize gui_data structure
gui_data = struct;
%% Load atlas and associated data
% Load in atlas
% Find path with CCF
if ~isdeployed
% (if being run in matlab: find CCF in the matlab path)
allen_atlas_path = fileparts(which('template_volume_10um.npy'));
if isempty(allen_atlas_path)
error('CCF atlas not in MATLAB path (click ''Set path'', add folder with CCF)');
end
elseif isdeployed
% (if being run standalone: use previous user-supplied path, or query if files not available)
load('nte_paths.mat')
allen_atlas_path = nte_paths.allen_atlas_path;
if isempty(allen_atlas_path)
% (use uigetdir_workaround: matlab-issued workaround for R2018a bug)
allen_atlas_path = uigetdir_workaround([],'Select folder with Allen CCF');
end
ccf_present = false;
while ~ccf_present
tv_fn = [allen_atlas_path filesep 'template_volume_10um.npy'];
av_fn = [allen_atlas_path filesep 'annotation_volume_10um_by_index.npy'];
st_fn = [allen_atlas_path filesep 'structure_tree_safe_2017.csv'];
tv_exist = exist(tv_fn,'file');
av_exist = exist(av_fn,'file');
st_exist = exist(st_fn,'file');
ccf_files = {tv_fn,av_fn,st_fn};
ccf_exist = [tv_exist,av_exist,st_exist];
if any(~ccf_exist)
% If CCF not present in specified directory, error out
errordlg([{'Allen CCF files not found: '}, ...
ccf_files(~ccf_exist)],'Allen CCF not found, select path again');
allen_atlas_path = uigetdir_workaround([],'Allen CCF not found, select folder again:');
if allen_atlas_path == 0
return
end
else
% If all CCF files present, save path for future
nte_paths.allen_atlas_path = allen_atlas_path;
nte_paths_fn = which('nte_paths.mat');
save(nte_paths_fn,'nte_paths');
ccf_present = true;
end
end
end
% Load CCF components
tv = readNPY([allen_atlas_path filesep 'template_volume_10um.npy']); % grey-scale "background signal intensity"
av = readNPY([allen_atlas_path filesep 'annotation_volume_10um_by_index.npy']); % the number at each pixel labels the area, see note below
st = load_structure_tree([allen_atlas_path filesep 'structure_tree_safe_2017.csv']); % a table of what all the labels mean
% Create CCF colormap
% (copied from cortex-lab/allenCCF/setup_utils
ccf_color_hex = st.color_hex_triplet;
ccf_color_hex(cellfun(@numel,ccf_color_hex)==5) = {'019399'}; % special case where leading zero was evidently dropped
ccf_cmap_c1 = cellfun(@(x)hex2dec(x(1:2)), ccf_color_hex, 'uni', false);
ccf_cmap_c2 = cellfun(@(x)hex2dec(x(3:4)), ccf_color_hex, 'uni', false);
ccf_cmap_c3 = cellfun(@(x)hex2dec(x(5:6)), ccf_color_hex, 'uni', false);
ccf_cmap = horzcat(vertcat(ccf_cmap_c1{:}),vertcat(ccf_cmap_c2{:}),vertcat(ccf_cmap_c3{:}))./255;
%% Make transform matrix from CCF to bregma/mm coordinates
% Set average stereotaxic bregma-lambda distance, set initial scale to 1
bregma_lambda_distance_avg = 4.1; % Currently approximation
% (translation values from our bregma estimate: AP/ML from Paxinos, DV from
% rough MRI estimate)
bregma_ccf = [570.5,520,44]; % [ML,AP,DV]
ccf_translation_tform = eye(4)+[zeros(3,4);-bregma_ccf,0];
% (scaling "Toronto MRI transform", reflect AP/ML, convert 10um to 1mm)
scale = [0.952,-1.031,0.885]./100; % [ML,AP,DV]
ccf_scale_tform = eye(4).*[scale,1]';
% (rotation values from IBL estimate)
ap_rotation = 5; % tilt the CCF 5 degrees nose-up
ccf_rotation_tform = ...
[1 0 0 0; ...
0 cosd(ap_rotation) -sind(ap_rotation) 0; ...
0 sind(ap_rotation) cosd(ap_rotation) 0; ...
0 0 0 1];
% Create transform matrix (operates as [ML,AP,DV])
ccf_bregma_tform_matrix = ccf_translation_tform*ccf_scale_tform*ccf_rotation_tform;
ccf_bregma_tform = affine3d(ccf_bregma_tform_matrix);
%% Make GUI axes and objects
% Set up the gui
screen_size_px = get(0,'screensize');
gui_aspect_ratio = 1.7; % width/length
gui_width_fraction = 0.6; % fraction of screen width to occupy
gui_width_px = screen_size_px(3).*gui_width_fraction;
gui_position = [...
(screen_size_px(3)-gui_width_px)/2, ... % left x
(screen_size_px(4)-gui_width_px/gui_aspect_ratio)/2, ... % bottom y
gui_width_px,gui_width_px/gui_aspect_ratio]; % width, height
probe_atlas_gui = figure('Toolbar','none','Menubar','none','color','w', ...
'Name','Neuropixels Trajectory Explorer', ...
'Units','pixels','Position',gui_position, ...
'CloseRequestFcn',{@gui_close});
% Set up the atlas axes
axes_atlas = axes('Position',[-0.08,0.05,1,0.9],'ZDir','reverse');
axis(axes_atlas,'vis3d','equal','off','manual'); hold(axes_atlas,'on');
view([30,150]);
caxis([0 300]);
xlim([-5,5]);ylim([-8,6]);zlim([-1,6.5]);
grid_spacing = 0.5;
set(gca,'XTick',floor(min(xlim)):grid_spacing:ceil(max(xlim)));
set(gca,'YTick',floor(min(ylim)):grid_spacing:ceil(max(ylim)));
set(gca,'ZTick',floor(min(zlim)):grid_spacing:ceil(max(zlim)));
grid on;
% Set up the text to display coordinates
gui_position_px = getpixelposition(probe_atlas_gui);
probe_coordinates_text = annotation('textbox','String','No probe selected', ...
'Units','normalized','Position',[0,0,1,1],'VerticalAlignment','top', ...
'FontSize',12,'FontName','Consolas','PickableParts','none');
% Set up the probe area axes
axes_probe_areas = axes('Position',[0.80,0.01,0.15,0.95],'TickDir','in');
axes_probe_areas.ActivePositionProperty = 'position';
probe_areas_plot = image(axes_probe_areas,[0,1],0,0);
axes_probe_areas_probelimits = ...
rectangle(axes_probe_areas, ...
'position',[min(xlim(axes_probe_areas)),0,0,0], ...
'edgecolor','b','linewidth',5);
set(axes_probe_areas,'FontSize',12);
set(axes_probe_areas,'XTick','','YColor','k','YDir','reverse');
ylabel(axes_probe_areas,'Depth (mm)');
axes_probe_areas.YAxisLocation = 'right';
title(axes_probe_areas,'Probe areas');
%% Create menu/buttons
probe_controls_menu = uimenu(probe_atlas_gui,'Text','Probe controls');
uimenu(probe_controls_menu,'Text','Display controls','MenuSelectedFcn',{@popup_controls,probe_atlas_gui});
uimenu(probe_controls_menu,'Text','Add probe','MenuSelectedFcn',{@probe_add,probe_atlas_gui});
uimenu(probe_controls_menu,'Text','Remove selected probe','MenuSelectedFcn',{@probe_remove,probe_atlas_gui});
uimenu(probe_controls_menu,'Text','Set entry','MenuSelectedFcn',{@set_probe_entry,probe_atlas_gui});
uimenu(probe_controls_menu,'Text','Set endpoint','MenuSelectedFcn',{@set_probe_endpoint,probe_atlas_gui});
scaling_menu = uimenu(probe_atlas_gui,'Text','Brain scaling');
uimenu(scaling_menu,'Text','Set bregma-lambda distance','MenuSelectedFcn',{@set_bregma_lambda_distance,probe_atlas_gui});
mesh_areas_menu = uimenu(probe_atlas_gui,'Text','3D areas');
uimenu(mesh_areas_menu,'Text','List areas','MenuSelectedFcn',{@add_area_list,probe_atlas_gui});
uimenu(mesh_areas_menu,'Text','Search areas','MenuSelectedFcn',{@add_area_search,probe_atlas_gui});
uimenu(mesh_areas_menu,'Text','Hierarchy areas','MenuSelectedFcn',{@add_area_hierarchy,probe_atlas_gui});
uimenu(mesh_areas_menu,'Text','Remove areas','MenuSelectedFcn',{@remove_area,probe_atlas_gui});
display_menu = uimenu(probe_atlas_gui,'Text','Display');
name_menu = uimenu(display_menu,'Text','Trajectory areas');
uimenu(name_menu,'Text','Probe position','MenuSelectedFcn',{@set_areas_probe,probe_atlas_gui},'Checked','on')
uimenu(name_menu,'Text','Full trajectory','MenuSelectedFcn',{@set_areas_trajectory,probe_atlas_gui},'Checked','off')
name_menu = uimenu(display_menu,'Text','Region names');
uimenu(name_menu,'Text','Acronym','MenuSelectedFcn',{@set_name_acronym,probe_atlas_gui},'Checked','on')
uimenu(name_menu,'Text','Full','MenuSelectedFcn',{@set_name_full,probe_atlas_gui})
slice_menu = uimenu(display_menu,'Text','Slice');
uimenu(slice_menu,'Text','Anatomical','MenuSelectedFcn',{@visibility_tv_slice,probe_atlas_gui},'Checked','off')
uimenu(slice_menu,'Text','Annotated','MenuSelectedFcn',{@visibility_av_slice,probe_atlas_gui})
object_menu = uimenu(display_menu,'Text','Objects');
uimenu(object_menu,'Text','Brain outline','MenuSelectedFcn',{@visibility_brain_outline,probe_atlas_gui},'Checked','on');
uimenu(object_menu,'Text','Grid','MenuSelectedFcn',{@visibility_grid,probe_atlas_gui});
uimenu(object_menu,'Text','Probe','MenuSelectedFcn',{@visibility_probe,probe_atlas_gui},'Checked','on');
uimenu(object_menu,'Text','3D areas','MenuSelectedFcn',{@visibility_3d_areas,probe_atlas_gui},'Checked','on');
uimenu(object_menu,'Text','Dark mode','MenuSelectedFcn',{@visibility_darkmode,probe_atlas_gui});
connect_menu = uimenu(probe_atlas_gui,'Text','Connect');
manipulator_menu = uimenu(connect_menu,'Text','Manipulator');
uimenu(manipulator_menu,'Text','New Scale MPM','MenuSelectedFcn',{@connect_newscale,probe_atlas_gui});
uimenu(manipulator_menu,'Text','Scientifica Patchstar','MenuSelectedFcn',{@connect_scientifica,probe_atlas_gui});
record_menu = uimenu(connect_menu,'Text','Recording');
uimenu(record_menu,'Text','OpenEphys','MenuSelectedFcn',{@connect_openephys,probe_atlas_gui});
uimenu(record_menu,'Text','SpikeGLX','MenuSelectedFcn',{@connect_spikeglx,probe_atlas_gui});
uimenu(record_menu,'Text','Set recording slot','MenuSelectedFcn',{@set_probe_recording_slot,probe_atlas_gui});
saveload_menu = uimenu(probe_atlas_gui,'Text','Save/Load');
uimenu(saveload_menu,'Text','Save positions','MenuSelectedFcn',{@save_probe_positions,probe_atlas_gui});
uimenu(saveload_menu,'Text','Load positions','MenuSelectedFcn',{@load_probe_positions,probe_atlas_gui});
%%% Buttons
button_fontsize = 12;
% View angle buttons
button_position = [0,0,0.1,0.05];
view_button_h(1) = uicontrol('Parent',probe_atlas_gui,'Style','pushbutton','FontSize',button_fontsize, ...
'Units','normalized','Position',button_position,'String','Coronal','Callback',{@view_coronal,probe_atlas_gui});
view_button_h(end+1) = uicontrol('Parent',probe_atlas_gui,'Style','pushbutton','FontSize',button_fontsize, ...
'Units','normalized','Position',button_position,'String','Sagittal','Callback',{@view_sagittal,probe_atlas_gui});
view_button_h(end+1) = uicontrol('Parent',probe_atlas_gui,'Style','pushbutton','FontSize',button_fontsize, ...
'Units','normalized','Position',button_position,'String','Horizontal','Callback',{@view_horizontal,probe_atlas_gui});
align(view_button_h,'fixed',0.1,'middle');
%% Store initial GUI data
gui_data.tv = tv; % Intensity atlas
gui_data.av = av; % Annotated atlas
gui_data.st = st; % Labels table
gui_data.bregma_lambda_distance_avg = bregma_lambda_distance_avg; % Average bregma-lambda distance
gui_data.bregma_lambda_distance_curr = bregma_lambda_distance_avg; % Set current as average
gui_data.cmap = ccf_cmap; % Atlas colormap
gui_data.ccf_bregma_tform_ref = ccf_bregma_tform; % Reference CCF-bregma transform
gui_data.ccf_bregma_tform = ccf_bregma_tform; % CCF-bregma transform to use
gui_data.structure_plot_idx = []; % Plotted structures
% Store handles
gui_data.handles.structure_patch = []; % Plotted structures
gui_data.handles.axes_atlas = axes_atlas; % Axes with 3D atlas
gui_data.handles.axes_probe_areas = axes_probe_areas; % Axes with probe areas
gui_data.handles.axes_probe_areas_probelimits = axes_probe_areas_probelimits; % Probe location on area plot
gui_data.handles.probe_areas_plot = probe_areas_plot; % Color-coded probe regions
gui_data.handles.slice_plot = surface(axes_atlas,'EdgeColor','none','Visible','off'); % Slice on 3D atlas
gui_data.handles.slice_volume = 'tv'; % The volume shown in the slice
gui_data.probe_coordinates_text = probe_coordinates_text; % Probe coordinates text
% Make 3D rotation the default state
h = rotate3d(axes_atlas);
h.Enable = 'on';
h.ButtonDownFilter = @rotate_clickable; % enable click-to-select during rotation
% Update the slice whenever a rotation is completed
h.ActionPostCallback = @update_slice;
% Set functions for key presses
hManager = uigetmodemanager(probe_atlas_gui);
[hManager.WindowListenerHandles.Enabled] = deal(false);
set(probe_atlas_gui,'KeyPressFcn',@key_press);
set(probe_atlas_gui,'KeyReleaseFcn',@key_release);
% Upload gui_data
guidata(probe_atlas_gui, gui_data);
% Draw brain outline
draw_brain(probe_atlas_gui);
end
function gui_close(probe_atlas_gui,eventdata)
% When closing gui, make sure all timers are ended
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Find all timers derived by the gui
if ~isdeployed
% (only necessary if running from matlab)
curr_timers = timerfindall;
if ~isempty(curr_timers)
gui_timers_idx = cellfun(@(x) x{2} == probe_atlas_gui,{curr_timers(:).TimerFcn});
stop(curr_timers(gui_timers_idx));
delete(curr_timers(gui_timers_idx));
end
end
% Close the gui
delete(probe_atlas_gui);
end
%% Probe controls and slice/brain updating
function key_press(probe_atlas_gui,eventdata)
% Get guidata
gui_data = guidata(probe_atlas_gui);
% If no probes are selected, do nothing
if ~isfield(gui_data,'selected_probe') || isempty(gui_data.selected_probe)
return
end
% Step sizes
step_size_position = 0.1; % position, mm
step_size_rotation = 10; % angle, deg
% Update probe coordinates
ap_offset = 0;
ml_offset = 0;
angle_ap_offset = 0;
angle_ml_offset = 0;
update_probe_flag = false;
switch eventdata.Key
case 'uparrow'
if isempty(eventdata.Modifier)
ap_offset = step_size_position;
elseif any(strcmp(eventdata.Modifier,'shift'))
angle_ap_offset = step_size_position;
elseif any(strcmp(eventdata.Modifier,'alt'))
gui_data.probe(gui_data.selected_probe).dv = ...
gui_data.probe(gui_data.selected_probe).dv - step_size_position;
update_probe_flag = true;
guidata(probe_atlas_gui,gui_data);
end
case 'downarrow'
if isempty(eventdata.Modifier)
ap_offset = -step_size_position;
elseif any(strcmp(eventdata.Modifier,'shift'))
angle_ap_offset = -step_size_position;
elseif any(strcmp(eventdata.Modifier,'alt'))
gui_data.probe(gui_data.selected_probe).dv = ...
gui_data.probe(gui_data.selected_probe).dv + step_size_position;
update_probe_flag = true;
guidata(probe_atlas_gui,gui_data);
end
case 'leftarrow'
if isempty(eventdata.Modifier)
ml_offset = -step_size_position;
elseif any(strcmp(eventdata.Modifier,'shift'))
angle_ml_offset = -step_size_position;
elseif any(strcmp(eventdata.Modifier,'control'))
gui_data.probe(gui_data.selected_probe).angle = ...
mod(gui_data.probe(gui_data.selected_probe).angle + ...
[0;0;-step_size_rotation],360);
update_probe_flag = true;
end
case 'rightarrow'
if isempty(eventdata.Modifier)
ml_offset = step_size_position;
elseif any(strcmp(eventdata.Modifier,'shift'))
angle_ml_offset = step_size_position;
elseif any(strcmp(eventdata.Modifier,'control'))
gui_data.probe(gui_data.selected_probe).angle = ...
mod(gui_data.probe(gui_data.selected_probe).angle + ...
[0;0;+step_size_rotation],360);
update_probe_flag = true;
end
end
% Draw updated trajectory
old_trajectory_vector = get(gui_data.probe(gui_data.selected_probe).trajectory,{'XData','YData'});
set(gui_data.probe(gui_data.selected_probe).trajectory,'XData', ...
old_trajectory_vector{1} + repmat(ml_offset,1,2) + [0,angle_ml_offset]);
set(gui_data.probe(gui_data.selected_probe).trajectory,'YData', ...
old_trajectory_vector{2} + repmat(ap_offset,1,2) + [0,angle_ap_offset]);
% Update position (only if insertion point doesn't change)
if update_probe_flag
update_probe_position(probe_atlas_gui);
end
% Upload gui_data
guidata(probe_atlas_gui, gui_data);
end
function key_release(probe_atlas_gui,eventdata)
% Get guidata
gui_data = guidata(probe_atlas_gui);
% If no probes are selected, do nothing
if ~isfield(gui_data,'selected_probe') || isempty(gui_data.selected_probe)
return
end
% On any key release: update the probe coordinates/position and slice
update_probe_position(probe_atlas_gui);
update_probe_areas_coordinates(probe_atlas_gui);
update_slice(probe_atlas_gui);
end
function update_slice(probe_atlas_gui,varargin)
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Only update the slice if it's visible
if strcmp(gui_data.handles.slice_plot(1).Visible,'on')
% Get trajectory and probe location
trajectory_position = cell2mat(get( ...
gui_data.probe(gui_data.selected_probe).trajectory, ...
{'XData','YData','ZData'})')';
probe_position = permute(cell2mat(permute(get( ...
gui_data.probe(gui_data.selected_probe).line, ...
{'XData','YData','ZData'}),[1,3,2])),[2,3,1]);
if size(probe_position,3) > 1
% If multiple shanks: use vector across shank points
plot_vector = diff(permute(probe_position(1,:,[1,end]),[3,2,1]));
else
% Otherwise: use plane perpendicular to camera viewpoint
% Get current position of camera
curr_campos = campos(gui_data.handles.axes_atlas);
% Get trajectory-camera vector
trajectory_camera_vector = trajectory_position(1,:) - curr_campos;
% Get the vector to plot the plane in (along with probe vector)
plot_vector = cross(trajectory_camera_vector,diff(trajectory_position,[],1));
end
% Get the normal vector of the plane
normal_vector = cross(plot_vector,diff(trajectory_position));
% Get the plane offset through the probe
plane_offset = -(normal_vector*trajectory_position(1,:)');
% Define a plane of points to index
% (the plane grid is defined based on the which cardinal plan is most
% orthogonal to the plotted plane. this is janky but it works)
ml_lim = xlim(gui_data.handles.axes_atlas);
ap_lim = ylim(gui_data.handles.axes_atlas);
dv_lim = zlim(gui_data.handles.axes_atlas);
slice_px_space = 0.03; % resolution of slice to grab
[~,cam_plane] = max(abs(normal_vector./norm(normal_vector)));
switch cam_plane
case 1
[plane_ap_bregma,plane_dv_bregma] = ndgrid(...
ap_lim(1):slice_px_space:ap_lim(2),...
dv_lim(1):slice_px_space:dv_lim(2));
plane_ml_bregma = ...
(normal_vector(2)*plane_ap_bregma+normal_vector(3)*plane_dv_bregma + plane_offset)/ ...
-normal_vector(1);
case 2
[plane_ml_bregma,plane_dv_bregma] = ndgrid(...
ml_lim(1):slice_px_space:ml_lim(2),...
dv_lim(1):slice_px_space:dv_lim(2));
plane_ap_bregma = ...
(normal_vector(3)*plane_dv_bregma+normal_vector(1)*plane_ml_bregma + plane_offset)/ ...
-normal_vector(2);
case 3
[plane_ml_bregma,plane_ap_bregma] = ndgrid(...
ml_lim(1):slice_px_space:ml_lim(2),...
ap_lim(1):slice_px_space:ap_lim(2));
plane_dv_bregma = ...
(normal_vector(2)*plane_ap_bregma+normal_vector(1)*plane_ml_bregma + plane_offset)/ ...
-normal_vector(3);
end
% Transform bregma coordinates to CCF coordinates
[plane_ml_ccf,plane_ap_ccf,plane_dv_ccf] = ...
transformPointsInverse(gui_data.ccf_bregma_tform,plane_ml_bregma,plane_ap_bregma,plane_dv_bregma);
% Grab pixels from (selected) volume
plane_coords = ...
round([plane_ap_ccf(:),plane_dv_ccf(:),plane_ml_ccf(:)]);
plane_coords_inbounds = all(plane_coords > 0 & ...
plane_coords <= size(gui_data.tv),2);
plane_idx = sub2ind(size(gui_data.tv), ...
plane_coords(plane_coords_inbounds,1), ...
plane_coords(plane_coords_inbounds,2), ...
plane_coords(plane_coords_inbounds,3));
switch gui_data.handles.slice_volume
case 'tv'
curr_slice = nan(size(plane_ap_ccf));
curr_slice(plane_coords_inbounds) = gui_data.tv(plane_idx);
curr_slice(curr_slice < 20) = NaN; % threshold values
colormap(gui_data.handles.axes_atlas,'gray');
caxis(gui_data.handles.axes_atlas,[0,255]);
case 'av'
curr_slice = nan(size(plane_ap_ccf));
curr_slice(plane_coords_inbounds) = gui_data.av(plane_idx);
curr_slice(curr_slice <= 1) = NaN; % threshold values
curr_slice(boundarymask(max(curr_slice,0),4)) = 0;
colormap(gui_data.handles.axes_atlas,gui_data.cmap);
caxis(gui_data.handles.axes_atlas,[1,size(gui_data.cmap,1)]);
end
% Update the slice display
set(gui_data.handles.slice_plot, ...
'XData',plane_ml_bregma,'YData',plane_ap_bregma,'ZData',plane_dv_bregma,'CData',curr_slice);
end
end
function set_probe_entry(h,eventdata,probe_atlas_gui)
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Prompt for angles
prompt_text = { ...
'AP position (mm from bregma)', ...
'ML position (mm from bregma)', ...
'Azimuth angle (relative to lambda -> bregma)', ....
'Elevation angle (relative to horizontal)', ...
'Rotation angle'};
new_probe_position_input = inputdlg(prompt_text,'Set probe position',1);
if any(cellfun(@isempty,new_probe_position_input))
error('Not all coordinates entered');
end
new_probe_position = cellfun(@str2num,new_probe_position_input);
% Convert degrees to radians
probe_angle = new_probe_position(3:5);
% Update the probe and trajectory reference
ml_lim = xlim(gui_data.handles.axes_atlas);
ap_lim = ylim(gui_data.handles.axes_atlas);
dv_lim = zlim(gui_data.handles.axes_atlas);
max_ref_length = norm([range(ap_lim);range(dv_lim);range(ml_lim)]);
[x,y,z] = sph2cart( ...
deg2rad(90-probe_angle(1)), ...
deg2rad(180+probe_angle(2)), ...
-max_ref_length);
% Get top of probe reference with user brain intersection point
% (get DV location of brain surface at chosen ML/AP point)
dv_query_bregma = interp1([0,1], ...
[new_probe_position([2,1])',-1; ...
new_probe_position([2,1])',6],linspace(0,1,100));
[ml_query_ccf,ap_query_ccf,dv_query_ccf] = ...
transformPointsInverse(gui_data.ccf_bregma_tform, ...
dv_query_bregma(:,1),dv_query_bregma(:,2),dv_query_bregma(:,3));
atlas_downsample = 5;
dv_ccf_line = interpn( ...
imresize3(gui_data.av,1/atlas_downsample,'nearest'), ...
ap_query_ccf/atlas_downsample, ...
dv_query_ccf/atlas_downsample, ...
ml_query_ccf/atlas_downsample,'nearest');
dv_brain_intersect_idx = find(dv_ccf_line > 1,1);
probe_brain_dv = dv_query_bregma(dv_brain_intersect_idx,3);
% (back up to 0 DV in CCF space)
probe_ref_top_ap = interp1(probe_brain_dv+[0,z],new_probe_position(1)+[0,y],0,'linear','extrap');
probe_ref_top_ml = interp1(probe_brain_dv+[0,z],new_probe_position(2)+[0,x],0,'linear','extrap');
% Set new probe position
probe_ref_top = [probe_ref_top_ml,probe_ref_top_ap,0];
probe_ref_bottom = probe_ref_top + [x,y,z];
trajectory_vector = [probe_ref_top;probe_ref_bottom]';
set(gui_data.probe(gui_data.selected_probe).trajectory, ...
'XData',trajectory_vector(1,:), ...
'YData',trajectory_vector(2,:), ...
'ZData',trajectory_vector(3,:));
% Upload gui_data
gui_data.probe(gui_data.selected_probe).angle = probe_angle;
guidata(probe_atlas_gui, gui_data);
% Update probe and slice
update_probe_position(probe_atlas_gui);
update_probe_areas_coordinates(probe_atlas_gui);
update_slice(probe_atlas_gui);
end
function set_probe_endpoint(h,eventdata,probe_atlas_gui)
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Prompt for angles
prompt_text = { ...
'AP position (mm from bregma)', ...
'ML position (mm from bregma)', ...
'DV position (mm from bregma)', ...
'Azimuth angle (relative to lambda -> bregma)', ....
'Elevation angle (relative to horizontal)', ...
'Rotation angle'};
new_probe_position_input = inputdlg(prompt_text,'Set probe position',1);
if any(cellfun(@isempty,new_probe_position_input))
error('Not all coordinates entered');
end
new_probe_position = cellfun(@str2num,new_probe_position_input);
probe_angle = new_probe_position(4:6);
% Convert degrees to radians
probe_angle_rad = deg2rad(probe_angle(1:2));
% Update the probe and trajectory reference
ml_lim = xlim(gui_data.handles.axes_atlas);
ap_lim = ylim(gui_data.handles.axes_atlas);
dv_lim = zlim(gui_data.handles.axes_atlas);
max_ref_length = norm([range(ap_lim);range(dv_lim);range(ml_lim)]);
[y,x,z] = sph2cart(pi+probe_angle_rad(1),pi-probe_angle_rad(2),max_ref_length);
% Move probe reference (draw line through point and DV 0 with max length)
probe_ref_top_ap = interp1(new_probe_position(3)+[0,z],new_probe_position(1)+[0,y],0,'linear','extrap');
probe_ref_top_ml = interp1(new_probe_position(3)+[0,z],new_probe_position(2)+[0,x],0,'linear','extrap');
probe_ref_top = [probe_ref_top_ml,probe_ref_top_ap,0];
probe_ref_bottom = probe_ref_top + [x,y,z];
trajectory_vector = [probe_ref_top;probe_ref_bottom]';
set(gui_data.probe(gui_data.selected_probe).trajectory, ...
'XData',trajectory_vector(1,:), ...
'YData',trajectory_vector(2,:), ...
'ZData',trajectory_vector(3,:));
% Upload gui_data
gui_data.probe(gui_data.selected_probe).angle = probe_angle;
guidata(probe_atlas_gui, gui_data);
% Update probe and slice
update_probe_position(probe_atlas_gui);
update_probe_areas_coordinates(probe_atlas_gui);
update_slice(probe_atlas_gui);
end
function gui_data = update_probe_position(probe_atlas_gui)
% Update the probe position position relative to trajectory vector angles,
% stored rotation angle, and stored DV position
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Get the trajectory angle
trajectory_vector = cell2mat( ...
get(gui_data.probe(gui_data.selected_probe).trajectory, ...
{'XData','YData','ZData'})');
[trajectory_azimuth_sph,trajectory_elevation_sph] = cart2sph( ...
diff(trajectory_vector(1,:)), ...
diff(trajectory_vector(2,:)), ...
diff(trajectory_vector(3,:)));
% Get probe shank coordinates relative to rotation
probe_rotation_rad = -deg2rad(gui_data.probe(gui_data.selected_probe).angle(3));
probe_angle_rad = [probe_rotation_rad, ...
pi/2-trajectory_elevation_sph, ...
trajectory_azimuth_sph+pi/2];
% Create rotation transform matricies
R_shank = [cos(probe_angle_rad(1)) -sin(probe_angle_rad(1)) 0; sin(probe_angle_rad(1)) cos(probe_angle_rad(1)) 0; 0 0 1];
R_elevation = [1 0 0; 0 cos(probe_angle_rad(2)) -sin(probe_angle_rad(2)); 0 sin(probe_angle_rad(2)) cos(probe_angle_rad(2))];
R_azimuth = [cos(probe_angle_rad(3)) -sin(probe_angle_rad(3)) 0; sin(probe_angle_rad(3)) cos(probe_angle_rad(3)) 0; 0 0 1];
R_probe = R_azimuth*R_elevation*R_shank;
% Rotate and translate default shanks to follow trajectory
shank_translate = trajectory_vector(:,1); % (move to trajectory top)
shank_ref_vec = gui_data.probe(gui_data.selected_probe).reference_vector;
shank_ref_vec_flat = reshape(permute(shank_ref_vec,[3,1,2]),3,[]);
shank_vector_flat = R_probe*shank_ref_vec_flat + shank_translate;
shank_vector = permute(reshape(shank_vector_flat,3,2,[]),[2 3 1]);
% Get current probe (reference shank) DV position
ref_shank = gui_data.probe(gui_data.selected_probe).ref_shank;
dv_target = gui_data.probe(gui_data.selected_probe).dv;
dv_ref = shank_vector(:,ref_shank,3);
new_probe_position = reshape(interp1(dv_ref, ...
reshape(shank_vector,2,[]), ...
dv_target-[diff(dv_ref),0],'linear','extrap'),size(shank_vector));
% Update shank line positions
for curr_shank = 1:size(shank_vector,2)
gui_data.probe(gui_data.selected_probe).line(curr_shank).XData = new_probe_position(:,curr_shank,1);
gui_data.probe(gui_data.selected_probe).line(curr_shank).YData = new_probe_position(:,curr_shank,2);
gui_data.probe(gui_data.selected_probe).line(curr_shank).ZData = new_probe_position(:,curr_shank,3);
end
% Update probe angles
gui_data.probe(gui_data.selected_probe).angle(1:2) = ...
mod(rad2deg([-trajectory_azimuth_sph,trajectory_elevation_sph]) + ...
[90,0],360);
% Upload gui_data
guidata(probe_atlas_gui, gui_data);
end
function update_probe_areas_coordinates(probe_atlas_gui,varargin)
% Update the areas and coordinates for the current probe position
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Get current probe location
probe_vector = permute(cell2mat(permute(get( ...
gui_data.probe(gui_data.selected_probe).line, ...
{'XData','YData','ZData'}),[1,3,2])),[2,3,1]);
n_shanks = size(probe_vector,3);
% Interpolate to extremes of probe range
ml_lim = xlim(gui_data.handles.axes_atlas);
ap_lim = ylim(gui_data.handles.axes_atlas);
dv_lim = zlim(gui_data.handles.axes_atlas);
max_ref_length = norm([range(ap_lim);range(dv_lim);range(ml_lim)]);
sample_points = (-max_ref_length:0.001:max_ref_length)';
probe_sample_points_bregma = reshape( ...
interp1([0,gui_data.probe(gui_data.selected_probe).length], ...
reshape(probe_vector,2,[]), ...
sample_points,'linear','extrap'), ...
[length(sample_points),size(probe_vector,[2,3])]);
probe_sample_points_ccf_flat = ...
round(transformPointsInverse(gui_data.ccf_bregma_tform, ...
reshape(permute(probe_sample_points_bregma,[1,3,2]),[],3)));
inbounds_idx = all(probe_sample_points_ccf_flat > 0 & ...
probe_sample_points_ccf_flat <= size(gui_data.av,[3,1,2]),2);
probe_sample_ccf_idx = ...
sub2ind(size(gui_data.av), ...
probe_sample_points_ccf_flat(inbounds_idx,2), ...
probe_sample_points_ccf_flat(inbounds_idx,3), ...
probe_sample_points_ccf_flat(inbounds_idx,1));
probe_areas = ones(length(sample_points),n_shanks);
probe_areas(inbounds_idx) = gui_data.av(probe_sample_ccf_idx);
% Only plot areas that have index >1 (in-brain)
plot_probe_areas_idx = find(any(probe_areas > 1,2));
probe_areas_plot = probe_areas(plot_probe_areas_idx,:);
% Get insertion coordinate
ref_shank = gui_data.probe(gui_data.selected_probe).ref_shank;
insertion_point = probe_sample_points_bregma( ...
plot_probe_areas_idx(find(probe_areas_plot(:,ref_shank) > 1,1,'first')),:,ref_shank);
if isempty(insertion_point)
% (don't update if there isn't an insertion point)
set(gui_data.probe_coordinates_text,'String','Probe trajectory is outside brain');
return
end
% Get current depth of probe relative to insertion coordinate
probe_depth = pdist2(insertion_point,probe_vector(2,:,ref_shank));
% Get area depths relative to insertion coordinate
probe_areas_plot_depth = pdist2(insertion_point, ...
probe_sample_points_bregma(plot_probe_areas_idx,:,ref_shank))';
% Get colors for all areas (draw white lines between areas)
probe_areas_hexcolors = gui_data.st.color_hex_triplet(probe_areas_plot);
probe_areas_rgbcolors = cell2mat(cellfun(@(x) ...
permute(hex2dec({x(1:2),x(3:4),x(5:6)})'./255,[1,3,2]), ...
probe_areas_hexcolors,'uni',false));
for curr_shank = 1:n_shanks
probe_areas_rgbcolors(imdilate(boundarymask( ...
probe_areas_plot(:,curr_shank)),ones(20,1)),curr_shank,:) = 1;
end
% Get boundaries, centers, and labels for all areas
if ~isfield(gui_data,'display_region_name')
gui_data.display_region_name = 'acronym';
end
probe_area_boundaries = cell(n_shanks,1);
probe_area_centers = cell(n_shanks,1);
probe_area_labels = cell(n_shanks,1);
probe_area_hexcolors = cell(n_shanks,1);
for curr_shank = 1:n_shanks
shank_areas_plot = probe_areas_plot(:,curr_shank);
shank_areas_boundaries_idx = intersect(unique( ...
[find(shank_areas_plot ~= 1,1,'first'); ...
find(diff(shank_areas_plot) ~= 0); ...
find(shank_areas_plot ~= 1,1,'last')]), ...
find(shank_areas_plot ~= 1));
shank_areas_centers_idx = round(shank_areas_boundaries_idx(1:end-1) + ...
diff(shank_areas_boundaries_idx)/2);
probe_area_boundaries{curr_shank} = ...
probe_areas_plot_depth(shank_areas_boundaries_idx);
probe_area_centers{curr_shank} = ...
probe_areas_plot_depth(shank_areas_centers_idx);
probe_area_labels{curr_shank} = ...
gui_data.st.(gui_data.display_region_name)(probe_areas_plot(shank_areas_centers_idx,curr_shank));
probe_area_hexcolors{curr_shank} = ...
probe_areas_hexcolors(shank_areas_centers_idx);
end
% Update area plot and labels
set(gui_data.handles.axes_probe_areas, ...
'YTick',floor(probe_areas_plot_depth(1)):0.5: ...
ceil(probe_areas_plot_depth(end)));
set(gui_data.handles.probe_areas_plot, ...
'XData',1:n_shanks, ...
'YData',probe_areas_plot_depth, ...
'CData',probe_areas_rgbcolors);
probe_area_shank = cellfun(@(x,shank) ones(length(x),1).*shank, ...
probe_area_centers,num2cell(1:n_shanks)','uni',false);
delete(findobj(gui_data.handles.axes_probe_areas,'Type','text'));
text_h = text(gui_data.handles.axes_probe_areas, ...
vertcat(probe_area_shank{:}), ...
vertcat(probe_area_centers{:}),vertcat(probe_area_labels{:}), ...
'FontSize',12,'HorizontalAlignment','center','clipping','on');
switch gui_data.display_region_name
case 'acronym'
set(text_h,'clipping','on')
case 'safe_name'
set(text_h,'clipping','off')
end
% Update probe insertion point
[gui_data.probe(gui_data.selected_probe).insertion_point.XData, ...
gui_data.probe(gui_data.selected_probe).insertion_point.YData, ...
gui_data.probe(gui_data.selected_probe).insertion_point.ZData] = ...
deal(insertion_point(1),insertion_point(2),insertion_point(3));
% Update area plot (user-selected zoom as probe or full trajectory)
probe_depth_limits = probe_depth - ...
[gui_data.probe(gui_data.selected_probe).length,0];
gui_data.handles.axes_probe_areas_probelimits.Position = ...
[0.5,probe_depth_limits(1),n_shanks,diff(probe_depth_limits)];
if ~isfield(gui_data,'display_areas')
gui_data.display_areas = 'probe';
end
axis(gui_data.handles.axes_probe_areas,'tight');
switch gui_data.display_areas
case 'probe'
% Set limits to probe, turn off probe box
ylim(gui_data.handles.axes_probe_areas,probe_depth_limits)
gui_data.handles.axes_probe_areas_probelimits.Visible = 'off';
title(gui_data.handles.axes_probe_areas,'Probe areas');
case 'trajectory'
% Set limits to whole trajectory, turn off probe box
ylim(gui_data.handles.axes_probe_areas,prctile(probe_areas_plot_depth,[0,100]));
gui_data.handles.axes_probe_areas_probelimits.Visible = 'on';
title(gui_data.handles.axes_probe_areas,'Trajectory areas');
end
% Update the text
% (manipulator angles)
probe_angle_text = sprintf('Angle: %.0f%c azimuth, %.0f%cH/%.0f%cV elevation, %.0f%c rotation', ...
gui_data.probe(gui_data.selected_probe).angle(1),char(176), ...
gui_data.probe(gui_data.selected_probe).angle(2),char(176), ...
90-gui_data.probe(gui_data.selected_probe).angle(2),char(176), ...
gui_data.probe(gui_data.selected_probe).angle(3),char(176));
% (probe insertion point and depth)
probe_insertion_text = sprintf('Insertion: % .2f AP, % .2f ML, % .2f DV', ...
insertion_point(2),insertion_point(1),insertion_point(3));
% (probe tip)
probe_tip_text = sprintf('Tip: % .2f AP, % .2f ML, % .2f DV, % .2f depth (Z)', ...
probe_vector(2,[2,1,3],ref_shank),probe_depth);
% (bregma-lambda distance for scaling)
bregma_lambda_text = sprintf('Bregma-Lambda distance: % .2f mm', ...
gui_data.bregma_lambda_distance_curr);
% (connection status)
manipulator_text = [];
recording_text = [];
if isfield(gui_data,'connection')
if isfield(gui_data.connection,'manipulator')
manipulator_text = sprintf('Connected manipulator: %s', ...
gui_data.connection.manipulator.model);
end
if isfield(gui_data.connection,'recording')
recording_text = sprintf('Connected recording: %s', ...
gui_data.connection.recording.software);
end
end
% (combine and update)
probe_text = {probe_angle_text,probe_insertion_text, ...
probe_tip_text,bregma_lambda_text, ...
manipulator_text,recording_text};
set(gui_data.probe_coordinates_text,'String',probe_text(cellfun(@(x) ~isempty(x),probe_text)));
% If recording software is connected, send areas for display
if isfield(gui_data,'connection') && ...
isfield(gui_data.connection,'recording')
send_recording_areas(gui_data, ...
probe_depth, ...
probe_area_boundaries, ...
probe_area_labels, ...
probe_area_hexcolors);
end
% Upload gui_data
guidata(probe_atlas_gui, gui_data);
end
function update_brain_scale(probe_atlas_gui,bregma_lambda_distance)
% Update the scaling of the brain based on the bregma-lambda distance
% Get guidata
gui_data = guidata(probe_atlas_gui);
% Add "rescaling" message
set(gui_data.probe_coordinates_text,'String','RESCALING BRAIN...');
set(gui_data.probe_coordinates_text,'Color','r');
drawnow;
% Get the sizing scale of this mouse to the reference atlas
mouse_scale = bregma_lambda_distance/ ...
gui_data.bregma_lambda_distance_avg;
% Apply scale to reference transform and set to new transform
mouse_scale_tform = eye(4).*[repmat(mouse_scale,3,1);1];
gui_data.ccf_bregma_tform.T = gui_data.ccf_bregma_tform_ref.T*mouse_scale_tform;
% Update current bregma-lambda distance
gui_data.bregma_lambda_distance_curr = bregma_lambda_distance;
% Upload gui_data
guidata(probe_atlas_gui, gui_data);
% Redraw to new scale:
% - Brain outline
draw_brain(probe_atlas_gui);
% - 3D areas
for redraw_area = gui_data.structure_plot_idx
draw_areas(probe_atlas_gui,redraw_area)
end
% - Slice
update_slice(probe_atlas_gui);
% Update probe coordinates
update_probe_areas_coordinates(probe_atlas_gui);
% Restore text color
set(gui_data.probe_coordinates_text,'Color','k')
end
%% Control functions
function view_coronal(h,eventdata,probe_atlas_gui)
% Set coronal view
gui_data = guidata(probe_atlas_gui);
view(gui_data.handles.axes_atlas,[0,0]);
update_slice(probe_atlas_gui);
% (hacky - switch focus back to axes)
set(h,'enable','off');drawnow;set(h,'enable','on');
end
function view_sagittal(h,eventdata,probe_atlas_gui)
% Set sagittal view
gui_data = guidata(probe_atlas_gui);
view(gui_data.handles.axes_atlas,[-90,0]);
update_slice(probe_atlas_gui);
% (hacky - switch focus back to axes)
set(h,'enable','off');drawnow;set(h,'enable','on');
end