-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrp.m
984 lines (838 loc) · 28.5 KB
/
rp.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
function [y,P,epsilon] = rp(varargin)
%
% Minimum input-arguments : 2
% Maximum input-arguments : 6
%
% [R,DM,epsilon] = rp(Y,E,thres_calc,norm,type,algorithm)
%
% Calculates a recurrence plot R from an embedding vector Y and using
% the threshold 'E'. 'DM' is an optional output and is the adjacency- or
% distancematrix. In case you choose the 'var'-fixed threshold selection
% method optional output 'epsilon' will give the actual calculated
% value.
%
%
% Input:
%
% 'Y' is a N-by-M matrix corresponding to N time points
% and M embedding dimensions.
%
% 'norm' (optional) norm for distance calculation in phasespace to
% 'euc' (euclidic) or 'max' (maximum). Default is
% max norm.
%
% 'algorithm' (optional) specify the way of calculating the distance
% matrix here. You can choose from
% ['loops','vector','matlabvector']. Default is
% 'vector'.
%
% 'threshold-calc' (optional) specifies how the threshold epsilon will
% be calculated. There are three options. Set 'threshold-calc' to
% - 'fix' The RP is computed under a fixed threshold epsilon specified by
% input parameter 'E'.
% - 'var' The RP is computed under a fixed threshold epsilon, which
% corresponds to the lower 'E'-quantile (specified by input parameter
% 'E') of the distance distribution of all points in phasespace.
% - 'fan' The RP is computed under a variable threshold epsilon using a
% fixed amount of nearest neighbours in phasespace to compute the
% epsilon-value for each point of the phasespace trajectory
% individually.
% Default is 'fix'.
%
% 'type' (optional) specifies the type of the RP.
% - 'normal' The RP is computed after the definition of Eckmann et
% al.1987
% - 'diagonal' The RP is computed after the definition of Eckmann et
% al.1987 and then line corrected after Kraemer and
% Marwan 2019
% - 'shape' The RP is computed the definition of Eckmann et
% al. 1987 and then shape-converted after J.Donath 2016
% (windowshape 3).
%
% Example:
% N = 300; % length of time series
% x = .9*sin((1:N)*2*pi/70); % exemplary time series
% xVec = embed(x,2,17);
% R = rp(xVec,.1);
% imagesc(R)
% Copyright (c) 2019
% Norbert Marwan, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% Modified by Hauke Krämer,Potsdam Institute for Climate Impact Research,
% Germany http://www.pik-potsdam.de
%
% Contact: [email protected]
%
% 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 2
% of the License, or any later version.
%% check input
narginchk(1,6)
nargoutchk(0,3)
algoLib={'loops','vector','matlabvector'}; % the possible algorithms
try
algorithm = varargin{6};
if ~isa(algorithm,'char') || ~ismember(algorithm,algoLib)
warning(['Specified algorithm should be one of the following possible values:',...
10,sprintf('''%s'' ',algoLib{:})])
end
catch
algorithm = 'vector';
end
typeLib={'normal','diagonal','shape'}; % the possible types
try
type = varargin{5};
if ~isa(type,'char') || ~ismember(type,typeLib)
warning(['Specified RP type should be one of the following possible values:',...
10,sprintf('''%s'' ',typeLib{:})])
end
catch
type = 'normal';
end
methLib={'euc','max'}; % the possible norms
try
meth = varargin{4};
if ~isa(meth,'char') || ~ismember(meth,methLib)
warning(['Specified norm should be one of the following possible values:',...
10,sprintf('''%s'' ',methLib{:})])
end
catch
meth = 'max';
end
thresLib={'fix','var','fan'}; % the possible ways of threshold computation
try
thres = varargin{3};
if ~isa(thres,'char') || ~ismember(thres,thresLib)
warning(['Specified way of calculating threshold should be one of the following possible values:',...
10,sprintf('''%s'' ',thresLib{:})])
end
catch
thres = 'fix';
end
try
e = varargin{2};
catch
e = 1;
end
x = varargin{1};
N = size(x);
if N(1) < N(2)
warning('Embedding dimension is larger than the length of the vector. Please check!')
end
%% init output
%% bind length of input vector in order to have constant iteration bounds while using parallel computing
M=N(1);
%% calculate distance matrix
switch algorithm
case 'loops'
%% calculation with loops
y = zeros(N(1),N(1));
parfor i = 1:M
for j = 1:M
switch lower(meth)
case 'euc'
d = (x(i,:) - x(j,:)).^2;
y(i,j) = sqrt(sum(d));
otherwise
d = abs(x(i,:) - x(j,:));
y(i,j) = max(d);
end
end
end
case 'vector'
%% calculation with vectorisation
x1 = repmat(x,N(1),1);
x2 = reshape(repmat(reshape(x,N(1)*N(2),1),1,N(1))',N(1)*N(1),N(2));
switch lower(meth)
case 'euc'
d = (x1 - x2).^2;
y = sqrt(sum(d,2));
otherwise
d = abs(x1 - x2);
y = max(d,[],2);
end
y = reshape(y,N(1), N(1));
case 'matlabvector'
%% calculation with matlab's vectorisation
switch lower(meth)
case 'euc'
y = squareform(pdist(x));
otherwise
y = squareform(pdist(x,'chebychev'));
end
end
P = y;
if strcmp(thres,'fix')
% apply threshold
y = double(y < e);
epsilon = e;
elseif strcmp(thres,'var')
% get lower (e*100)%-quantile of distance-distribution
epsilon = quantile(P(:),e);
y = double(y < epsilon);
elseif strcmp(thres,'fan')
% compute variable threshold for each point in order to get fixed
% number of nearest neighbours
q = quantile(P,e); % distance that corresponds to the fraction e of rec. points per column
thresholds = repmat(q,N(1),1); % q has to be applied for each row in d
% apply individual thresholds
epsilon = e;
% apply threshold(s)
y=double(y<thresholds);
end
if strcmp(type,'diagonal')
[y, ~] = rp_diagonal(y);
elseif strcmp(type,'shape')
y = shape3(y);
end
end
%%%%% Helper functions %%%%%%
function [Y] = shape3(X)
%==========================================================================
%Creates a new window Y with lenght s based on X. All border diagonals have
%the lenght s in Y.
%==========================================================================
s = floor(size(X,1)/2);
sc = floor(size(X,1)/4);
Y = zeros(size(X,1));
for i = 1:s
for j = 0:sc-1
Y(sc-j+i,sc+j+i) = X(sc-j+i,sc+j+i);
Y(sc-j+i,sc+j+i+1) = X(sc-j+i,sc+j+i+1);
Y(sc+j+i,sc-j+i) = X(sc+j+i,sc-j+i);
Y(sc+j+i,sc-j+i+1) = X(sc+j+i,sc-j+i+1);
end
end
end
function [X_new,dl_new] = rp_diagonal(varargin)
% RP_DIAGONAL RP with corrected lines ...
%
% [RP_new, dl_new] = rp_diagonal(RP)
% computes a new recurrence plot 'RP_new' by altering diagonal line structures
% in the input recurrence plot 'RP': Slubs, but also block structures,
% are deleted in favour of the longest diagonal lines (skeletonization).
% Whenever a diagonal line (starting with the longest lines contained in
% the diagonal line length histogram) encounters an adjacent diagonal
% line, this adjacent line and - recursively - all its consecutive
% adjacent lines, get deleted.
%
% Output:
% You receive the corrected recurrence plot 'RP_new' INCLUDING the line
% of identity. Optional you also receive a matrix containing all lines
% of this new RP. This matrix has three lines and as many columns as
% there are lines in the RP. In the first line the total length of each
% line is stored. In the second and third line, the corresponding line
% and column indices are stored.
%
% Example (CRP toolbox needs to be installed):
% x = sin(linspace(0,5*2*pi,1000));
% xe = embed(x,2,50);
% r = rp(xe,.2);
% [r2, ~] = rp_diagonal(r);
% figure
% subplot(1,2,1)
% imagesc(r), colormap([1 1 1; 0 0 0]), axis xy square
% title('input RP')
% subplot(1,2,2)
% imagesc(r2), colormap([1 1 1; 0 0 0]), axis xy square
% title('diagonal RP')
%
%
% Copyright (c) 2019-
% K.Hauke Kraemer, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% Institute of Geosciences, University of Potsdam,
% Germany
% http://www.geo.uni-potsdam.de
% Norbert Marwan, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.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 2
% of the License, or any later version.
%% check input
narginchk(1,3)
nargoutchk(1,2)
X = varargin{1};
% size of the RP
[N_org,M_org] = size(X);
if N_org~=M_org
error('Input needs to be a squared, binary recurrence matrix')
end
if sum(sum(X>1))~=0 || sum(sum(X<0))~=0 || sum(sum(rem(X,1)))~=0
error('Input needs to be a squared, binary recurrence matrix')
end
% check whether input RP is symmetric
if issymmetric(X)
symm = true;
% if yes, just take the lower triangle
X2 = tril(X);
% convert this RP into a close returns map and just use the upper half
X_cl = convertRP(X2);
% get line distributions
[~, lines_1] = dl_h(X_cl); % black horizontal lines
% % remove lines < 2
% lines_1(:,lines_1(1,:) < 2) = [];
% make a copy of the line matrix
lines_1_copy = lines_1;
Nlines = size(lines_1,2); % number of found lines
% create a close returns map with horizontal lines represented by
% numbers, equal to its lengths
X_hori = zeros(size(X_cl));
for i = 1:size(lines_1,2)
line_ind = lines_1(2,i);
column_ind = lines_1(3,i);
for j = 0:lines_1(1,i)-1
X_hori(line_ind,column_ind+j) = lines_1(1,i);
end
end
else
symm = false;
% if not, store lower triangle in X2 and upper triangle transposed in
% X3
X2 = tril(X);
X3 = triu(X)';
% convert these RPs into close returns maps and just use the upper half
X_cl = convertRP(X2);
X_cl2 = convertRP(X3);
% get line distributions
[~, lines_1] = dl_h(X_cl); % black horizontal lines
[~, lines_2] = dl_h(X_cl2); % black horizontal lines
% make a copy of the line matrices
lines_1_copy = lines_1;
lines_2_copy = lines_2;
Nlines = size(lines_1,2); % number of found lines in lower triangle
Nlines2 = size(lines_2,2); % number of found lines in upper triangle
% create a close returns map with horizontal lines represented by
% numbers, equal to its lengths
X_hori = zeros(size(X_cl));
for i = 1:size(lines_1,2)
line_ind = lines_1(2,i);
column_ind = lines_1(3,i);
for j = 0:lines_1(1,i)-1
X_hori(line_ind,column_ind+j) = lines_1(1,i);
end
end
X_hori2 = zeros(size(X_cl2));
for i = 1:size(lines_2,2)
line_ind = lines_2(2,i);
column_ind = lines_2(3,i);
for j = 0:lines_2(1,i)-1
X_hori2(line_ind,column_ind+j) = lines_2(1,i);
end
end
end
% scan the lines, start with the longest one and discard all adjacent lines
% initialize final line matrix
line_matrix_final = zeros(3,1);
% go through all lines stored in the sorted line matrix
[N,M] = size(X_hori);
for l_ind = 1:Nlines
% check if line is still in the rendered line matrix
if ~ismember(lines_1(:,l_ind)',lines_1_copy','rows')
continue
end
% get index pair for start of the line
linei = lines_1(2,l_ind);
columni = lines_1(3,l_ind);
% copy this line in the final line matrix
line_matrix_final = horzcat(line_matrix_final,lines_1(:,l_ind));
% delete this line from the RP
X_hori = delete_line_from_RP(X_hori,lines_1(:,l_ind));
% go along each point of the line and check for neighbours
l_max = lines_1(1,l_ind);
for l = 1:l_max
% scan each line twice - above and underneth
for index = -1:2:1
% make sure not to exceed RP-boundaries
if linei+index > N | linei+index == 0
break
end
% if there is a neighbouring point, call recursive scan-function
if X_hori(linei+index,columni+l-1)
[X_hori,lines_1_copy]=scan_lines(X_hori,lines_1_copy,...
linei+index,columni+l-1);
end
end
end
end
% if not symmetric input RP, than compute for the upper triangle as well
if ~symm
% initialize final line matrix
line_matrix_final2 = zeros(3,1);
for l_ind = 1:Nlines2
% check if line is still in the rendered line matrix
if ~ismember(lines_2(:,l_ind)',lines_2_copy','rows')
continue
end
% get index pair for start of the line
linei = lines_2(2,l_ind);
columni = lines_2(3,l_ind);
% copy this line in the final line matrix
line_matrix_final2 = horzcat(line_matrix_final2,lines_2(:,l_ind));
% delete this line from the RP
X_hori2 = delete_line_from_RP(X_hori2,lines_2(:,l_ind));
% go along each point of the line and check for neighbours
l_max = lines_2(1,l_ind);
for l = 1:l_max
% scan each line twice - above and underneth
for scan = 1:2
if scan == 1
index = 1;
% make sure not to exceed RP-boundaries
if linei+index > N
break
end
else
index = -1;
% make sure not to exceed RP-boundaries
if linei+index == 0
break
end
end
% if there is a neighbouring point, call recursive scan-function
if X_hori2(linei+index,columni+l-1)
[X_hori2,lines_2_copy]=scan_lines(X_hori2,lines_2_copy,...
linei+index,columni+l-1);
end
end
end
end
end
% build RP based on the histogramm of the reduced lines
X_cl_new = zeros(N,M);
if ~symm
X_cl2_new = zeros(N,M);
end
% fill up close returns map with lines stored in the new line matrix
for i = 1:size(line_matrix_final,2)
l_max = line_matrix_final(1,i);
linei = line_matrix_final(2,i);
columni = line_matrix_final(3,i);
for j = 1:l_max
X_cl_new(linei,columni+j-1) = 1;
end
end
if symm
% revert this close returns map into a legal RP
XX = revertRP(X_cl_new);
X_new = XX + (XX-eye(size(XX)))';
else
% fill up close returns map with lines stored in the new line matrix
for i = 1:size(line_matrix_final2,2)
l_max = line_matrix_final2(1,i);
linei = line_matrix_final2(2,i);
columni = line_matrix_final2(3,i);
for j = 1:l_max
X_cl2_new(linei,columni+j-1) = 1;
end
end
% revert this close returns map into a legal RP
XX = revertRP(X_cl_new);
XXX= revertRP(X_cl2_new);
X_new = XX + (XXX-eye(size(XXX)))';
end
% bind optional output
% get line distributions of new RP
if nargout > 1
[~, lines3] = dl_e(X_new);
dl_new = sortrows(lines3','descend')';
end
end
function [a_out, b_out] = dl_e(X)
% DL_E Mean of the diagonal line lengths and their distribution
% additionally with the corresponding indices of the lines.
% A=DL_E(X) computes the mean of the length of the diagonal
% line structures in a recurrence plot.
%
% [A B]=DL_E(X) computes the mean A and the lengths of the
% found diagonal lines, stored in the first line of B. B is a 3 line
% matrix storing the found diagonal line lengths in its columns. Line 2
% and 3 store the indices i, j of the startpoint of the diagonal line
% stored in the same column in the first line.
% In order to get the
% histogramme of the line lengths, simply call
% HIST(B(1,:),[1 MAX(B(1,:))]).
%
% Examples: X = crp(rand(200,1),1,1,.3,'fan','silent');
% [l l_dist] = dl_e(X);
% hist(l_dist(1,:),200)
%
% See also CRQA, TT, DL.
% Copyright (c) 2019-
% Norbert Marwan, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% K.Hauke Kraemer, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% Institute of Geosciences, University of Potsdam,
% Germany
% http://www.geo.uni-potsdam.de
%
% $Date: 2018/09/19 $
% $Revision: $
%
% $Log: dl.m,v $
%
%
% 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 2
% of the License, or any later version.
[Y,~] = size(X);
lines(:,1) = getLinesOnDiag(X,-Y+1); % init with first (scalar) diagonal
for j=-Y+2:Y-1
lines = horzcat(lines,getLinesOnDiag(X,j));
end
% remove lines of length zero (=no line)
zero_lines = lines(1,:)==0;
lines(:,zero_lines) = [];
b_out= sortrows(lines','descend')';
a_out = mean(b_out(1,:));
end
function lines = getLinesOnDiag(M,j)
% getLinesOnDiag computes lines on a diagonal 'j' of a matrix 'M'. The
% output is a 3-by-number_of_lines_in_the_digonal-matrix. In the first line
% the length of the line is stored and in line 2 and 3 the respective line
% and column index of the starting point of that diagonal.
%
% Copyright (c) 2019
% K.Hauke Kraemer, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% Institute of Geosciences, University of Potsdam,
% Germany
% http://www.geo.uni-potsdam.de
% Nikolaus Koopmann
%
% 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 2
% of the License, or any later version.
d = diag(M,j);
if ~any(d)
lines = [0;0;0];
return
end
starts = find(diff([0; d],1)==1);
ends = find(diff([d; 0],1)==-1);
lines = zeros(3,numel(starts));
for n=1:numel(starts)
ll = get_indices(starts(n),j);
for k = 1:length(ll)
lll = ll{k};
lines(2,n) = lll(1);
lines(3,n) = lll(2);
lines(1,n) = ends(n) - starts(n) +1;
end
end
end
function tuples = get_indices(indices,position_from_LOI)
% GET_INDICES gets "true" indices from of the lines represented in the column
% vector 'indices' and its diagonal determined by 'position_from_LOI'.
% "True" indices in this case means the indices in the corresponding RP,
% not the close returns map.
%
% tuples = get_indices(indices,position_from_LOI,sourceRP)
%
% Input:
% 'indices' is a column vector, 'position_from_LOI' a integer
%
% Output: a cell array of tuples conating the true line and column index in
% the sourceRP.
%
% Copyright (c) 2019
% K.Hauke Kraemer, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% Institute of Geosciences, University of Potsdam,
% Germany
% http://www.geo.uni-potsdam.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 2
% of the License, or any later version.
%% check input
narginchk(2,2)
nargoutchk(1,1)
if size(indices,1)<size(indices,2)
indices = indices';
end
if rem(position_from_LOI,1)~=0
error('position_from_LOI needs to be a integer')
end
%%
tuples = cell(1,length(indices));
for i = 1:length(indices)
if position_from_LOI < 0
start_line = indices(i) + abs(position_from_LOI);
start_column = indices(i);
elseif position_from_LOI > 0
start_line = indices(i);
start_column = indices(i) + abs(position_from_LOI);
elseif position_from_LOI == 0
start_line = indices(i);
start_column = indices(i);
end
tuples{i}=[start_line start_column];
end
end
function [a_out, b_out]=dl_h(x)
% DL_H Mean of the horizontal line lengths and their distribution in a
% close returns map, additionally with the corresponding indices of the lines.
% A=DL_H(X) computes the mean of the length of the horizontal
% line structures in a close returns map of a recurrence plot.
%
% [A B]=DL_H(X) computes the mean A and the lengths of the
% found horizontal lines, stored in the first line of B. B is a 3 line
% matrix storing the found horizontal line lengths in its columns. Line 2
% and 3 store the indices i, j of the startpoint of the horizontal line
% stored in the same column in the first line.
% In order to get the
% histogramme of the line lengths, simply call
% HIST(B(1,:),[1 MAX(B(1,:))]).
%
% Examples: X = crp(rand(200,1),1,1,.3,'fan','silent');
% [l l_dist] = dl_h(convertRP(X));
% hist(l_dist(1,:),200)
%
% See also CRQA, TT, DL, convertRP, revertRP
% Copyright (c) 2018-
% K.Hauke Kraemer, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.de
% Institute of Geosciences, University of Potsdam,
% Germany
% http://www.geo.uni-potsdam.de
% Norbert Marwan, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.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 2
% of the License, or any later version.
narginchk(1,1)
nargoutchk(0,2)
[N,~] = size(x);
liness = zeros(3,1);
for j = 1:N
d = x(j,:)';
starts = find(diff([0; d],1)==1);
ends = find(diff([d; 0],1)==-1);
if ~isempty(starts)
lines = zeros(3,numel(starts));
for n=1:numel(starts)
lines(2,n) = j;
lines(3,n) = starts(n);
lines(1,n) = ends(n) - starts(n) +1;
end
else
lines = zeros(3,1);
end
liness = horzcat(liness,lines);
end
% remove lines of length zero (=no line)
zero_lines = liness(1,:)==0;
liness(:,zero_lines) = [];
b_out= sortrows(liness','descend')';
a_out = mean(b_out(1,:));
end
function Y = convertRP(X)
% CONVERTRP Transforms the standard RP to a close returns map
% Y = convertRP(X)
%
% Example:
% x = sin(linspace(0,5*2*pi,200));
% xe = embed(x,2,5);
% r = rp(xe,.2);
% imagesc(r)
% c = convertRP(r);
% imagesc(c)
%% size of RP
N = size(X);
%% initialize new matrix
Y = zeros(2*N(1)+1,N(1));
%% fill rows of Y by the diagonals of X
% upper triangle
for i = 0:N(1)-1
Y(N(1)+i+1,(1:(N(1)-i))) = diag(X,i);
end
% lower triangle
for i = 0:N(1)-1
Y(N(1)-i+1,(1:(N(1)-i))+i) = diag(X,-i);
end
end
function X = revertRP(Y)
% REVERTRP Transforms a close returns map to the standard RP
% X = revertRP(Y)
%
% Example:
% x = sin(linspace(0,5*2*pi,200));
% xe = embed(x,2,5);
% r = rp(xe,.2);
% c = convertRP(r);
% r2 = revertRP(c);
% imagesc(r2)
% imagesc(r-r2) % shows the difference between original and reverted
%% size of close returns map
N = size(Y);
%% initialize new matrix
X = zeros(N(2),N(2));
%% make Y to a square matrix, fill the new part with zeros
Z = [Y zeros(N(1),N(2)+1)];
Z = flipud(Z); % flip upside down
%% fill columns of by the diagonals of Z (but only the first N points)
for i = 1:N(2)
di = diag(Z,-i);
X(:,N(2)-i+1) = di(1:N(2));
end
end
function RP = delete_line_from_RP(RP,l_vec)
% deletes a line, specified in 'l_vec' (line vector, with first line being
% the total line length, the second line the line-index of the starting point
% and the third line the column-index of the starting pint) from the 'RP'.
RP(l_vec(2),l_vec(3)+(1:l_vec(1))-1) = 0;
% X = RP;
end
function [XX,YY]= scan_lines(XX,l_vec,line,column)
% for the input index tuple look for the start indices
index = 0;
while true
% check whether the input index tuple is a listed index for starting
% points of line lengths in the line matrix
loc_line = find(line==l_vec(2,:));
del_ind = loc_line(column+index==l_vec(3,loc_line));
if del_ind
break
else
index = index - 1;
end
end
% delete the line from RP
%XX = delete_line_from_RP(XX,l_vec(:,del_ind));
XX(l_vec(2,del_ind),l_vec(3,del_ind)+(1:l_vec(1,del_ind))-1) = 0;
% bind line length, line & column starting index
len = l_vec(1,del_ind);
li = l_vec(2,del_ind);
co = l_vec(3,del_ind);
% delete the line from the line matix
l_vec(:,del_ind) = [];
[N,M] = size(XX);
%%%%%% check for borders of the RP %%%%%%
if li-1 < 1
flag1 = false;
else
flag1 = true;
end
if li+1 > N
flag2 = false;
else
flag2 = true;
end
for i = 1:len
% check for borders of the RP
if li-1 < 1 || co+i-2 == 0
flag1b = false;
else
flag1b = true;
end
if li-1 < 1 || co+i > M
flag1c = false;
else
flag1c = true;
end
if li+1 > N || co+i-2 == 0
flag2b = false;
else
flag2b = true;
end
if li+1 > N || co+i > M
flag2c = false;
else
flag2c = true;
end
% check above left for a neighbour
if flag1b && XX(li-1,co+i-2)
% call function itself
[XX,l_vec] = scan_lines(XX,l_vec,li-1,co+i-2);
% check above the line for a neighbour
elseif flag1 && XX(li-1,co+i-1)
% call function itself
[XX,l_vec] = scan_lines(XX,l_vec,li-1,co+i-1);
% check above right for a neighbour
elseif flag1c && XX(li-1,co+i)
% call function itself
[XX,l_vec] = scan_lines(XX,l_vec,li-1,co+i);
% check underneeth left for a neighbour
elseif flag2b && XX(li+1,co+i-2)
% call function itself
[XX,l_vec] = scan_lines(XX,l_vec,li+1,co+i-2);
% check underneeth the line for a neighbour
elseif flag2 && XX(li+1,co+i-1)
% call function itself
[XX,l_vec] = scan_lines(XX,l_vec,li+1,co+i-1);
% check underneeth right for a neighbour
elseif flag2c && XX(li+1,co+i)
% call function itself
[XX,l_vec] = scan_lines(XX,l_vec,li+1,co+i);
end
end
YY = l_vec;
end
function y = embed(varargin)
%
% version 1.0
%
%
% Create embedding vector using time delay embedding
% Y=EMBED(X,M,T) create the embedding vector Y from the time
% series X using a time delay embedding with dimension M and
% delay T. The resulting embedding vector has length N-T*(M-1),
% where N is the length of the original time series.
%
% Example:
% N = 300; % length of time series
% x = .9*sin((1:N)*2*pi/70); % exemplary time series
% y = embed(x,2,17);
% plot(y(:,1),y(:,2))
%
% Copyright (c) 2012
% Norbert Marwan, Potsdam Institute for Climate Impact Research, Germany
% http://www.pik-potsdam.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 2
% of the License, or any later version.
narginchk(1,3)
nargoutchk(0,1)
try
t = varargin{3};
catch
t = 1;
end
try
m = varargin{2};
catch
m = 1;
end
x = varargin{1}(:);
% length of time series
Nx = length(x);
NX = Nx-t*(m-1);
if t*(m-1) > Nx
warning('embedding timespan exceeding length of time series')
end
%% create embeeding vector using Matlab's vectorization
% index series considering the time delay and dimension
for mi = 1:m
jx(1+NX*(mi-1):NX+NX*(mi-1)) = 1+t*(mi-1):NX+t*(mi-1);
end
% the final embedding vector
y = reshape(x(jx),NX,m);
end