-
Notifications
You must be signed in to change notification settings - Fork 5
/
num.m
1036 lines (1033 loc) · 36.7 KB
/
num.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
classdef num
methods(Static)
%% utils
%checks for scalar numerics
function out=isscalar(in)
out=isnumeric(in) && isscalar(in);
end
% converts cell array to numeric array if all entries are numeric
function inout=cell(inout)
if iscell(inout) && all(cellfun(@isnumeric,inout))
inout=cell2mat(inout);
end
end
function out=odd(in)
if ~isscalar(in)
out=arrayfun(@num.odd,in);
return
end
if mod(in,2)==0
out=in-sign(in);
else
out=in;
end
end
function out=even(in)
if ~isscalar(in)
out=arrayfun(@num.even,in);
return
end
if mod(in,2)==0
out=in;
else
out=in-sign(in);
end
end
% shortcut for [s.field(:,column)] or [s.field(line,:)]
function out=struct_deal(s,field,line,column)
if ~xor(isempty(line),isempty(column))
error('(only) one of ''line'' or ''column'' must be empty.')
end
if isempty(line)
out=zeros(size(s(1).(field),1),numel(s));
for i=1:numel(s)
out(:,i)=s(i).(field)(:,column);
end
else
out=zeros(numel(s),size(s(1).(field),2));
for i=1:numel(s)
out(i,:)=s(i).(field)(line,:);
end
end
end
%removes NaNs from the extremeties of 'in'
function out=trim_NaN(in)
transpose_flag=false;
%need column vector
if isvector(in) && size(in,2)>1; transpose_flag=true; end
%enforce transpose
if transpose_flag; in=transpose(in); end
%init loop
out=true(size(in));
in_isnan=isnan(in);
for j=1:size(in,2)
for i=1:size(in,1)
if ~in_isnan(i,j); break; end
out(i,j)=false;
end
end
for j=size(in,2):-1:1
for i=size(in,1):-1:1
if ~in_isnan(i,j) || ~out(i,j); break; end
out(i,j)=false;
end
end
end
%NOTICE: this may look redundant but Matlab's linspace is not very accurate and introduces small errors
function out=linspace(l,u,n)
out=l:(u-l)/(n-1):u;
assert(num.ishomogeneous(out),...
['num.linspace failed to produce homoegeneous domain, min/max diff is ',num2str(diff(num.minmax(diff(out))))])
end
%NOTICE: unlike matlab's minmax, this returns the min/max of all entries
function out=minmax(in)
out=minmax(transpose(in(:)));
end
function out=ishomogeneous(x,tol)
if ~exist('tol','var') || isempty(tol)
tol=1e-15;
end
out=diff(num.minmax(diff(x)))<tol;
end
function io=makehomogeneous(io)
if ~num.ishomogeneous(io)
io=num.linspace(min(io),max(io),numel(io));
end
end
function out=deltax(x)
x=x(:);
out=interp1(mean([x(1:end-1),x(2:end)],2),diff(x),x,'linear','extrap');
end
function M=diff_coeffs(dt,xpoints,nderiv)
n=length(xpoints);
i=0:n-1;
w=warning('error','MATLAB:nearlySingularMatrix'); %#ok<NASGU,CTPCT>
try
M=inv((xpoints(:)*ones(1,n)).^(ones(n,1)*i).*(dt*ones(n)).^(ones(n,1)*i)).*(factorial(0:n-1)'*ones(1,n));
catch ME
switch ME.identifier
case 'MATLAB:nearlySingularMatrix'
%reduce number of points
if abs(xpoints(1))>=abs(xpoints(end))
xpoints_new=xpoints(2:end);
else
xpoints_new=xpoints(1:end-1);
end
assert(numel(xpoints_new)>nderiv,'When trying to fix nearly singular matrix issue, ended up removing too many xpoints')
% warning(['Using xpoints = [',strjoin(cellfun(@num2str,cells.m2c(xpoints),'Uniform',false),' '),'] for the ',...
% str.th(nderiv),' derivative leads to nearly singular matrix; trying the following xpoints = [',...
% strjoin(cellfun(@num2str,cells.m2c(xpoints_new),'Uniform',false),' '),']'])
M=num.diff_coeffs(dt,xpoints_new,nderiv);
otherwise
error(['Cannot handle error ', ME.identifier,'; DEBUG NEEDED!'])
end
return
end
%negative sign needed here.
M=M(nderiv+1,:)*(-1)^nderiv;
end
%applies convolution for each rows of 'in'
function out=conv(in,coeffs)
out=zeros(size(in));
for i=1:size(in,1)
out(i,:)=conv(in(i,:),coeffs,'same');
end
end
%computes the derivative with order 'nderiv' of each row of 'f'
%assuming homogeneous x-domain step equal to 'dt'
%using a central stencial scheme with npoints*2+1
function [df,out]=diff(f,dt,varargin)
p=machinery.inputParser;
p.addParameter('npoints',3, @(i) isnumeric(i) && isscalar(i));
p.addParameter('nderiv', 1, @(i) isnumeric(i));
% NOTICE: extremeties can be:
% crop
% nan
% fix
% '' (default)
p.addParameter('extremeties','nan', @(i) ischar(i));
p.addParameter('verbose',false, @(i) islogical(i));
% NOTICE: noplot is only relevant for tests
p.addParameter('noplot',false, @(i) islogical(i));
% parse it
p.parse(varargin{:});
%easier names
np=p.Results.npoints;
nd=p.Results.nderiv;
%special calls
if ischar(f)
switch lower(f)
case 'dt'; df=0.1;
case 'npoints'; df=3;
case 'nderiv'; df=1;
case {'sin','p'}
%need dt,npoints,nderiv
if ~exist('dt','var') || isempty(dt)
out.dt=num.diff('dt');
else
out.dt=dt;
end
if nd<=0
out.nderiv=num.diff('nderiv');
else
out.nderiv=nd;
end
if np<=0
out.npoints=num.diff('npoints');
else
out.npoints=np;
end
switch lower(f)
case 'sin'
out.t=0:out.dt:out.dt*100*pi/2/out.dt;
out.f=sin(out.dt*out.t);
syms dts ts
out.fa=sin(dts*ts);
out.dfa=double(subs(diff(out.fa,out.nderiv),{'dts','ts'},{out.dt,out.t}));
out.dfn1=num.diff(out.f,out.dt,varargin{:},'extremities','nan');
case 'cos'
out.t=0:out.dt:out.dt*100*pi/2/out.dt;
out.f=cos(out.dt*out.t);
syms dts ts
out.fa=cos(dts*ts);
out.dfa=double(subs(diff(out.fa,out.nderiv),{'dts','ts'},{out.dt,out.t}));
out.dfn1=num.diff(out.f,out.dt,varargin{:},'extremities','nan');
case 'p'
out.degree=2;
%NOTICE: as of now, crossing 45 latitude creates problems
out.t=sin(linspace(-pi*0.5,pi*0.5,round(2*pi/out.dt)));
%TODO: dig up Ppq
out.f=Ppq(out.t,out.degree,0);
out.fa='legendre';
out.dfa=gradient(out.f,1)./(ones(size(out.f,1),1)*transpose(num.deltax(out.t)));
out.dfn1=Ppq(out.t,out.degree,1);out.dfn1=out.dfn1{2};
end
%NOTICE: this is the alternative solution with fixing the extremities
% out.dfn1 contains the normal solution of discarding the extremeties
out.dfn2=num.diff(out.f,out.dt,varargin{:},'extremities','fix');
%compute difference wrt analytical solution
delta=out.dfn1-out.dfa;
delta=delta(~isnan(delta));
out.std1=std(delta);
out.max1=max(abs(delta));
delta=out.dfn2-out.dfa;
delta=delta(~isnan(delta));
out.std2=std(delta);
out.max2=max(abs(delta));
%NOTICE: the main output is empty, this test only intends to return 'out'
df=[];
case {'test-sin','test-p'}
if ~exist('dt','var') || isempty(dt)
dt=num.diff('dt');
end
[~,out]=num.diff(strrep(f,'test-',''),dt,varargin{:});
if ~p.Results.noplot
figure
subplot(2,1,1)
plot(out.t,out.dfn1),hold on
plot(out.t,out.dfn2),hold on
plot(out.t,out.dfa,'k')
legend('numeric (edges dropped)','numeric (edges fixed)','analytic')
ylabel(char(out.fa)),xlabel('ts')
title([num2str(out.npoints),'-point stencil central ',num2str(out.nderiv),'-th derivative'])
subplot(2,1,2)
semilogy(abs(out.dfn1-out.dfa)), hold on
semilogy(abs(out.dfn2-out.dfa))
legend('edges dropped','edges fixed')
title(['numeric - analytic, std=',num2str(out.std1),', maxabs=',num2str(out.max1)])
end
df=[];
case {'error-sin','error-p'}
if ~exist('dt','var') || isempty(dt)
dt=num.diff('dt');
end
min_np=max(1,np);
max_np=max([np,num.diff('npoints')])*3;
np=min_np:2:max_np;
stds1=zeros(size(np));
maxs1=zeros(size(np));
stds2=zeros(size(np));
maxs2=zeros(size(np));
for i=1:length(np)
[~,out]=num.diff(strrep(f,'error','test'),dt,'npoints',np(i),'nderiv',nd,'noplot',true,varargin{:});
%case when the edges are dropped
stds1(i)=out.std1/diff(minmax(out.dfa))*100;
maxs1(i)=out.max1/diff(minmax(out.dfa))*100;
%case when the edges are fixed
stds2(i)=out.std2/diff(minmax(out.dfa))*100;
maxs2(i)=out.max2/diff(minmax(out.dfa))*100;
end
plotting.figure;
subplot(2,2,1)
semilogy(np,stds1)
xlabel('n')
ylabel('std(error) [% of minmax(df)]')
plotting.enforce('plot_title',[num2str(nd),'-th order diff, edges dropped'],'plot_legend_location','none');
subplot(2,2,2)
semilogy(np,maxs1)
xlabel('npoints')
ylabel('max(error) [% of minmax(df)]')
plotting.enforce('plot_title',[num2str(nd),'-th order diff, edges dropped'],'plot_legend_location','none');
subplot(2,2,3)
semilogy(np,stds2)
title('edges fixed')
xlabel('npoints')
ylabel('std(error) [% of minmax(df)]')
plotting.enforce('plot_title','edges fixed','plot_legend_location','none');
subplot(2,2,4)
semilogy(np,maxs2)
xlabel('npoints')
ylabel('max(error) [% of minmax(df)]')
plotting.enforce('plot_title','edges fixed','plot_legend_location','none');
end
return
end
%handle shortcuts calls
if np==0
df=f;
for i=1:nd
df=gradient(df,dt);
end
return
end
%some sanity
if isscalar(np)
dp=transpose(-np:np);
else
assert(isvector(np),'input <npoints>, if not scalar, must be a 1D vector.')
dp=np(:);
end
assert(nd <= np,['cannot calculate the ',...
num2str(nd),'-th derivative with only ',...
num2str(np),' points.'])
nf=size(f,2);
assert(nf>=np,['cannot use ',num2str(np),...
' points stencil with data with only ',num2str(nf),' points'])
%compute derivative
df=num.conv(f,num.diff_coeffs(dt,dp,nd));
%find edges
idx=[floor(np),ceil(np)];
if cells.isincluded(varargin,'verbose')
tab=16;
disp(['start=',num2str(idx(1)),' end=',num2str(idx(2)),...
' npoints=',num2str(dp(1)),':',num2str(dp(end))])
for i=1:size(df,1)
disp([' df(',num2str(i),',[1:',num2str(idx(1)),',',num2str(nf-idx(2)+1),...
':',num2str(nf),'])=',str.tablify(tab,df(i,[1:idx(1),end-idx(2)+1:end]))])
end
end
%fixing warm-up/cool-down points, if requested
switch p.Results.extremeties
case 'crop'
%crop it
df(:,[1:idx(1),end-idx(2)+1:end])=[];
case 'nan'
%nan it
df(:,[1:idx(1),end-idx(2)+1:end])=NaN;
case 'fix'
for i=0:np-1
if cells.isincluded(varargin,'verbose')
disp(['--- idx=',num2str(i+1)])
disp(['dp=',num2str(-i),':',num2str(2*np-i)])
disp(str.tablify(tab,['old df(:,',num2str(i+1),')'],transpose(df(:,i+1))))
end
tmp=num.conv(f(:,1:2*np+1),...
num.diff_coeffs(dt,-i:2*np-i,nd));
df(:,i+1)=tmp(:,np+1);
if cells.isincluded(varargin,'verbose')
disp(str.tablify(tab,['fixed df(:,',num2str(i+1),')'],transpose(df(:,i+1))))
disp(['dp=',num2str(-2*np+i),':',num2str(i)])
disp(str.tablify(tab,['old df(:,',num2str(nf-i),')'],transpose(df(:,end-i))))
end
tmp=num.conv(f(:,end-2*np:end),num.diff_coeffs(dt,-2*np+i:i,nd));
df(:,end-i)=tmp(:,np+1);
if cells.isincluded(varargin,'verbose')
disp(str.tablify(tab,['fixed df(:,',num2str(nf-i),')'],transpose(df(:,end-i))))
end
end
end
end
function out=zeros(in)
%also handes symbolic zeros
switch class(in)
case 'sym'; out=sym(zeros(size(in)));
otherwise; out= zeros(size(in));
end
end
function out=triu(in)
switch ndims(in)
case 1
%this shouldn't happen, because matlab:
%ndims([])=2
%ndims(0)=2
%ndims(ones(1,1))=2
%ndims(ones(1,2))=2
%ndims(ones(2,1))=2
%ndims(ones(1,1,1))=2
%ndims(ones(1,1,2))=3
case 2
if isvector(in)
out=in;
else
out=triu(in);
end
case 3
out=num.zeros(in);
nk=size(in,3);
for k=1:nk
out(k:end,k:end,k)=num.triu(in(k:end,k:end,k));
end
otherwise
error(['Cannot handle matrices with ',num2str(ndims(in)),' dimensions: implementation needed'])
end
end
function out=symmetricidx(in)
switch ndims(in)
case 2
if isvector(in)
%trivial call, no symmetry
out=reshape(1:numel(in),size(in));
return
else
n1=size(in,1);
n2=size(in,2);
ci=cell(n1,n2);
s1=str.characters(1:n1);
s2=str.characters(1:n2);
for i=1:n1
for j=1:n2
ci{i,j}=[s1(i),s2(j)];
end
end
end
case 3
n1=size(in,1);
n2=size(in,2);
n3=size(in,3);
ci=cell(n1,n2,3);
s1=str.characters(1:n1);
s2=str.characters(1:n2);
s3=str.characters(1:n3);
for i=1:n1
for j=1:n2
for k=1:n3
ci{i,j,k}=[s1(i),s2(j),s3(k)];
end
end
end
end
out=num.zeros(ci);
ci=cellfun(@sort,ci,'UniformOutput',false);
done=false(size(ci));
for i=1:numel(ci)
if done(i), continue, end
same_idx=strfind(ci,ci{i});
same_idx=cellfun(@(i) ~isempty(i),same_idx);
out(same_idx)=i;
done(same_idx)=true;
end
end
function out=makesymmetric(in)
idx=num.symmetricidx(in);
out=num.zeros(in);
for i=1:numel(in)
out(i)=in(idx(i));
end
end
function out=issymmetric(in)
idx=num.symmetricidx(in);
idx_flat=unique(idx(:));
for i=1:numel(idx_flat)
f=(idx==idx_flat(i));
if sum(f)==1, continue, end
fv=in(f);
if ~all(fv==fv(1))
out=false;
return
end
end
out=true;
end
%% pardecomp stuff (deprecated)
function plot_pardecomp(pd_struct)
s=200+[0,0,21,9]*50;
lf={'-','--',':','-.'};
figure('Position',s,'PaperPosition',s)
legend_str=cell(1,numel(pd_struct.polynomial)+numel(pd_struct.sinusoidal)+numel(pd_struct.cosinusoidal)+2);
c=0;
plot(pd_struct.in.t,pd_struct.in.y,'b','LineWidth',2), hold on
c=c+1;legend_str{c}='original';
plot(pd_struct.in.t,pd_struct.y_res,'k','LineWidth',2)
c=c+1;legend_str{c}='residual';
for i=1:numel(pd_struct.polynomial)
plot(pd_struct.in.t,pd_struct.y_polynomial(:,i),['r',lf{mod(i-1,numel(lf))+1}],'LineWidth',2)
c=c+1;legend_str{c}=['t^',num2str(i-1),':',num2str(pd_struct.polynomial(i))];
end
for i=1:numel(pd_struct.sinusoidal)
plot(pd_struct.in.t,pd_struct.y_sinusoidal(:,i),['g',lf{mod(i-1,numel(lf))+1}],'LineWidth',2)
c=c+1;legend_str{c}=['sin_',num2str(i),':',num2str(pd_struct.sinusoidal(i))];
end
for i=1:numel(pd_struct.cosinusoidal)
plot(pd_struct.in.t,pd_struct.y_cosinusoidal(:,i),['m',lf{mod(i-1,numel(lf))+1}],'LineWidth',2)
c=c+1;legend_str{c}=['cos_',num2str(i),':',num2str(pd_struct.cosinusoidal(i))];
end
legend(legend_str,'location','eastoutside')
title(['norm(x+res-y)=',num2str(norm(sum([pd_struct.y_polynomial,pd_struct.y_sinusoidal,pd_struct.y_cosinusoidal,pd_struct.y_res,-pd_struct.in.y],2))),...
newline,'T=',num2str(pd_struct.in.T(:)')])
fs=16;
set( gca, 'FontSize',fs);
set(get(gca,'Title' ),'FontSize',round(fs*1.3));
set(get(gca,'XLabel'),'FontSize',round(fs*1.1));
set(get(gca,'YLabel'),'FontSize',round(fs*1.2));
grid on
end
function pd_struct=save_pardecomp(t,T,x,y,y_mod,y_res,np,ns)
pd_struct=struct(...
'in',struct(... %this is just record keeping
't',t,...
'y',y,...
'T',T...
),...
'polynomial',x(1:np),... %constant, liner, quadratic, etc (reverse order than the poly* functions of matlab)
'sinusoidal',x(np+1:np+ns),... %in the same order as the periods defined in the 'sinusoidal' argument
'cosinusoidal',x(np+ns+1:end),... %in the same order as the periods defined in the 'sinusoidal' argument
'y_polynomial',y_mod(:,1:np),...
'y_sinusoidal',y_mod(:,np+1:np+ns),...
'y_cosinusoidal',y_mod(:,np+ns+1:end),...
'y_res',y_res,...
'rnorm',norm(y_res)./norm(y),...
'norm',norm(y_res)...
);
end
function out=pardecomp(t,y,varargin)
%NOTICE: the timescale of t must be defined externally, it is implicit here
if nargin==0
num.pardecomp([0;1],[-1;-1],'mode','test');
return
end
% add input arguments and plot metadata to collection of parameters 'v'
v=varargs.wrap('sources',{....
{...
't', [], @(i) (isnumeric(i) && isvector(i) && all(size(i)==size(t)) && ~any(isnan(i))) || isempty(i) ;...
'y', [], @(i) (isnumeric(i) && isvector(i) && all(size(i)==size(t)) && ~any(isnan(i))) || isempty(i) ;...
'polynomial', 2, @(i) (num.isscalar(i)) || isempty(i);...
'sinusoidal',[2*min(diff(t)),(t(end)-t(1))/2], @(i) isnumeric(i) || isempty(i);...
't0', [], @num.isscalar;...
'mode', 'pd_struct', @ischar;...
'x', [], @(i) isnumeric(i) || isempty(i);...
'pd_struct', [], @(i) isstruct(i) || isempty(i);...
},...
},varargin{:});
%patch derived parameters
if ~isempty(v.t) && isempty(v.t0)
v.t0=t(1);
end
if ~isempty(v.pd_struct)
if isempty(v.t); v.t=v.pd_struct.in.t; end
if isempty(v.y); v.y=v.pd_struct.in.y; end
if isempty(v.T); v.sinusoidal=v.pd_struct.in.T; end
% continuar aqui
end
p=machinery.inputParser;
p.addRequired( 't', @(i) isnumeric(i) && isvector(i) && size(i,2)==1 && ~any(isnan(i)) );
p.addRequired( 'y', @(i) (isnumeric(i) && isvector(i) && all(size(i)==size(t)) && ~any(isnan(i))) || isempty(i) );
%number of polynomial coefficients (not order): 1 constant, 2 constant+linear, 3 constant+linear+quadratic, etc
p.addParameter('polynomial',2, @(i) (num.isscalar(i)) || isempty(i));
%sinusoidal periods (in implicit units):
p.addParameter('sinusoidal',[2*min(diff(t)),(t(end)-t(1))/2], @(i) isnumeric(i) || isempty(i));
p.addParameter('t0', t(1), @num.isscalar);
p.addParameter('mode', 'pd_struct', @ischar);
%these parameters are only valid for the "model" mode.
p.addParameter('x', [], @(i) isnumeric(i) || isempty(i));
p.addParameter('pd_struct', [], @(i) isstruct(i) || isempty(i));
% parse it
p.parse(t,y,varargin{:});
%some sanity
if isempty(y)
assert(strcmp(p.Results.mode,'model'),'if input ''y'' is empty, then mode must be ''model''')
y=ones(size(t));
end
%simpler names
np=p.Results.polynomial;
ns=numel(p.Results.sinusoidal);
ny=numel(y);
%start from t0
t=t-p.Results.t0;
% trivial call
if ~any(y~=0)
%assign outputs
out=num.save_pardecomp(t,p.Results.sinusoidal,...
zeros(np+2*ns,1),... x
y,... y
zeros(ny,np+2*ns),... y_mod
zeros(ny,np+2*ns),... y_res
np,ns...
);
%we're done
return
end
% branch on mode
switch p.Results.mode
case 'test'
%test parameters
step=1;
n=10000;
poly_coeffs=[1 3 5]./[1 n n^2];
sin_periods=n/step./[2 5];
sin_periods_assumed=sin_periods+randn(size(sin_periods))*n/1e2;
sin_coeffs=[0.5 3];
cos_coeffs=[2 0.8];
randn_scale=0.5;
%inform
disp(['sin_periods : ',num2str(sin_periods(:)')])
disp(['poly_coeffs : ',num2str(poly_coeffs(:)')])
disp(['sin_coeffs : ',num2str(sin_coeffs(:)')])
disp(['cos_coeffs : ',num2str(cos_coeffs(:)')])
disp(['randn_scale : ',num2str(randn_scale(:)')])
%derived parameters
t=transpose(1:step:(n*step));
y=num.pardecomp(t,[],'mode','model',...
'polynomial',numel(poly_coeffs),...
'sinusoidal',sin_periods,...
'x',[poly_coeffs,sin_coeffs,cos_coeffs]...
);
%sum all components
y=sum(y,2);
%add noise
y=y+randn_scale*randn(size(y));
%decompose
pd_struct=num.pardecomp(t,y,'mode','pd_struct',...
'polynomial',numel(poly_coeffs),...
'sinusoidal',sin_periods_assumed...
);
%show results
num.plot_pardecomp(pd_struct);
% returns the design matrix
case 'design'
%get the period(s)
if ~isempty(p.Results.pd_struct)
%TODO
end
T=p.Results.sinusoidal;
% init design matrix
A=zeros(ny,np+2*ns);
% build design matrix: polynomial coefficients
for i=1:np
A(:,i)=t.^(i-1);
end
% build design matrix: sinusoidal coefficients
for i=np+(1:ns)
A(:,i)=sin(2*pi/T(i-np)*t);
end
% build design matrix: co-sinusoidal coefficients
for i=np+ns+(1:ns)
A(:,i)=cos(2*pi/T(i-np-ns)*t);
end
%outputs
out=A;
% returns the y vector
case 'model'
%sanity
assert(~isempty(p.Results.x),'need input argument ''x''.')
%get the design matrix
A=num.pardecomp(t,y,varargin{:},'mode','design');
%get modelled components
x=p.Results.x;
y_mod=zeros(numel(y),numel(x));
for j=1:numel(x)
y_mod(:,j)=A(:,j)*x(j);
end
%outputs
out=y_mod;
% returns struct with x coefficients and some more stuff
case 'pd_struct'
%get the design matrix
A=num.pardecomp(t,y,varargin{:},'mode','design');
%solve the system of linear equations
x=A\y;
%get modelled components
y_mod=num.pardecomp(t,y,varargin{:},'mode','model','x',x);
%get residuals
y_res=y-sum(y_mod,2);
%assign outputs
out=num.save_pardecomp(t,p.Results.sinusoidal,x,y,y_mod,y_res,np,ns);
otherwise
error(['unknown output mode ''',p.Results.mode,'''.'])
end
end
function x_opt=param_search1(fun,x,varargin)
% input parsing
p=machinery.inputParser;
p.addRequired( 'fun', @(i) isa(i,'function_handle'));
p.addRequired( 'xrange', @isnumeric);
p.addParameter('searchspace', 'linear', @ischar);
p.addParameter('searchlen',numel(x)*10, @isnumeric);
p.addParameter('interpmethod','spline', @ischar);
p.addParameter('plot', false, @islogical);
p.addParameter('enforce_scalar', false, @islogical);
p.addParameter('vectorize', false, @islogical);
p.parse(fun,x,varargin{:})
%define search space
switch p.Results.searchspace
case {'linear'}
xd=linspace(x(1),x(end),p.Results.searchlen);
case {'log'}
xd=logspace(log10(x(1)),log10(x(end)),p.Results.searchlen);
otherwise
error(['Cannot handle argument ''searchspace'' with value ''',p.Results.searchspace,'''.'])
end
%use vectorize if allowed
if p.Results.vectorize
y=fun(x);
else
%init records
y=nan(size(x));
%loop over xrange
for i=1:numel(x)
y(i)=fun(x(i));
end
end
%interpolate
yd=interp1(x,y,xd,p.Results.interpmethod);
%pick the minimum
yi=yd==min(yd);
x_opt=xd(yi);
%warn user if minimum is at one extremety
if yi(1) || yi(end)
warning(['Could not find minimum of function ''',func2str(fun),''' in [',num2str(x(1)),',',num2str(x(end)),']'])
end
if p.Results.enforce_scalar
x_opt=x_opt(1);
end
%debug plot
if p.Results.plot
figure
plot(x_opt,yd(yi),'*','Markersize',10), hold on
plot(x,y,'o')
plot(xd,yd,'-')
set(gca,'XScale',p.Results.searchspace)
legend({'minimum','tries','interpolated'})
end
end
function [x_opt,y,x]=param_brute(fun,x_lower,x_upper,varargin)
% input parsing
p=machinery.inputParser;
p.addRequired( 'fun', @(i) isa(i,'function_handle'));
p.addRequired( 'x_upper', @isnumeric);
p.addRequired( 'x_lower', @isnumeric);
p.addParameter('searchspace', 'linear', @ischar);
p.addParameter('searchlen', 100, @isnumeric);
p.addParameter('searchlenmaxfactor',2e10,@isnumeric);
p.addParameter('searchiter', 0, @isnumeric);
p.addParameter('searchiter_counter', 0, @isnumeric);
p.addParameter('searchpdf', 'rand', @ischar);
p.addParameter('searchshrinkfactor', 2, @isnumeric);
p.addParameter('vectorize', false, @islogical);
p.parse(fun,x_upper,x_lower,varargin{:})
%sanity
assert(numel(x_upper)==numel(x_lower),...
'Arguments ''x0'', ''x_upper'' and ''x_lower'' must have the same number of elements')
%simpler names
l=p.Results.searchlen;
n=numel(x_upper);
searchpdf=str2func(p.Results.searchpdf);
%define search space
switch p.Results.searchspace
case {'linear'}
d0=x_lower;
dx=x_upper-d0;
x=searchpdf(l,n).*(ones(l,1)*dx)+ones(l,1)*d0;
case {'log'}
d0=log10(x_lower);
dx=log10(x_upper)-d0;
x=10.^(searchpdf(l,n).*(ones(l,1)*dx)+ones(l,1)*d0);
otherwise
error(['Cannot handle argument ''searchspace'' with value ''',p.Results.searchspace,'''.'])
end
%limit the search length: get an estimate of the memory used by fun
fun_info=functions(fun);
fun_mem=sum(structfun(@(i) numel(i),fun_info.workspace{1}));
if l*fun_mem^2>p.Results.searchlenmaxfactor
l_old=l;
l=floor(p.Results.searchlenmaxfactor/fun_mem^2);
str.say('say_stack_delta',1,['searchlen reset to ',num2str(l),...
' because searchlen*fun_mem>searchlenmaxfactor (',...
num2str(l_old),'*',num2str(fun_mem),'>',num2str(p.Results.searchlenmaxfactor),')'])
end
%use vectorize if allowed
if p.Results.vectorize
y=fun(x);
else
%init records
y=nan(size(x,1),1);
%loop over xrange
for i=1:size(x,1)
y(i)=fun(x(i,:));
end
end
assert(~any(isnan(y)),'Found NaNs in the output of fun')
%retrieve lowest value from all y and get corresponding x
x_opt=x(find(min(y)==y,1,'first'),:);
%iterate if requested
if p.Results.searchiter>0
sd=1+p.Results.searchiter_counter;
str.say('say_stack_delta',sd,str.tablify(16,'----- iter ----- ',p.Results.searchiter_counter+1))
str.say('say_stack_delta',sd,str.tablify(16,'res',min(y)))
str.say('say_stack_delta',sd,str.tablify(16,'res',min(y)))
str.say('say_stack_delta',sd,str.tablify(16,'x_lower',x_lower))
str.say('say_stack_delta',sd,str.tablify(16,'x_opt',x_opt))
str.say('say_stack_delta',sd,str.tablify(16,'x_upper',x_upper))
if p.Results.searchiter_counter<=p.Results.searchiter
%define next iter search space amplitude
dx=dx/p.Results.searchshrinkfactor;
%define next iter search space
switch p.Results.searchspace
case {'linear'}
x_lower=x_opt-dx/2;
x_upper=x_opt+dx/2;
case {'log'}
x_lower=x_opt./10.^(dx/2);
x_upper=x_opt.*10.^(dx/2);
otherwise
error(['Cannot handle argument ''searchspace'' with value ''',p.Results.searchspace,'''.'])
end
%iteration number
iter=p.Results.searchiter_counter+1;
%recursive call
[~,y_iter,x_iter]=num.param_brute(fun,...
x_lower,...
x_upper,...
varargin{:},...
'searchlen',l,...
'searchiter_counter',iter ...
);
%append to existing set of y,x
y=[y(:);y_iter(:)];x=[x;x_iter];
%update lowest value from all y and get corresponding x (may be the same)
x_opt=x(find(min(y)==y,1,'first'),:);
end
end
end
%% memory utils (everything is in Mb)
function out=memory_system
if ismac
com='sysctl hw.memsize';
[status, cmdout]=system(com);
if status; error(['could not issue the command ''',com,'''; debug needed.']);end
cmdout=cells.rm_empty(strsplit(cmdout));
out=str2double(cmdout{2})/1024^2;
elseif isunis
error('implementation needed')
elseif ispc
error('implementation needed')
else
error('cannot determine the operating system type')
end
if isnan(out);keyboard;end
end
function out=memory_matlab_fraction
if ismac
com='ps -c -o ''pmem comm'' | grep maci64';
[status, cmdout]=system(com);
if status; error(['could not issue the command ''',com,'''; debug needed.']);end
cmdout=cells.rm_empty(strsplit(cmdout));
out=str2double(cmdout{1})/100;
elseif isunis
error('implementation needed')
elseif ispc
error('implementation needed')
else
error('cannot determine the operating system type')
end
if isnan(out);keyboard;end
end
%% statistics
function out = rms(x,w,dim)
if ~exist('dim','var') || isempty(dim)
dim=0;
else
assert(dim <= numel(size(w)),'the value of input <dim> must not be larger than the number of dimensions in <x>')
end
if ~exist('w','var') || isempty(w)
w=ones(size(x));
else
assert(all(size(w) == size(x)),'inputs <x> and <w> must have the same size')
end
switch dim
case 0
%filtering NaNs
i = ~isnan(x) & ~isnan(w);
%compute
out= sqrt(sum(w(i).*(x(i).^2))/sum(w(i)));
case 1 %computes the RMS along columns, so a row is returned
out=arrayfun(@(i) num.rms(x(:,i),w(:,i),0),1:size(x,2));
case 2 %computes the RMS along rows, so a column is returned
out=transpose(arrayfun(@(i) num.rms(x(i,:),w(i,:),0),1:size(x,1)));
otherwise
error(['dim=',num2str(dim),' not implemented.'])
end
end
function out = mean(x,w,dim)
if ~exist('dim','var') || isempty(dim)
dim=0;
else
assert(dim <= numel(size(w)),'the value of input <dim> must not be larger than the number of dimensions in <x>')
end
if ~exist('w','var') || isempty(w)
w=ones(size(x));
else
assert(all(size(w) == size(x)),'inputs <x> and <w> must have the same size')
end
switch dim
case 0
%filtering NaNs
i = ~isnan(x) & ~isnan(w);
%compute
out= sum(w(i).*(x(i)))/sum(w(i));
case 1 %computes the RMS along columns, so a row is returned
out=arrayfun(@(i) num.mean(x(:,i),w(:,i),0),1:size(x,2));
case 2 %computes the RMS along rows, so a column is returned
out=transpose(arrayfun(@(i) num.mean(x(i,:),w(i,:),0),1:size(x,1)));
otherwise
error(['dim=',num2str(dim),' not implemented.'])
end
end
function out = std(x,w,dim)
out=sqrt(num.rms(x,w,dim).^2-num.mean(x,w,dim).^2);
end
function out=cov(x,y)
n=size(x,2);
if n==0
out=0;
return
end
if any(size(x)~=size(y))
out=NaN;
return
end
out=size(1,n);
for i=1:n
out(i)=sum(...
(x(:,i)-mean(x(:,i))).*...
(y(:,i)-mean(y(:,i)))...
)/size(x,1);
end
end
function out=corrcoef(x,y)
n=min([size(x,2),size(y,2)]);
if n==0
out=0;
return
end
out=size(1,n);
for i=1:n
if any([std(x(:,i)),std(y(:,i))]==0)
out(i)=0;
else
out(i)=num.cov(x(:,i),y(:,i))./std(x(:,i),1)./std(y(:,i),1);
end
end
end
%% symbolic stuff
function [common,map,pow]=factorize(expr)
%NOTE: expr = (map*comm).^pow
%gather factors
fact=cell(size(expr));
for i=1:numel(expr)
fact{i}=factor(expr(i));
end
%get common factors
common=unique([fact{:}]);
%get power
pow=zeros(numel(expr),numel(common));
for i=1:numel(expr)
for j=1:numel(common)
for l=1:numel(fact{i})
if isequal(fact{i}(l),common(j))
pow(i,j)=pow(i,j)+1;
end
end
end
end
%get mapping of common factors
map=(pow~=0);
end
%NOTE: exact inverse operation to factorize
function expr=defactorize(common,map,pow)
expr=(map*common).^pow;
end
function out=matvecmul(expr,var)
%NOTE: expr=out*var (matrix multiplication)
out=sym(zeros(size(expr)));
%loop through the expressions
for i=1:numel(expr)
for j=1:numel(var)
out(i,j)=diff(expr(i),var(j));
end
end
end
% Christoffel Symbol of the Second Kind: Lambda^m_{i,j}
% http://mathworld.wolfram.com/ChristoffelSymboloftheSecondKind.html
function out=cs2k(g,u,m,invg)
n=numel(u);
%this is only used internally to avoid re-computing the inverse when the full tensor is requested
if ~exist('invg','var') || isempty(invg)
invg=inv(g);
end
if ~exist('m','var') || isempty(m)
%full tensor requested, loop over m
out=sym(zeros(n,n,n));
for m=1:n
out(:,:,m)=num.cs2k(g,u,m,invg);
end
else
out=sym(zeros(n));
for i=1:n
for j=1:n
for k=1:n
out(i,j)=out(i,j)+invg(k,m)*(diff(g(i,k),u(j))+diff(g(j,k),u(i))-diff(g(i,j),u(k)));
end
end
end
out=simplify(0.5*out);
end
end
function out=latex_def(name,value,repstr,transpose_flag)
%NOTE: defined a latex macro called <name> with the latex string of the symbolic expression <value>
%NOTE: <repstr> is the replacement string cell array that defines how matlab's latex command is fine-tuned