-
Notifications
You must be signed in to change notification settings - Fork 0
/
prelim_UDS_analysis.m
933 lines (843 loc) · 33.5 KB
/
prelim_UDS_analysis.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
%% prelim_UDS_analysis
% this script uses multiunit activity and filtered LFP traces to ID indices
% of probable upstates. An optional plotting function can be used as an
% additional sanity check
%(c) Constance Holman & Roberto De Filippo
%INPUT
%1. LFP file downsampled to 200 Hz. Rows are channels, and columns are time
%samples, Format = 'DSC-xxxxxx_xH_downsampled.mat'
%2. Files generated by Kilosort2 algorithm (Pachitariu et al., 2016) for spikes orting/multiunit
%analysis, e.g. ('spike_time.npy')
% Required: 'Spikes' package from Harris lab. See https://github.com/cortex-lab/spikes
% Required: 'npy-matlab' package (or equivalent) if Kilosort files in
% python, see https://github.com/kwikteam/npy-matlab
%OUTPUT
% row matrix of start and stop indices of detected upstates
load('your filename here') %downsampled LFP file, rows = channels, columns = time points
fs=200;
mychan= 1;%SELECT which channel to use to extract the 1-4 Hz trace
rec_length=round(length(dsdata)/fs/60);%recording length in minutes
%get spike time information
spikeStruct = loadKSdir(pwd);
rate = 0.1; %spike count bin size
[spikecountovertime]=spikeovertime(spikeStruct.st,rate,rec_length);
spikecountovertime=interp(spikecountovertime,20); %smoothing
spikecountovertime(spikecountovertime<0)=0;
onechan=dsdata(mychan,:);
[s] = spectrogram(onechan,fs/100,1,200,fs,'yaxis');
plim = abs(s);
delta_filtered=mean(plim(1:4,:));%mean 1-4 hz
%gamma_filtered=mean(plim(41:101,:)); %not used in current script
filteredTrace = sgolayfilt(delta_filtered,3,15);
[start_us,stop_us]=search_wrapper(onechan,filteredTrace,fs,mychan,spikecountovertime,rec_length,[]);
%% save US indices for future us (i.e. in batch processing scripts
%final script output
indices = horzcat(start_us,stop_us);
name2save ='US_indices.mat';
save(name2save,'indices')
%% Associated Mini-Functions
%%
function [spikecountovertime]=spikeovertime(st,rate,rec_length)%rate = rate of sampling,e.g. 0.1 sample every 100ms
[spikecountovertime,edges]=histcounts(st,0:rate:60*rec_length);
spikecountovertime=spikecountovertime/rate;
end
%%
function [start_us,stop_us]=search_wrapper(onechan,filteredTrace,fs,mychan,spikecountovertime,rec_length,XY)
%search for stop and start indices of us based on (1) LFP
%and (2) MUA
%TODO make this sequential rather than running script twice...
[start_LFP,stop_LFP] = find_upstates(onechan,filteredTrace,fs,mychan,2); %find upstates according to power frequency
[start_spikes,stop_spikes] = find_upstates(onechan,spikecountovertime,fs,mychan,1);%find upstates according to spike count
% go through detected deflections of LFP
for i=1:numel(start_LFP)
us_lfpmua(start_LFP(i):stop_LFP(i))=1;
end
us_lfpmua(end+1:stop_spikes(end))=0; %append any extra period of elevated mua
%generate final indices to save
start_us=[];
stop_us=[];
%iterate through periods of elevated spiking
for i=1:numel(start_spikes)
if sum(us_lfpmua(start_spikes(i):stop_spikes(i)))~=0 %find deflections in trace that are already contained within periods of elevated spiking
start_us = vertcat(start_us,start_spikes(i)); %save this deflection as an upstate
stop_us = vertcat(stop_us,stop_spikes(i));
end
end
% % %% Optional plotting functions for additional sanity check
% % % TODO: fix bug with axes and way indices are save
% % figure
% % plot(onechan(mychan,:),'k')
% %
% % hold on
% % for i=1: numel(start_us)
% % rectangle('Position',[start_us(i) -1000 stop_us(i)-start_us(i) 2000],'LineStyle', 'none','FaceColor',[246/255 71/255 64/255 0.5])
% % end
% % if ~isempty(XY)
% % for i=1:2: numel(XY(:,1))
% % rectangle('Position',[XY(i,1) -1000 XY(i+1,1)-XY(i,1) 2000],'LineStyle', 'none','FaceColor',[21/255 193/255 47/255 0.5])
% % end
% % end
% % xticks(0:fs*60:fs*rec_length*60)
% % xticklabels(0:60)
% % xlabel('time(m)')
% % title('raw trace')
% % xlim([1 numel(onechan(mychan,:))])
% % ylim([-1000 1000])
% %
% % figure
% % ax1=subplot(3,1,2)
% %
% % % if (filteredTrace) < fs*60*10 %added 12.02.19 by CH for bug in short 190207 RH baseline
% % % p = plot:numel(filteredTrace),filteredTrace,1:numel(filteredTrace),(movmedian(filteredTrace,2000)+std(filteredTrace(1:length(filteredTrace))/2))%added 12.02.19 by CH for bug in short 190207 RH baseline
% % % else
% % p=plot(1:numel(filteredTrace),filteredTrace,1:numel(filteredTrace),(movmedian(filteredTrace,2000)+std(filteredTrace(1:fs*60*10))*2));
% % % end
% % p(1).LineWidth = 2;p(2).LineWidth = 4; p(1).Color='k'
% % title('1-4 Hz power')
% % set(gca,'xticklabel',{[]})
% % hold on
% % for i=1: numel(start_spikes(1,:))
% % rectangle('Position',[start_spikes(i) 0 stop_spikes(i)-start_spikes(i) 50],'LineStyle', 'none','FaceColor',[255/255 49/255 46/255 0.5])
% % end
% % for i=1: numel(start_LFP(1,:))
% % rectangle('Position',[start_LFP(i) 0 stop_LFP(i)-start_LFP(i) 50],'LineStyle', 'none','FaceColor',[71/255 121/255 152/255 0.5])
% % end
% %
% % ax3=subplot(3,1,3)
% % p=plot(1:numel(spikecountovertime),spikecountovertime,1:numel(spikecountovertime),(movmedian(spikecountovertime,2000)+std(spikecountovertime(1:fs*60*10))/2))
% % title('Spike rate/s')
% % p(1).LineWidth = 2;;p(2).LineWidth = 4;; p(1).Color='k'
% % hold on
% % for i=1: numel(start_LFP(1,:))
% % rectangle('Position',[start_LFP(i) 0 stop_LFP(i)-start_LFP(i) 200],'LineStyle', 'none','FaceColor',[71/255 121/255 152/255 0.5])
% % end
% %
% %
% % xticks(0:fs*60:fs*rec_length*60)
% % xticklabels(0:60)
% % xlabel('time(m)')
% % set(gcf,'color','w');
% %
% % ax2=subplot(3,1,1)
% % plot(onechan(mychan,:),'k')
% % set(gca,'xticklabel',{[]})
% % hold on
% % for i=1: numel(start_us)
% % rectangle('Position',[start_us(i) -1000 stop_us(i)-start_us(i) 2000],'LineStyle', 'none','FaceColor',[246/255 71/255 64/255 0.5])
% % end
% % % if isempty(XY)~=1
% % % for i=1:2: numel(XY(:,1))
% % % rectangle('Position',[XY(i,1) -1000 XY(i+1,1)-XY(i,1) 2000],'LineStyle', 'none','FaceColor',[21/255 193/255 47/255 0.5])
% % % end
% % % end
% % title('raw trace')
% % %linkaxes([ax1,ax2,ax3],'x')
% % xlim([1 numel(onechan(mychan,:))/24])
% % fprintf('When RIGHT-click, the point is selected \n When LEFT-click, ZOOM-IN is performed right into the selected point \n When DOUBLE-click, ZOOM-OUT is done \n A) If ENTER is pressed, the selection is terminated. If no point was already selected, the outputs are empty \n B) If BACKSPACE key is pressed, the last selected point isdeleted and the selection continues.')
% %
% % if exist(ginput2(false,'r*')); %X = select rubbish upstates
% % XX=ginput2(false,'r*');
% % for i=2:2:numel(XX(:,1))
% % start_us(start_us>XX(i-1,1)&start_us<XX(i,1))=[];
% % stop_us(stop_us>XX(i-1,1)&stop_us<XX(i,1))=[];
% % end
% % end
end
%%
function [start_temp,stop_temp] = find_upstates(onechan,trace2analyze,fs,klik,mua_or_lfp)
%spike_or_freqpower==1 for lfp
%spike_or_freqpower==2 for mua
upstatelimit=4; %maximum us length in seconds
if (trace2analyze) < fs*60*10 %added 12.02.19 by CH as catch for very short recs (<10 min) baselines
overthreshold =trace2analyze>movmedian(trace2analyze,2000)+2*std(trace2analyze(1:length(trace2analyze)));%added 12.02.19 by CH for bug in 190207RH baseline
else
overthreshold=trace2analyze>movmedian(trace2analyze,2000)+2*std(trace2analyze(1:fs*60*10));
end
start_temp=strfind( [0 overthreshold 0], [ 0 1 ] ); %start upstate
stop_temp=strfind( [0 overthreshold 0], [ 1 0 ] ); %stop upstate
for i=2:numel(start_temp)
if start_temp(i)-stop_temp(i-1)<fs/100*35 %if gap between two overthreshold<350 ms FILL IT!
overthreshold(stop_temp(i-1):start_temp(i))=1;
end
end
start_temp=strfind( [0 overthreshold 0], [ 0 1 ] );
stop_temp=strfind( [0 overthreshold 0], [ 1 0 ] );
%%
if mua_or_lfp==2 %analyze mua, check max and min length of frequency deflections
for i=1:numel(start_temp)
if stop_temp(i)-start_temp(i)<fs/100*10 %no shorter than 20ms
overthreshold(start_temp(i):stop_temp(i))=0; %if so, get rid of it
end
end
for i=1:numel(start_temp)
if stop_temp(i)-start_temp(i)>fs*upstatelimit %no longer than upstate limit
overthreshold(start_temp(i):stop_temp(i))=0;
end
end
%find remaining epochs
start_temp= strfind( [0 overthreshold 0], [ 0 1 ] );
stop_temp= strfind( [0 overthreshold 0], [ 1 0 ] );
% check for epochs at beginning and end of recording
% extend candidate periods to add initial deflection/return to baseline
% 10uV is used here, may have to modify depending on noise
for i=1:numel(start_temp)
if onechan(start_temp(i))>10
while onechan(start_temp(i))>10
if start_temp(i)==1
break
end
start_temp(i)= start_temp(i)-1;
end
end
if onechan(start_temp(i))<-10
while onechan(start_temp(i))<-10
if start_temp(i)==1
break
end
start_temp(i)= start_temp(i)-1;
end
end
end
for i=1:numel(stop_temp)
if onechan(stop_temp(i))>10
while onechan(stop_temp(i))>10
if stop_temp(i)==length(onechan)
break
end
stop_temp(i)= stop_temp(i)+1;
end
end
if onechan(stop_temp(i))<-10
while onechan(stop_temp(i))<-10
stop_temp(i)= stop_temp(i)+1;
end
end
end
% plot(onechan(:,klik))
% hold on
% for i=1: numel(start_spikes(1,:))
% rectangle('Position',[start_spikes(i) 0 stop_spikes(i)-start_spikes(i) 500],'LineStyle', 'none','FaceColor',[1 0 0 0.5])
% end
end
end
%%
% ginput2
% Carlos Adrian Vargas Aguilera (2020). ginput2.m v3.1 (Nov 2009) (https://www.mathworks.com/matlabcentral/fileexchange/20645-ginput2-m-v3-1-nov-2009), MATLAB Central File Exchange. Retrieved October 25, 2020.
function [X,Y,BUTTON,SCALEMAT] = ginput2(varargin)
%GINPUT2 Graphical input from mouse with zoom, pan, plot and scaling.
%
% SYNTAX:
% XY = ginput2;
% XY = ginput2(DoScale); true or false
% XY = ginput2(...,PlotOpt); '.r' for example
% XY = ginput2(...,'KeepZoom'); vs. 'UnZoom'
% XY = ginput2(N,...);
% XY = ginput2(...);
% [X,Y] = ginput2(...);
% [X,Y,BUTTON] = ginput2(...);
% [X,Y,BUTTON,SCALEMAT] = ginput2(...);
%
% INPUT:
% DoScale - Single logical specifying whether the IMAGE should be
% interactively scaled (georeferenced), or it can be the
% 2x4 SCALEMAT matrix for automatically scaling.
% DEFAULT: false (do not scales/georeferences)
% PlotOpt - String and/or parameter/value pairs specifying the drawn
% points optional inputs (see PLOT for details).
% DEFAULT: 'none' (do not plot any point)
% 'KeepZoom' - When finishing selection by default the zoom is
% restored. By using this option this feature is ignored.
% DEFAULT: 'UnZoom' (restores original axis limits)
% N - Number of points to be selected. One of 0,1,2,...,Inf
% DEFAULT: Inf (selects until ENTER or ESCAPE is pressed)
%
% OUTPUT:
% XY - [X(:) Y(:)] axis coordinate(s).
% X - X-coordinate(s).
% Y - Y-coordinate(s).
% BUTTON - Last pressed button.
% SCALEMAT - 2x4 matrix specifying the coordinates of two different
% points (1) and (2) in the Image coordinates (pixels) and
% the User coordinates (data):
% Point 1 Point 2
% Image coord (pixels): [ (I1x,I1y) (I2x,I2y)
% User coord (data) : (U1x,U1y) (U2x,U2y) ]
% to be use for scaling/georeferencing.
%
% DESCRIPTION:
% This program uses MATLAB's GINPUT function to get the coordinates
% of a mouse-selected point in the current figure (see GINPUT for
% details), but with five major improvements:
% 1. ZOOMING (left click)
% 2. PANNING (dragging mouse)
% 3. DELETING (last selected point)
% 4. PLOTING (temporarily the selected points)
% 5. SCALING or GEOREFERENCE IMAGES.
% The differences are:
% a) Obviously, the SCALEOPT and PlotOpt optional arguments.
% b) When click is made outside the axes, it is ignored.
% c) When LEFT-click, ZOOM-IN is performed right into the selected
% point (PANNING).
% d) When RIGHT-click, the point is selected (normal).
% e) When DOUBLE-click, ZOOM-OUT is done.
% f) When MIDDLE-click, ZOOM-RESET is done (see ZOOM for details).
% g) When dragging while pressed left-click PAN is done (until the
% button is released).
% h) When pressed any KEY follows the next rules:
% A) If ENTER is pressed, the selection is terminated. If no point
% was already selected, the outputs are empty's.
% B) If BACKSPACE key is pressed, the last selected point is
% deleted and the selection continues.
% C) If SPACEBAR the mouse current position or NANs coordinates
% are saved, depending whether the mouse was inside or outside
% any of the current figure axes, respectively. In this latter
% case, the selection is NOT counted as one of the N points.
% Besides, when drawing the color is changed. Then, the outputs
% may not be of length N.
%
% NOTE:
% * Optional inputs use its DEFAULT value when not given or [].
% * Optional outputs may or not be called.
% * String inputs may be shortened, as long as they are unambiguous.
% Case is ignored.
% * The function can be used for interactively digitalize/vectorize
% RASTER images with:
% >> ginput(true)
% * The function can be used only as a georeference function with
% >> ginput2(0,true)
% * The scale/georeference only works when the current axes has an
% IMAGE type children (see Image for details).
% * The x and y data from axes and image are changed when scale/
% georeference is used.
% * The drawn points are deleted from the graphics once the selection
% is finished.
% * The priority of the inputs are: N, then SCALEOPT and finally
% PlotOpt. If the first (integer) is missing, the next is taken into
% account (logical or 2x4 matrix) and so on.
%
% EXAMPLE:
% % Selects until ENTER is pressed:
% xy = ginput2;
% % Selects 5 points:
% [x,y] = ginput2(5);
% % Gets pressed button:
% [x,y,button] = ginput2(1);
% % Scales image and select 4 points temporarily coloring them in
% black. Besides to not ZOOM OUT at the end:
% imagesc(peaks(40))
% [x,y,button,scalemat] = ginput2(4,true,'k*','KeepZoom');
% hold on, plot(x,y,'or'), hold off
%
% SEE ALSO:
% GINPUT, PLOT.
%
%
% ---
% MFILE: ginput2.m
% VERSION: 3.1 (Nov 12, 2009) (<a href="matlab:web('http://www.mathworks.com/matlabcentral/fileexchange/authors/11258')">download</a>)
% MATLAB: 7.7.0.471 (R2008b)
% AUTHOR: Carlos Adrian Vargas Aguilera (MEXICO)
% CONTACT: [email protected]
% REVISIONS:
% 1.0 Released. (Jul 09, 2008)
% 2.0 Changed default YESERROR value and fixed a bug there. Changed
% behavior when N==1. Fixed bug with zoom out. Changed default
% selection keys. Changed default selection click mouse: from
% left one to the right one. (Jun 08, 2009)
% 2.1 Fixed bugs related with points deletion. Added new 'KeepZoom'
% feature. (Aug 20, 2009)
% 3.0 Now it PANs when dragging. Updated help. (Nov 05, 2009)
% 3.1 Now returns when N==1 and pressed not predefined KEYS or one
% of DELECTION or RETURN buttons. (Nov 12, 2009)
% DISCLAIMER:
% ginput2.m is provided "as is" without warranty of any kind, under the
% revised BSD license.
% Copyright (c) 2008-2009 Carlos Adrian Vargas Aguilera
% INPUTS CHECK-IN
% -------------------------------------------------------------------------
% PARAMETERS
% Defaults:
X = [];
Y = [];
BUTTON = [];
SCALEMAT = [];
N = Inf;
DoScale = false;
PlotOpt = {'none'};
UnZoom = 'UnZoom';
% Constants KEYs (on my personal keyboard):
DOUBLECLICK = 0;
LEFTCLICK = 1;
MIDDLECLICK = 2;
RIGHTCLICK = 3;
BACKSPACE = 8;
ESCAPE = 27;
LEFTARROW = 28;
RIGHTARROW = 29;
UPARROW = 30;
DOWNARROW = 31;
SPACEBAR = 32;
DELETE = 127;
ASCII = [ ...
33:64 ... UP-KEYS
65:90 ... UP-LETTERS
91:96 ... LOW-KEYS
97:122 ... LOW-LETTERS
123:126 ... LOW-KEY
161:255 ... FOREING
];
% Functionality:
% NOTE: I left all this KEYs because the user may use this special case for
% other special purposes outside this function.
% % First version default:
% % SELECTS = [LEFTCLICK ASCII ESCAPE LEFTARROW RIGHTARROW ...
% % UPARROW DOWNARROW SPACEBAR DELETE];
% % ZOOMIN = RIGHTCLICK;
SELECTS = [RIGHTCLICK SPACEBAR]; % Selection buttons
DELETES = BACKSPACE; % Deletion buttons
FINISHES = []; % Finishes buttons
ZOOMIN = LEFTCLICK; % ZOOM(2) buttons
ZOOMRESET = MIDDLECLICK; % ZOOM RESET buttons
ZOOMOUT = DOUBLECLICK; % ZOOM OUT buttons
% Other parameters
secpause = 0.3; % Seconds to wait for double-click response.
YESERROR = false; % If there is an error with GINPUT, it tells to display
% an ERROR or a WARNING message.
% Checks number of inputs:
if nargout>4
error('CVARGAS:ginput2:tooManyOutputs',...
'At most 4 outputs are allowed.')
end
% Checks N:
if ~isempty(varargin) && ~isempty(varargin{1}) && ...
isfloat(varargin{1})
N = round(abs(varargin{1}(1))); % Forced unique, positive
varargin(1) = []; % integer.
end
% Checks DoScale:
if ~isempty(varargin) && ~isempty(varargin{1}) && ...
((islogical(varargin{1})) || (ndims(varargin{1})==2 && ...
all(size(varargin{1})==[2 4])))
DoScale = varargin{1};
varargin(1) = [];
end
% Checks UnZoom:
if ~isempty(varargin)
if ~isempty(varargin{1}) && ischar(varargin{1})
if strncmpi(varargin(1),'UnZoom' ,max(length(varargin{1}),2))
UnZoom = 'UnZoom';
varargin(1) = [];
elseif strncmpi(varargin(1),'KeepZoom',max(length(varargin{1}),2))
UnZoom = 'KeepZoom';
varargin(1) = [];
end
elseif (length(varargin)>1) && ~isempty(varargin{end}) && ...
ischar(varargin{end})
if strncmpi(varargin(end),'UnZoom' ,max(length(varargin{1}),2))
UnZoom = 'UnZoom';
varargin(end) = [];
elseif strncmpi(varargin(end),'KeepZoom',max(length(varargin{1}),2))
UnZoom = 'KeepZoom';
varargin(end) = [];
end
end
end
% Checks PlotOpt:
if ~isempty(varargin) && ~isempty(varargin{1})
PlotOpt = varargin;
end
clear varargin
% Checks DoScale:
if ~islogical(DoScale)
SCALEMAT = DoScale;
DoScale = true;
end
% SCALES/GEOREFERENCE?:
if DoScale
method = 'linear';
extrap = 'extrap';
ha = gca;
hi = findobj(get(ha,'Children'),'Type','image');
axes(ha)
if ~isempty(hi)
hi = hi(1);
xlim = get(ha,'XLim');
ylim = get(ha,'YLim');
zlim = get(ha,'ZLim');
z = repmat(max(zlim),1,5);
xdata = get(hi,'XData');
ydata = get(hi,'YData');
if isempty(SCALEMAT) % interactively
I1x = round(min(xdata)); I2x = round(max(xdata));
I1y = round(min(ydata)); I2y = round(max(ydata));
% Default (equal):
U1x = I1x; U2x = I2x;
U1y = I1y; U2y = I2y;
hgeo = [];
dlgTitle = 'Georeference image';
lineNo = 1;
while true
% Selects first corner:
theans = ...
questdlg('Select the first corner (1 of 2):',dlgTitle,'OK','OK');
if ~strcmp(theans,'OK'), return, end
pause(secpause)
[I1x,I1y] = ginput2(1,false,'none','UnZoom');
I1x = round(I1x);
I1y = round(I1y);
if ~ishandle(ha), return, end
if (ha==gca) && ~isempty(I1x) && ~isnan(I1x)
axis(ha,[xlim ylim])
hgeo(1) = line([xlim NaN I1x I1x],[I1y I1y NaN ylim],z,'color','m');
prompt = {'X-coordinate at 1st corner:',...
'Y-coordinate at 1st corner:'};
def = {int2str(I1x),int2str(I1y)};
answer = inputdlg(prompt,dlgTitle,lineNo,def);
answer = str2num(char(answer{:}));
break
end
end
axes(ha)
% Checks inputs:
if ~isempty(answer) && isfloat(answer) && (length(answer)==2) && ...
all(isfinite(answer))
U1x = answer(1); U1y = answer(2);
secondcorner = true;
else
secondcorner = false;
warning('CVARGAS:ginput2:incorrectGeoreference',...
'Ignored incorrect georeference corners.')
end
while secondcorner
% Selects second corner:
theans = ...
questdlg('Select the second corner (2 of 2):',dlgTitle,'OK','OK');
if ~strcmp(theans,'OK'), return, end
pause(secpause)
[I2x,I2y] = ginput2(1,false,'none','UnZoom');
I2x = round(I2x);
I2y = round(I2y);
if ~ishandle(ha), return, end
if (ha==gca) && ~isempty(I2x) && ~isnan(I2x) && ...
(I2x~=I1x) && (I2y~=I1y)
axis(ha,[xlim ylim])
hgeo(2) = line([xlim NaN I2x I2x],[I2y I2y NaN ylim],z,'color','c');
prompt = {'X-coordinate at 2nd corner:',...
'Y-coordinate at 2nd corner:'};
def = {int2str(I2x),int2str(I2y)};
answer = inputdlg(prompt,dlgTitle,lineNo,def);
answer = str2num(char(answer{:}));
break
end
end
axes(ha)
% Checks inputs:
if secondcorner && ~isempty(answer) && isfloat(answer) && ...
(length(answer)==2) && all(isfinite(answer))
U2x = answer(1); U2y = answer(2);
else
warning('CVARGAS:ginput2:incorrectGeoreference',...
'Ignored incorrect georeference corners.')
end
% Deletes corner's lines:
if any(ishandle(hgeo))
delete(hgeo(ishandle(hgeo)))
end
% Scale matrix:
SCALEMAT = [I1x I1y I2x I2y; U1x U1y U2x U2y];
else
% Continue
end
else
warning('CVARGAS:ginput2:noImageFound',...
'No image found in the current axes to georeference.')
end
% OK, set the scaling then:
if ~isempty(SCALEMAT)
xdata = interp1(SCALEMAT(1,[1 3]),SCALEMAT(2,[1 3]),xdata,method,extrap);
ydata = interp1(SCALEMAT(1,[2 4]),SCALEMAT(2,[2 4]),ydata,method,extrap);
xlim2 = interp1(SCALEMAT(1,[1 3]),SCALEMAT(2,[1 3]),xlim ,method,extrap);
ylim2 = interp1(SCALEMAT(1,[2 4]),SCALEMAT(2,[2 4]),ylim ,method,extrap);
set(hi,'XData',xdata);
set(hi,'YData',ydata);
set(ha,'XLim' ,sort(xlim2,'ascend'));
set(ha,'YLim' ,sort(ylim2,'ascend'));
% Reverses axis directions:
if diff(xlim)*diff(xlim2)<1
if strcmp(get(ha,'XDir'),'normal')
set(ha,'XDir','reverse')
else
set(ha,'XDir','normal')
end
end
if diff(ylim)*diff(ylim2)<1
if strcmp(get(ha,'YDir'),'normal')
set(ha,'YDir','reverse')
else
set(ha,'YDir','normal')
end
end
end
axis(ha,'normal')
end
% DRAWS?:
if strcmpi(PlotOpt{1},'none')
yesdraw = false;
else
yesdraw = true;
end
% Optional parameters:
if yesdraw
hpoints = [];
% Check for linestyle color:
yescolor = true;
Nplotopt = length(PlotOpt);
yeslinestyle = rem(Nplotopt,2);
if yeslinestyle % Given LineStyle
for k = 1:length(PlotOpt{1})
switch lower(PlotOpt{1}(k))
case 'y', yescolor = false; break
case 'm', yescolor = false; break
case 'c', yescolor = false; break
case 'r', yescolor = false; break
case 'g', yescolor = false; break
case 'b', yescolor = false; break
case 'w', yescolor = false; break
case 'k', yescolor = false; break
otherwise, % no color specified
end
end
end
if ~yescolor && (Nplotopt*yeslinestyle~=1)
for k = yeslinestyle+1:2:Nplotopt % Given 'Color'
if strncmpi(PlotOpt{k},'co',2), yescolor = false; break, end
end
end
if yescolor
contnan = 1;
colors = get(gca,'ColorOrder');
ncolors = size(colors,1);
color = colors(1,:);
end
end
% -------------------------------------------------------------------------
% MAIN
% -------------------------------------------------------------------------
cont = 0;
alim.ha = [];
alim.la = {};
undoPtrFig = [];
while cont<N % Principal loop
% GINPUT:
try
[x,y,button] = ginput(1);
catch % Changed for compatibility.
% GINPUT error:
if YESERROR
error('CVARGAS:ginput2:executionError',lasterr)
else
warning('CVARGAS:ginput2:executionError',lasterr)
if nargout<2 % Fixed BUG 29 SEP, 2008
X = [X Y];
end
return
end
end
% Axes clicked:
ha = gca;
% Gets limits:
if ~any(alim.ha==ha)
alim.ha(end+1) = ha;
alim.la{end+1} = axis;
end
% Sets zoom:
zlim = getappdata(ha,'zoom_zoomOrigAxesLimits');
if isempty(zlim) % Fixed BUG, SEP 2008
zoom reset
zlim = getappdata(ha,'zoom_zoomOrigAxesLimits');
end
% Checks if DOUBLE clicks:
pause(secpause) % Gives time for response
if strcmp(get(gcf,'selectiontype'),'open')
button = DOUBLECLICK;
end
% Checks if ENTER or FINISHES button:
if isempty(button) || ismember(button,FINISHES)
% Finishes selection:
if (N==1) && isempty(X) % New feature v3.1
BUTTON = button;
end
break
end
% Checks if DELETION button:
if ismember(button,DELETES)
if ~isempty(X)
inan = isnan(X(end));
if yesdraw
if ~inan
% Deletes last drawn point:
if ~isempty(hpoints) && ishandle(hpoints(end)) % Fixed bug Aug 2009
delete(hpoints(end)), hpoints(end) = [];
end
elseif yescolor
% Change color as necessary:
contnan = contnan-1;
color = colors(mod(contnan-1,ncolors)+1,:);
end
end
% Deletes the last selected point:
X(end) = [];
Y(end) = [];
BUTTON(end) = [];
% Checks if the last point was NaN:
if ~inan
cont = cont-1;
end
elseif N==1
% Finishes selection: New feature v3.1
BUTTON = button;
break
end
continue
end
% Checks if ZOOM OUT button:
if ismember(button,ZOOMOUT)
undoPtrFig = gcf;
setptr(undoPtrFig,'glassminus')
zoom out
continue
end
% Checks if ZOOM RESET button:
if ismember(button,ZOOMRESET)
zoom reset
continue
end
% Checks if the mouse was inside an axes of the current figure;
lim = axis;
outside = x<lim(1) || x>lim(2) || y<lim(3) || y>lim(4);
% Checks if ZOOM IN with PAN:
if ismember(button,ZOOMIN) && ~outside
% Dragging rectangle:
undoPtrFig = gcf;
setptr(undoPtrFig,'closedhand')
rbbox
ydrag = get(gca,'CurrentPoint');
xdrag = ydrag(1,1)-x;
ydrag = ydrag(1,2)-y;
% Do the PANNING:
if any(abs([xdrag ydrag])>eps*1000000)
% Only PAN (dragging):
lim(1:4) = lim(1:4) - [xdrag xdrag ydrag ydrag];
axis(lim)
else
% PAN (centers the last point) and ZOOM in:
setptr(undoPtrFig,'glassplus')
lim = [x+diff(lim(1:2))/2*[-1 1] y+diff(lim(3:4))/2*[-1 1]];
axis(lim)
zoom(2)
end
continue
end
% Checks if SELECTS button:
if ismember(button,SELECTS)
% Sets NaNs if outside the axes:
if outside
if ~isnumeric(N)
% Change color:
if yesdraw && yescolor
contnan = contnan+1;
color = colors(mod(contnan-1,ncolors)+1,:);
end
% Adds NaNs but the point counters do not take it into account:
X = [X; NaN];
Y = [Y; NaN];
BUTTON = [BUTTON; button];
else
% Ignores the point
end
else
% Draws the result:
if yesdraw
% Search for last point:
x0 = []; y0 = []; z0 = [];
inan = isnan([NaN; X; NaN]);
if ~inan(end-1)
inan = find(inan);
nlastpoints = inan(end)-inan(end-1)-1;
npoints = length(hpoints);
range = npoints-nlastpoints+1:npoints;
hlastaxes = get(hpoints(range),'Parent');
if iscell(hlastaxes), hlastaxes = [hlastaxes{:}]; end
[loc,loc] = ismember(ha,hlastaxes);
if loc
x0 = get(hpoints(range(loc)),'XData');
y0 = get(hpoints(range(loc)),'YData');
z0 = get(hpoints(range(loc)),'ZData');
end
end
holdon = ishold;
if ~holdon, hold on, end
h = plot([x0 x],[y0 y],PlotOpt{:});
% Elevates the value:
z = get(ha,'ZLim'); z = z(2);
set(h,'Zdata',[z0 z])
% Sets the color:
if yescolor
set(h,'Color',color)
end
hpoints = [hpoints; h];
if ~holdon, hold off, end
% Restores limits:
axis(lim)
end
% Centers the selected point if ZOOM-IN: 29 SEP,2008
if all((lim~=zlim(1:4)))
lim = [x+diff(lim(1:2))/2*[-1 1] y+diff(lim(3:4))/2*[-1 1]];
axis(lim)
end
% Saves the result:
X = [X; x];
Y = [Y; y];
BUTTON = [BUTTON; button];
cont = cont+1;
end
continue
end
% Checks if any other button pressed inside the axes:
if ~outside
X = [X; x];
Y = [Y; y];
BUTTON = [BUTTON; button];
cont = cont+1;
else
if N==1 % New feature v3.1
BUTTON = button;
break
end
% ignores the selection
end
end
% Returns pointer.
if ~isempty(undoPtrFig) && ishandle(undoPtrFig)
setptr(undoPtrFig,'arrow')
end
% Deletes drawn points if still exist:
if yesdraw && any(ishandle(hpoints))
delete(hpoints(ishandle(hpoints)))
end
% Returns original limits.
if ~strcmp(UnZoom,'KeepZoom') && ~isempty(alim.ha)
alim.ha(~ishandle(alim.ha)) = [];
for k = 1:length(alim.ha)
temp = axis(alim.ha(k));
if ~all(temp(1:4)==alim.la{k}(1:4))
axis(alim.ha(k),alim.la{k})
end
end
end
% OUTPUTS CHECK-OUT
% -------------------------------------------------------------------------
if nargout<2
X = [X Y];
end
end