-
Notifications
You must be signed in to change notification settings - Fork 141
/
roots.m
1361 lines (1190 loc) · 45.1 KB
/
roots.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
function varargout = roots( F, varargin )
%ROOTS Find the common zeros of a CHEBFUN2V object.
% r = ROOTS(F) finds the common zeros of the two bivariate functions F(1) and
% F(2) in their domain of definition under the assumption that the solution
% set is zero-dimensional. R is a matrix with two columns storing the x- and
% y-values of the solutions. This script is also called by the syntax
% ROOTS(f,g), where f and g are CHEBFUN2 objects.
%
% [x, y] = ROOTS(F) returns the x- and y-values as two separate columns.
%
% Currently, if the maximum degree of F(1) and F(2) is greater than 200 then
% an algorithm based on Marching squares is employed, and an algorithm based
% on a resultant method is used otherwise (see [1]).
%
% ROOTS(F, 'ms') or ROOTS(F, 'marchingsquares') always employs the marching
% squares algorithm.
%
% ROOTS(F, 'resultant') always employs the algorithm based on the hidden
% variable resultant method.
%
% [1] Y. Nakatsukasa, V. Noferini, and A. Townsend, Computing the common zeros
% of two bivariate functions via Bezout resultants, (2013).
%
% See also CHEBFUN2/ROOTS, CHEBFUN/ROOTS.
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
% Maximum degree for resultant method:
max_degree = 200;
% Empty check:
if ( isempty(F) )
varargout = {[]};
return
end
f = F.components{1};
g = F.components{2};
[nf, mf] = length(f);
[ng, mg] = length(g);
% Maximum degree:
dd = max([mf, nf, mg, ng]);
validArgs = {'ms', 'marchingsquares', 'resultant'};
if ( (nargin > 1) && ~any(strcmpi(varargin{1}, validArgs)) )
error('CHEBFUN:CHEBFUN2V:roots:badInput', ...
'Unrecognised optional argument.');
end
if ( isempty(varargin) )
% If rootfinding method has not been defined, then use resultant if
% degrees are small:
if ( dd <= max_degree )
[xroots, yroots] = roots_resultant(F);
else
[xroots, yroots] = roots_marchingSquares(F);
xroots = xroots.';
yroots = yroots.';
end
elseif ( strcmpi(varargin{1}, 'resultant') )
% If the user wants the resultant method, then use it:
[xroots, yroots] = roots_resultant(F);
elseif ( any( strcmpi(varargin{1}, {'ms', 'marchingsquares'} ) ) )
% If the user wants the marching squares method, then use it:
[xroots, yroots] = roots_marchingSquares(F);
xroots = xroots.';
yroots = yroots.';
else
% Print error. Unknown method.
error('CHEBFUN2V:ROOTS:METHOD', 'Unknown rootfinding method.')
end
if ( nargout <= 1 )
varargout{1} = [xroots ; yroots].';
else
varargout = {xroots, yroots};
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% RESULTANT METHOD %%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [xroots,yroots] = roots_resultant(F)
% extract out the two CHEBFUN2 objects.
f = F.components{1}; g = F.components{2};
% Useful parameters
rect = f.domain; % rectangular domain of CHEBFUN2.
[nf,mf]=length(f);[ng,mg]=length(g);
dd = max([mf nf mg ng]); % max degree
max_degree = min( 16 , dd ); % subdivision threshold degree
reg_tol = 1e-15; % Regularization (for Bezoutian)
domain_overlook = 1e-10; % start by looking for zeros on larger domain.
donewton = 0; % Newton polishing?
multitol = sqrt(eps); % for multiple roots we do not go for more than sqrt(eps);
% Consider a slightly large domain to make sure we get all the roots along
% edges.
% domain width (attempt to make scale invariant)
xwid = diff(rect(1:2))/2; ywid = diff(rect(3:4))/2;
xmax = rect(2) + xwid*domain_overlook;
xmin = rect(1) - xwid*domain_overlook;
ymax = rect(4) + ywid*domain_overlook;
ymin = rect(3) - ywid*domain_overlook;
subdividestop = 2*(1/2)^((log(16)-log(dd))/log(.79)); % subdivision threshold
subdividestop = min(subdividestop,1/4);
% initial scaling to O(1)
f = f/abs(f.pivotValues(1));
g = g/abs(g.pivotValues(1));
[xroots,yroots] = subrootsreptwo(f,g,xmin,xmax,ymin,ymax,xwid,ywid,reg_tol,max_degree,subdividestop);
% ballpark obtained, next do local bezoutian refinement
[fx, fy] = gradient(chebfun2(f,rect));
[gx, gy] = gradient(chebfun2(g,rect));
%%%%% subdivision for accuracy when dynamical range is an issue %%%%%%%%
% find region in which roots might have been missed
F = chebcoeffs2(f);
G = chebcoeffs2(g);
F = rot90(F, -2);
G = rot90(G, -2);
xpts = linspace(xmin,xmax,2*max(size(F,2),size(G,2)));
ypts = linspace(ymin,ymax,2*max(size(F,1),size(G,1)));
[xx,yy] = meshgrid(xpts,ypts);
FX = fx(xx,yy);FY = fy(xx,yy); GY = gy(xx,yy);GX = gx(xx,yy);
FG = abs(FX.*GY-FY.*GX); % Bezout conditioning
FpG = abs(f(xx,yy))+abs(g(xx,yy)); % function values
FGG = (log10(FpG+eps)<-6 & log10(FG/max(max(FG))+eps)<-12); % dangerous region (Bezout might have missed)
if sum(sum(FGG))>0, % Bezout could have missed these, do local search
xx = zeros(1,size(FGG,1)*size(FGG,2)); yy = xx;
ip = 1;
for i=1:size(FGG,1)
for j=1:size(FGG,2)
if FGG(i,j)==1,
s = svd([FX(i,j) FY(i,j);GX(i,j) GY(i,j)]);
Jacobs = 1./s(end); % conditioning of original problem
if ( Jacobs < 1e15 ), % give up if solution is too ill conditioned
xx(ip) = xpts(j); yy(ip) = ypts(i);
ip = ip+1;
end
end
end
end
xdis = (xpts(2)-xpts(1)); ydis = (ypts(2)-ypts(1));
xx = xx(1:ip-1); yy = yy(1:ip-1);
m = blockingxy(xx,yy,max(xdis,ydis)*1.1);
for i = 1:max(m)
xnow = xx(m==i); ynow = yy(m==i);
[xt,yt] = subrootsreptwo(f,g,min(xnow)-xdis,max(xnow)+xdis,min(ynow)-ydis,max(ynow)+ydis,xwid,ywid,reg_tol,max_degree); % local (second) bez
xroots = [xroots xt]; yroots = [yroots yt];
end
end
% xroots,yroots should contain solutions (condnum<1e14) and maybe more.
tolblock = xwid*min(3e-3,1/(10*dd)); % clustering threshold
m = blockingxy(xroots,yroots,tolblock);
z = xroots+1i*yroots;
xroots = [];yroots = [];
tolbdefault = min(5*xwid*sqrt(multitol),tolblock); % local bezout width
for i = 1:max(m)
znow = z(m==i); xnow = real(znow); ynow = imag(znow);
J = [fx(mean(xnow),mean(ynow)) fy(mean(xnow),mean(ynow));gx(mean(xnow),mean(ynow)) gy(mean(xnow),mean(ynow))];
s = svd(J);
Jacobs = 1./s(end); % original conditioning
Jacobsbez = 1/abs(det(J)); % Bezout conditioning
tolb = max(tolbdefault,eps*100*Jacobsbez);
tolb = min(tolb,xwid*1e-2); % give up if Jacobs too large
[xrootsnow,yrootsnow] = subrootsreptwo(f,g,min(xnow)-tolb,max(xnow)+tolb,min(ynow)-tolb,max(ynow)+tolb,xwid,ywid,0,max_degree); % local (second) bez no subdivision
xxx = []; yyy = [];
if length(xrootsnow)>=1,
if Jacobs<1e10, %only for well-conditioned roots
tolbb = max(xwid*multitol,Jacobs*1000*eps);
for j = 1:length(xrootsnow)
[xx,yy] = subrootsreptwo(f,g,min(xrootsnow(j))-tolbb,max(xrootsnow(j))+tolbb,min(yrootsnow(j))-tolbb,max(yrootsnow(j))+tolbb,xwid,ywid,0,max_degree/2); % local (second) bez
xxx = [xxx xx]; yyy = [yyy yy];
end
else
xxx = xrootsnow;
yyy = yrootsnow;
end
end
xroots = [xroots xxx]; yroots = [yroots yyy];
end
% finally collapse close roots
xrootsnow = []; yrootsnow = [];
mm = blockingxy(xroots,yroots,min(xwid*sqrt(eps)*10));
for ii = 1:max(mm)
xtmp = xroots(mm==ii); ytmp = yroots(mm==ii);
res = zeros(1,length(xtmp));
for ij = 1:length(xtmp)
res(ij) = norm([feval(f,xtmp(ij),ytmp(ij)) feval(g,xtmp(ij),ytmp(ij))]);
end
[mres,IX] = min(res);
if min(mres)<1e-10,
xrootsnow = [xrootsnow xtmp(IX)]; yrootsnow = [yrootsnow ytmp(IX)];
end
end
xroots = xrootsnow; yroots = yrootsnow;
if donewton % optional Newton update (don't do by default)
[xroots,yroots] = newtonupdate(f,g,xroots,yroots);
end
% discard roots safely outside initial domain
xmax = xmax - xwid*domain_overlook; xmin = xmin + xwid*domain_overlook; % original domain
ymax = ymax - ywid*domain_overlook; ymin = ymin + ywid*domain_overlook;
ii = find(xroots<xmax+xwid*1e-15 & xroots>xmin-xwid*1e-15 & yroots<ymax+ywid*1e-15 & yroots>ymin-ywid*1e-15);
xroots = xroots(ii); yroots = yroots(ii);
for i=1:length(xroots)
if xroots(i)>xmax, xroots(i) = xmax; end % push outliers to boundary
if xroots(i)<xmin, xroots(i) = xmin; end
if yroots(i)>ymax, yroots(i) = ymax; end
if yroots(i)<ymin, yroots(i) = ymin; end
end
end
function [xroots,yroots] = subrootsreptwo(f,g,xmin,xmax,ymin,ymax,xwid,ywid,tolreg,maxd,subdividestop)
% execute subdivision and if degrees small enough, run bezout
xroots = [];yroots = [];
if xmin==xmax || ymin==ymax, return , end % empty domain
approx_tol = 1e-13; % Approximation accuracy.
magicnum = 0.004849834917525; % 'magic number'
honournum = -0.0005194318842611; % 'honourary number'
if exist('subdividestop','var')==0, subdividestop = 0.008;end
ff = cheb2(f,[xmin xmax ymin ymax],approx_tol,maxd+2); % sample at a bit more than maxd points
gg = cheb2(g,[xmin xmax ymin ymax],approx_tol,maxd+2);
fcoef = ff.coeffs; gcoef = gg.coeffs;
% subdivision test
if (xmax-xmin)>xwid*subdividestop || (ymax-ymin)>ywid*subdividestop % subdivide only if domain is not too small
if (size(fcoef,1)>maxd && size(fcoef,2)>maxd) ||...
(size(gcoef,1)>maxd && size(gcoef,2)>maxd)
% subdivide in both x,y
xmed = (xmax+xmin)/2 - magicnum * (xmax-xmin)/2;
ymed = (ymin+ymax)/2 - honournum * (ymax-ymin)/2;
[xroots1,yroots1] = subrootsreptwo(f,g,xmin,xmed,ymin,ymed,xwid,ywid,tolreg,maxd,subdividestop);
[xroots12,yroots12] = subrootsreptwo(f,g,xmed,xmax,ymin,ymed,xwid,ywid,tolreg,maxd,subdividestop);
[xroots2,yroots2] = subrootsreptwo(f,g,xmin,xmed,ymed,ymax,xwid,ywid,tolreg,maxd,subdividestop);
[xroots22,yroots22] = subrootsreptwo(f,g,xmed,xmax,ymed,ymax,xwid,ywid,tolreg,maxd,subdividestop);
xroots = [xroots xroots1 xroots2 xroots12 xroots22];
yroots = [yroots yroots1 yroots2 yroots12 yroots22];
return
elseif (size(fcoef,1)>maxd)||(size(gcoef,1)>maxd) % subdivide in y
ymed = (ymin+ymax)/2 - magicnum * (ymax-ymin)/2;
[xroots1,yroots1] = subrootsreptwo(f,g,xmin,xmax,ymin,ymed,xwid,ywid,tolreg,maxd,subdividestop);
[xroots12,yroots12] = subrootsreptwo(f,g,xmin,xmax,ymed,ymax,xwid,ywid,tolreg,maxd,subdividestop);
xroots = [xroots xroots1 xroots12];
yroots = [yroots yroots1 yroots12];
return
elseif (size(fcoef,2)>maxd)||(size(gcoef,2)>maxd) % subdivide in x
xmed = (xmax+xmin)/2 - honournum * (xmax-xmin)/2;
[xroots1,yroots1] = subrootsreptwo(f,g,xmin,xmed,ymin,ymax,xwid,ywid,tolreg,maxd,subdividestop);
[xroots12,yroots12] = subrootsreptwo(f,g,xmed,xmax,ymin,ymax,xwid,ywid,tolreg,maxd,subdividestop);
xroots = [xroots xroots1 xroots12];
yroots = [yroots yroots1 yroots12];
return
end
else
ff = cheb2(f,[xmin xmax ymin ymax],approx_tol,round(1.5*maxd)); % didn't resolve, sample at more than maxd points but not too much
gg = cheb2(g,[xmin xmax ymin ymax],approx_tol,round(1.5*maxd));
end
F = ff.coeffs; G = gg.coeffs;
if isempty(F); F = 0; end
if isempty(G); G = 0; end
if (2-eps*10)*abs(F(end,end))>sum(sum(abs(F))) || (2-eps*10)*abs(G(end,end))>sum(sum(abs(G)))
% 'no roots here!'
else
if min(min(size(F)),min(size(G)))<=1,
if length(F)<=1 && length(G)<=1, % constant
if (abs(F)<=1e-15) && (abs(G)<=1e-15), % flat 0; just say middle point is 0
xroots = (xmax+xmin)/2; yroots = (ymax+ymin)/2;
else
xroots = [];yroots=[];
end
else
% 'no roots here!'
[xroots,yroots] = onevar(F,G,xmin,xmax,ymin,ymax);
end
else
[xroots,yroots] = runbezval(F,G,xmin,xmax,ymin,ymax,tolreg);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [xroots,yroots] = runbezval(F,G,xmin,xmax,ymin,ymax,tol)
% run bezout (core code):
% form Bezout matrix polynomial and solve eigenproblem, then find other variable
% form Bezoutian at magic number and find null space and diagonal balancing
% regularization tolerance
mc = size(F,1)-1+size(G,1)-1+1; % # of sampling points (degree of B(y))
mc = max(mc,2);
magicnum = 0.004849834917525; % 'magic number'
doswap = 0;
% swap x and y if appropriate
if max(size(F,1),size(G,1))*(size(F,2)+size(G,2)) > max(size(F,2),size(G,2))*(size(F,1)+size(G,1))
F = F'; G = G'; doswap = 1;
mc = size(F,1)-1+size(G,1)-1+1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% form B and regularize %%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
B0 = formBez(F,G,magicnum); % sample Bezoutian at 'magic number'
% now form Bezoutians at Chebyshev points
x = chebpts(mc);
B = zeros(size(B0,1),size(B0,1),mc);
Bsum = zeros(size(B0));
for i = 1:mc
B(:,:,i) = formBez(F,G,x(i));
Bsum = Bsum+abs(B(:,:,i));
% B(:,:,i) = Btmp(k+1:end,k+1:end); % extract regular part
end
if tol == 0, % no regularization
k = 0;
else
%%%%%%%%%% REGULARIZATION parameter %%%%%%%%%%%%%%% extract lower-right part of Bezoutian %%%
d = diag(B0);
for i = 1:size(B0,1), d(i) = max(max(abs(Bsum(1:i,1:i)))); end
m = find(abs(d)/max(abs(d))> tol);
if isempty(m)
k = 0;
else
offd = zeros(1,m(1)-1);
for i = 1:m(1)-1
offd(i) = max(max(abs(Bsum(i+1:end,1:i))));
end
mm = find(offd/max(abs(d))<sqrt(tol));
if isempty(mm), m(1) = 1; else m(1) = max(mm); end
k = max(m(1)-1,0);
end
end
%regsize = [length(B0) k]
if length(size(B))<3,
ei = [];
else
B = B(k+1:end,k+1:end,:); % regularize
ns = size(B); BB = reshape(B,ns(1),ns(1)*ns(3));
CC = matrixChebfft(BB);
for i = 1:mc
B(:,:,i) = CC(:,(i-1)*size(B,1)+1:i*size(B,1));
end
% cutoff negligible B
nrmB = norm(B(:,:,end),'fro');
for ii=1:size(B,3)
if norm(B(:,:,ii),'fro')/nrmB > 10*eps, break; end
end
B = B(:,:,ii:end);
ns = size(B);
%Bori = B;
% diagonal balancing (optional)
[Dori] = balancecong(B0(k+1:end,k+1:end));
for i = 1:size(B,3)
B(:,:,i) = Dori * B(:,:,i) * Dori;
B(:,:,i) = rot90(B(:,:,i),2); % fliplr,ud
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% done forming B, now solve polyeig %%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% colleague QZ (most stable but slow)
nrm = norm(BB,'fro')/ns(1); % scale as suggested as Van Dooren
ei = chebT1rtsmatgep(B/nrm);
%[ei,AG,BG] = chebT1rtsmatgep(B/nrm); ei = stairqz(AG,BG); % semi-staircase
end
yreal = sort(real(ei(abs(real(ei))<=1+10*eps & abs(imag(ei))<sqrt(eps)*10)));
% finally obtain x-values
[xroots,yroots] = xunivariate(F,G,xmin,xmax,ymin,ymax,yreal,doswap);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%% UNIVARIATE %%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [xval,yval] = xunivariate(F,G,xmin,xmax,ymin,ymax,y,doswap)
% compute x-vals from y
% collapse if near-multiple y-values are present
magicnum = 0.004849834917525; % 'magic number'
ep = 10*eps; % tolerance for collapsing
dist = abs(y(1:end)-[y(2:end);2]);
ii = dist>ep;
y = y(ii);
xreal = magicnum*ones(size(y));
xtmp = [];ytmp = [];
for j = 1:length(y)
if xreal(j)==magicnum
% compute coefficients via vandermonde vector
vy = vandercheb(y(j),size(G,1)); coef1 = vy'*G;
vy = vandercheb(y(j),size(F,1)); coef2 = vy'*F;
% find roots of two univariate polys via colleague
if length(coef1)<=1 || norm(coef1)==0, rts1=[];
else
rts1 = chebT1rts(coef1(find(abs(coef1)>0,1,'first'):end)');
rts1 = real(sort(rts1(abs(imag(rts1))<=10*1e-8 & abs(rts1)<=1+10*eps)));
end
if length(coef2)<=1 || norm(coef2)==0, rts2=[];
else
rts2 = chebT1rts(coef2(find(abs(coef2)>0,1,'first'):end)');
rts2 = real(sort(rts2(abs(imag(rts2))<=10*1e-8 & abs(rts2)<=1+10*eps)));
end
% collapse nearby roots if any (deal with multiple roots)
dist = abs(rts1(1:end)-[rts1(2:end);2]);
ii = dist>10*ep; rts1 = rts1(ii);
dist = abs(rts2(1:end)-[rts2(2:end);2]);
ii = dist>10*ep; rts2 = rts2(ii);
rts = sort([rts1;rts2]); res = ones(size(rts));
% compute function values
for i = 1:length(rts)
res(i) = max([abs(coef1*vandercheb(rts(i),size(G,2))),abs(coef2*vandercheb(rts(i),size(F,2)))]);
end
% adopt depending on the interval size
if xmax-xmin > 2e-3,
%rtscan = rts(find(res<1000*sqrt(eps))); % candidates for x-values
rtscan = rts((res<100*sqrt(eps))); % candidates for x-values
elseif xmax-xmin > 1e-7, % local bez
rtscan = rts((res<1e-10));
else % very local (final) bez
rtscan = rts((res<1e-12));
end
% collect/collapse candidate roots
if ~isempty(rtscan)
skipnext = 0;
for i = 1:length(rtscan)-1
if skipnext
skipnext = 0;
else
if ( abs(rtscan(i)-rtscan(i+1))<10*ep ),
skipnext = 1;
vali = max([abs(coef1*vandercheb(rtscan(i),size(G,2))), abs(coef2*vandercheb(rtscan(i),size(F,2)))]);
valip= max([abs(coef1*vandercheb(rtscan(i+1),size(G,2))),abs(coef2*vandercheb(rtscan(i+1),size(F,2)))]);
if ( vali < valip )
xtmp = [xtmp;rtscan(i)];
else
xtmp = [xtmp;rtscan(i+1)];
end
else
xtmp = [xtmp;rtscan(i)];
end
ytmp = [ytmp;y(j)];
end
end
% last i
if skipnext % do nothing
else
xtmp = [xtmp;rtscan(end)]; ytmp = [ytmp;y(j)];
end
end
end
end
if doswap ==0 % recover if swapped initially
xval = (xmin+xmax)/2+(xmax-xmin)/2*xtmp';
yval = (ymin+ymax)/2+(ymax-ymin)/2*ytmp';
else
xval = (xmin+xmax)/2+(xmax-xmin)/2*ytmp';
yval = (ymin+ymax)/2+(ymax-ymin)/2*xtmp';
end
return
end
%%%%%%%%%%%%%%%%%%%%%% KEEP IN CASE I NEED AT SOME STAGE %%%%%%%%%%%%%%%%%
% function [xroots,yroots,sproots] = localrefine(f,g,xmin,xmax,ymin,ymax,xwid,ywid,tolreg,maxd)
% % execute subdivision and if degrees small enough, run bezout
%
% approx_tol = 1e-13; % cheb2 cutoff tolerance
% ff = cheb2(f,[xmin xmax ymin ymax],approx_tol,maxd+2); % sample at a bit more than maxd points
% gg = cheb2(g,[xmin xmax ymin ymax],approx_tol,maxd+2);
% F = ff.coeffs; G = gg.coeffs;
%
% if isempty(F),
% v = vandercheb(0,size(G,2));
% G = G*v;
% rx = chebT1rts(G(find(abs(G)>0,1,'first'):end)')';
% rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));
% yroots = (ymin+ymax)/2+(ymax-ymin)/2*rx;
% xroots = (xmin+xmax)/2*ones(size(yroots));
% return,
% end
% if isempty(G),
% v = vandercheb(0,size(F,2));
% F = F*v;
% rx = chebT1rts(F(find(abs(F)>0,1,'first'):end)')';
% rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));
% yroots = (ymin+ymax)/2+(ymax-ymin)/2*rx;
% xroots = (xmin+xmax)/2*ones(size(yroots));
% return,
% end
%
%
% if min(min(size(F)),min(size(G)))<=1,
% if length(F)<=1 && length(G)<=1, % constant
% if (abs(F)<=1e-15) && (abs(G)<=1e-15), % flat 0; just say middle point is 0
% xroots = (xmax+xmin)/2; yroots = (ymax+ymin)/2;
% else
% xroots = [];yroots=[];
% end
% else
% % 'no roots here!'
% %[xmin xmax ymin ymax],keyboard
% [xroots,yroots] = onevar(F,G,xmin,xmax,ymin,ymax);
% end
% else
% [xroots,yroots] = runbezval(F,G,xmin,xmax,ymin,ymax,tolreg); % bez not syl
% end
% end
function [xroots,yroots] = onevar(F,G,xmin,xmax,ymin,ymax)
% when either F or G is constant
doswap = 0;
if min(min(size(F)))==1,
if size(F,2) ==1, FF = F'; GG = G'; doswap = 1;
else FF = F; GG = G;
end
else
if size(G,2) ==1, FF = G'; GG = F'; doswap = 1;
else FF = G; GG = F;
end
end
if length(FF)==1
if abs(FF)<1e-15,
if min(size(GG))==1,
rx = chebT1rts(GG(find(abs(GG)>0,1,'first'):end)')';
rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));
rr = rx;
else % GG is matrix. just take x=0 and find y.
%gcheb = chebfun2(g,[xmin xmax ymin ymax]); roots(gcheb);
v = vandercheb(0,size(GG,2));
GG = GG*v;
rx = chebT1rts(GG(find(abs(GG)>0,1,'first'):end)')';
rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));
rr = rx;
end
if size(GG,1)>size(GG,2)
yroots =rr; xroots = zeros(size(rr));
else
xroots =rr; yroots = zeros(size(rr));
end
else
xroots = []; yroots = [];
end
else
rx = chebT1rts(FF(find(abs(FF)>0,1,'first'):end)');
rx = real(sort(rx(abs(imag(rx))<=1e-8 & abs(rx)<=1+10*eps)));
xroots = []; yroots = [];
for j=1:length(rx)
vy = vandercheb(rx(j),size(GG,2)); coef = GG*vy;
% ry = roots(chebfun(coef,'coeffs'))';
if length(coef)<=1,
if norm(coef)<1e-15,
ry = 0;
else ry=[];
end
else
rts2 = chebT1rts(coef(find(abs(coef)>0,1,'first'):end));
rts2 = real(sort(rts2(abs(imag(rts2))<=1e-8 & abs(rts2)<=1+10*eps)));
ry = rts2';
end
yroots = [yroots ry];
xroots = [xroots rx(j)*ones(size(ry))];
end
end
if doswap
xt = xroots; xroots = yroots; yroots = xt;
end
xroots = (xmin+xmax)/2+(xmax-xmin)/2*xroots;
yroots = (ymin+ymax)/2+(ymax-ymin)/2*yroots;
end
function [r,A,B] = chebT1rtsmatgep(c)
% CHEBT1RTSMATGEP(c), finds via QZ the roots of a MATRIX polynomial
% expressed in a ChebT basis
% by using the colleague matrix *pencil* of the first kind. F can be a vector of
% coefficients or a chebfun. Coefficients are ordered highest degree down.
%
% c is a nxnxk array. k-1 is the degree, n is the matrix size.
k=length(c(1,1,:)); n=length(c(:,:,1));
if size(c,3) ==2, % linear case
r = eig(c(:,:,2),-c(:,:,1));
return
end
for ii=2:k
c(:,:,ii)=c(:,:,ii)*(-.5); % coefficients
end
c(:,:,3) = c(:,:,3)+.5*c(:,:,1);
oh = .5*ones(n*(k-2),1);
% form colleague matrix A,B:
A = diag(oh,n)+diag(oh,-n);
A(end-n+1:end,end-2*n+1:end-n) = eye(n);
for ii=1:k-1
A(1:n,(ii-1)*n+1:ii*n) = c(:,:,ii+1);
end
B=eye(size(A)); B(1:n,1:n)=c(:,:,1);
r = eig(A,B);% Compute roots
end
function r = chebT1rts(c)
% CHEBT1RTS(F), finds the roots of a polynomial expressed in a Cheb T basis
% by using the colleague matrix of the first kind. F can be a vector of
% coefficients or a chebfun.
if length(c)<=1
r=[];
return
end
if size(c,1) < size(c,2) % c is column vector
c = c';
end
if length(c)==2, % linear case
r = -c(2)/c(1); return
end
if c(1)==0
c(1)=eps*max(c); % perturb a zero leading coefficient by eps.
end
c = -.5*c(end:-1:2)/c(1);
c(end-1) = c(end-1)+.5;
oh = .5*ones(length(c)-1,1);
% Modified colleague matrix:
A = diag(oh,1)+diag(oh,-1);
A(end,end-1) = 1; A(1,:) = flipud(c);
r = eig(A);% Compute roots as eig(A)
end
function B = formBez(F,G,y)
% forms Bezoutian using DLP for F,G (matrices) at a specific value of y.
yv = vandercheb(y,max(size(F,1),size(G,1))); % Chebyshev-vandermonde form vector
ff = yv(end-size(F,1)+1:end)'*F;
gg = yv(end-size(G,1)+1:end)'*G;
if length(ff)<length(gg), gt = gg; gg=ff; ff = gt;end
if length(ff)==length(gg), ff = [0 ff]; shrink = 1; else shrink = 0; end
B = DLPforbez(ff,[zeros(1,length(ff)-length(gg)-1)';gg']); %B=(B+B')/2; input k
if shrink
B = B(2:end,2:end);
end
end
function [Y] = DLPforbez(AA,v)
% DLPforbez constructs the Bezoutian. Highly specified for Chebyshev
% biroots.
%
[n m] = size(AA); k=m/n-1; s=n*k; % matrix size and degree
S = [zeros(1,k+1);(2*v)*AA];
R = S'-S;
% Bartel-Stewart algorithm on M'Y+YM=R, M is upper triangular.
Y = zeros(s);
if s ==1, Y = R(1,2); return, end
Y(1,:) = R(1,2:end);
Y(2,:) = R(2,2:end)+[Y(1,2:end-1) 2*Y(1,end) 0]+[0 Y(1,1:end-1)];
for i = 3:k % backwards substitution
Y(i,:) = R(i,2:end)-Y(i-2,1:end)+[Y(i-1,2:end-1) 2*Y(i-1,end) 0]+[0 Y(i-1,1:end-1)];
end
Y(k,:) = Y(k,:)/2;
end
function D = matrixChebfft(A)
% First attempt and matrix chebfft. Given a set of matrix coefficients,
% this function is designed to return the set of matrix values.
% Assumption: The matrix coefficients are square.
n = size(A,1); k = size(A,2)/size(A,1); % get matrix size and degree.
if ( abs( k - round(k) ) > 0 )
error('CHEBFUN:CHEBFUN2V:roots:matrixChebfft:badDegree', ...
'Degree must be integer');
end
D = A;
for jj = 1:n % for each column of A
B = A(:,jj:n:n*k);
C = chebtech2.vals2coeffs(B.'); % convert first column of each coefficient to values.
D(:,jj:n:n*k) = rot90(C, -1); % assign to output.
end
end
function m = blockingxy(x,y,delta)
% BLOCKINGXY Produce blocking pattern for data x,y within tolerance delta.
% Elements will be assigned numbers for each class.
if isempty(x), m=[]; return, end
[xx,IX] = sort(x); m = ones(size(x));
xxp = ones(size(x)); ppos = ones(size(x));
p = 1;
for i=1:length(x)-1
if abs(xx(i)-xx(i+1))>delta,
p = p+1; ppos(p) = i+1;
end
end
ppos = ppos(1:p); % done with x
q = 0;
for i=1:p
q = q+1;
if i<p
m(IX(ppos(i):ppos(i+1)-1)) = q*ones(size(ppos(i):ppos(i+1)-1));
ynow = y(IX(ppos(i):ppos(i+1)-1));
else % i=p, end
m(IX(ppos(i):end)) = q*ones(size(IX(ppos(i):end)));
ynow = y(IX(ppos(i):end));
end
[yy,IY] = sort(ynow);
for j = 1:length(yy)-1
if abs(yy(j)-yy(j+1))>delta,
q = q+1;
m(IX(ppos(i)+IY(j+1:end)-1)) = q*ones(size(IX(ppos(i)+IY(j+1:end)-1)));
end
end
end
end
function v = vandercheb(x,n)
% v = vandercheb(x,n) forms unit vector in vandermonde form
v = zeros(n,1);
for i = 1:n
v(end-i+1) = real(cos((i-1)*acos(x)));
end
end
function D = balancecong(B)
% diagonal congruence balancing to make the diagonals of DBD equal.
D = eye(length(B));
for i = length(B)-1:-1:1;
if norm(B(i,:))>0,
D(i,i) = max(1,sqrt(norm(B(end,:))/norm(B(i,:))));
else
D(i,i) = D(i+1,i+1);
end
end
end
function [xroots,yroots] = newtonupdate(f,g,xroots,yroots,itnum)
%%%%%%%%%%%% newton update %%%%%%%%%%%%%%%%
% Use one iteration of Newton to get 14-15 digits.
if nargin < 5
itnum = 1;
end
f = chebfun2(f); g = chebfun2(g) ;
tol = 1e-15;
fx = diff(f,1,2); fy=diff(f); gx = diff(g,1,2); gy=diff(g); % derivatives.
J = @(x,y) [feval(fx,x,y) feval(fy,x,y);feval(gx,x,y) feval(gy,x,y)]; % Jacobian
for jj=1:itnum
r = [xroots' yroots'];
for kk = 1:size(r,1)
x0 = [r(kk,1),r(kk,2)].';dx=1; iter = 1;
while ( norm(dx) > 10*tol && iter < 2 )
dx = J(x0(1),x0(2)) \ -[feval(f,x0(1),x0(2));feval(g,x0(1),x0(2))]; % update
x0 = dx + x0; iter = iter + 1;
end
r(kk,:) = x0;
end
xroots = r(:,1)'; yroots = r(:,2)';
end
end
function g = cheb2(f,varargin)
% Basic bivariate tensor product, nonadaptive constructor.
default_tol = 10*eps;
default_n = 300;
% Did we get any user defined domain?
if nargin == 2
% Assume this is a user defined domain [a b c d]
if numel(varargin{1}) > 1
ends = varargin{1};
tol = default_tol;
elseif numel(varargin{1}) == 1
tol = varargin{1};
end
elseif nargin == 3
ends = varargin{1};
tol = varargin{2};
elseif nargin == 4
ends = varargin{1};
tol = varargin{2};
n = varargin{3};
else
% default to the unit interval [-1 1 -1 1]
ends = [-1 1 -1 1];
tol = default_tol;
n = default_n;
end
if isstruct(f)
g = f;
return;
end
% evaluate the function on a grid.
if exist('n','var')==0,
n = 300;
end
x = mypoints(n,ends(1:2)); y = mypoints(n,ends(3:4));
[xx, yy]=meshgrid(x,y); F = f(xx,yy);
% vertical scale for machine precision
vscl = max(1,max(abs(F(:)))); % don't go for more than absolute accuracy.
% Compute bivariate Chebyshev T coefficients.
C = chebfun2.vals2coeffs(F);
C = rot90(C, -2);
% Very simple truncation of the coefficients.
%m = find(max(abs(C))>100*eps*vscl,1,'first'); n = find(max(abs(C.'))>100*eps*vscl,1,'first');
m = find(max(abs(C))>tol*vscl,1,'first'); n = find(max(abs(C.'))>tol*vscl,1,'first');
C = C(n:end,m:end);
% Form cheb2 object.
g = struct('coeffs',C,'scl',vscl,'corners',ends);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% Marching Squares %%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [xroots, yroots] = roots_marchingSquares( f )
fx = f.components{1};
fy = f.components{2};
pref = chebfunpref;
tol = pref.cheb2Prefs.chebfun2eps;
num = 0;
r = zeros(1,2);
dom = fy.domain;
nf = f.nComponents;
if ( nf > 2 )
error('CHEBFUN:CHEBFUN2V:roots:zeroSurface', ...
'CHEBFUN2 is unable to find zero surfaces.');
end
if ( length(fx) == 1 || length(fy) == 1 ) % one of them is of the form u(x)v(y)
if ( length(fx) == 1 )
% Find roots of fx.
rowz = roots(fx.rows);
colz = roots(fy.cols);
for jj = 1:length(rowz)
rr = roots(fy(rowz(jj),:));
for kk = 1:length(rr)
r(num+1,:) = [rowz(jj) rr(kk)]; num=num+1;
end
end
for jj = 1:length(colz)
rr = roots(fy(:,colz(jj)));
for kk = 1:length(rr)
r(num+1,:) = [rr(kk) colz(jj)]; num=num+1;
end
end
elseif ( length(fy) == 1 )
% roots lie along these lines
rowz = roots(fy.rows);
colz = roots(fy.cols);
for jj = 1:length(rowz)
ff = fx(rowz(jj),:);
rr = roots(ff);
for kk = 1:length(rr)
r(num+1,:) = [rowz(jj) rr(kk)]; num=num+1;
end
end
for jj = 1:length(colz)
rr = roots(fx(:,colz(jj)));
for kk = 1:length(rr)
r(num+1,:) = [rr(kk) colz(jj)]; num=num+1;
end
end
end
else
% Use contourc to get roots to 3-4 digits.
N = 400;
NewtonFail = 0;
rfx = roots(fx);
rfy = roots(fy);
x = linspace(-1, 1, N); % this is on [-1,1] because all zero contours are represented by chebfuns on the default interval.
r = zeros(0,2);
num = 0;
Rx = rfx(x(:), :);
Ry = rfy(x(:), :);
if ( any(size(Rx)==[1 1]) )
Rx = Rx( : );
end
if ( any(size(Ry)==[1 1]) )
Ry = Ry( : );
end
for jj = 1:size(rfx, 2)
rx = Rx(:, jj);
rlx = real( rx );
imx = imag( rx );
for kk = 1:size(rfy,2)
ry = Ry(:,kk);
[x0, y0]=intersections(rlx, imx, real(ry), imag(ry));
if ( ~isempty(x0) )
r(num+1:num+length(x0),1)=x0;
r(num+1:num+length(x0),2)=y0;
num=num+length(x0);
end
end
end
% Use a few iterations of Newton to get 14-15 digits.
f = fx;
g = fy;
fx = diff(f,1,2);
fy = diff(f);
gx = diff(g,1,2);
gy = diff(g); % derivatives.
J = @(x,y) [feval(fx,x,y) feval(fy,x,y);...
feval(gx,x,y) feval(gy,x,y)]; % Jacobian
warnstate = warning('off','CHEBFUN:CHEBFUN2:NEWTON'); % turn warnings off, and capture Newton failure instead.
for kk = 1:size(r,1)
x0 = [r(kk,1), r(kk,2)].';
dx = 1;
iter = 1;
while ( norm(dx) > 10*tol && iter < 15 )
dx = J(x0(1),x0(2)) \ -[feval(f,x0(1),x0(2));feval(g,x0(1),x0(2))]; % update
x0 = dx + x0; iter = iter + 1;
end
if ( norm(dx) < 10*sqrt(tol) ) % we may have diverged so don't always update.