forked from GiggleLiu/ModernScientificComputing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.linear-least-square.jl
2052 lines (1723 loc) · 61 KB
/
5.linear-least-square.jl
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
### A Pluto.jl notebook ###
# v0.19.22
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 03d7776f-1ae1-4305-8638-caa82837166a
using PlutoUI
# ╔═╡ f375e09d-cfe2-4ca8-a2c1-32d11dd0b236
using Plots
# ╔═╡ 078d0638-7540-4ca4-bc11-b77b2c7f28c4
using LinearAlgebra
# ╔═╡ 24ace4f1-3801-4586-93cb-dcaecf1df9a3
using Test
# ╔═╡ c0992773-4324-4c22-a806-9ec7bd135a2f
using Luxor
# ╔═╡ c91e28af-d372-429b-b0c1-e6579b6230d4
TableOfContents()
# ╔═╡ 50272a9d-5040-413c-84f5-69ffe06b133a
html"""
<button onclick="present();"> present</button>
"""
# ╔═╡ 3bc7e1c5-4d06-4b2d-adbd-20935f8c54b2
ts = collect(0.0:0.5:10.0)
# ╔═╡ 69ea48d1-58c2-4e7d-a351-c4d96dcbed55
ys = [2.9, 2.7, 4.8, 5.3, 7.1, 7.6, 7.7, 7.6, 9.4, 9.0, 9.6, 10.0, 10.2, 9.7, 8.3, 8.4, 9.0, 8.3, 6.6, 6.7, 4.1]
# ╔═╡ 42fd3d15-40b6-4051-913b-293bd953028c
scatter(ts, ys; label="", xlabel="t", ylabel="y", ylim=(0, 10.5))
# ╔═╡ af03fa73-40ce-45f5-9f4f-d8c7809f7166
A2 = [ones(length(ts)) ts ts.^2]
# ╔═╡ c4b34c32-fc00-4a7c-8089-edd35c23bd65
A2
# ╔═╡ 7209792f-4944-4d06-9098-ae7ce1cea103
A2inv = pinv(A2)
# ╔═╡ d9a623cd-74fb-4404-8f62-30ed24a82ed7
x2 = pinv(A2) * ys
# ╔═╡ 72cb2367-c4bc-4ed1-b942-4144881e558f
norm(A2 * x2 - ys)^2
# ╔═╡ 0653d1cc-febe-4b97-9cea-ccf1ea5ef77c
let
plt = scatter(ts, ys; xlabel="t", ylabel="y", ylim=(0, 10.5), label="data")
tt = 0:0.1:10
plot!(plt, tt, map(t->x2[1] + x2[2]*t + x2[3] * t^2, tt); label="fitted")
end
# ╔═╡ 3cfd45c5-4618-4b9a-a931-0b0cb7f12cf1
pinv(A2)
# ╔═╡ 78bd6ebd-a710-4cbb-a2a4-6ac663eb64d5
cond(A2)
# ╔═╡ 7e8d4ef5-6b3a-4588-8e1b-5a491860f9f9
opnorm(A2) * opnorm(pinv(A2))
# ╔═╡ 8e07091c-0b4b-490a-9cf7-dad94c3fa08a
maximum(svd(A2).S)/minimum(svd(A2).S)
# ╔═╡ f240e540-65a2-4f82-8006-a1d2a9955d1b
let
p = 12345678
q = 1
p - sqrt(p^2 + q)
end
# ╔═╡ f4acf2cd-a183-4986-91f5-da6729759c84
let # more accurate
p = 12345678
q = 1
q/(p + sqrt(p^2 + q))
end
# ╔═╡ 135c30d2-2168-4e88-82e3-673bbb4764d9
rectQ = Matrix(qr(A2).Q)
# ╔═╡ 573b545b-314a-4938-8ae8-1be006a918ae
qr(A2).R
# ╔═╡ 7d4d74ed-2de8-4b95-88c4-92d1398a7c4c
rectQ * qr(A2).R ≈ A2
# ╔═╡ 0322976d-d3a2-42ba-ab55-8d75796b0388
struct HouseholderMatrix{T} <: AbstractArray{T, 2}
v::Vector{T}
β::T
end
# ╔═╡ 525d5273-e10f-4669-afc4-7a527ff25acf
Base.size(A::HouseholderMatrix) = (length(A.v), length(A.v))
# ╔═╡ d9a7fbb0-243e-452c-ad23-ed116bf1849c
Base.size(A::HouseholderMatrix, i::Int) = i == 1 || i == 2 ? length(A.v) : 1
# ╔═╡ 9c9ea963-64db-437d-8509-d334b27b57d4
# some other methods to avoid ambiguity error
# ╔═╡ db6114bc-b253-4c7b-948c-1ad2036fd4b8
Base.inv(A::HouseholderMatrix) = A
# ╔═╡ 6c2555d4-5d84-42e0-8dd3-6e5781037a95
Base.adjoint(A::HouseholderMatrix) = A
# ╔═╡ 42812c21-229f-4e4a-b7ad-0d0317061776
inv(A2' * A2) * A2'
# ╔═╡ 5c3d483b-c1a4-4af9-b06f-f01b306d383b
A2' * A2
# ╔═╡ 4979c507-72c3-4cbb-8a7e-27cf4c9c4660
A2' * ys
# ╔═╡ 8782019c-f4b4-4b68-9d84-61aec009fe50
rectQ' * rectQ
# ╔═╡ 32258e09-1dd7-4954-be0f-98db3c2fb7ed
@testset "householder property" begin
v = randn(3)
β = 2/norm(v, 2)^2
H = I - β * v * v'
# symmetric
@test H' ≈ H
# reflexive
@test H^2 ≈ I
# orthogonal
@test H' * H ≈ I
end
# ╔═╡ 64a46e12-ae2e-445f-b870-3389e15bcc5b
# the `mul!` interfaces can take two extra factors.
function left_mul!(B, A::HouseholderMatrix)
B .-= (A.β .* A.v) * (A.v' * B)
return B
end
# ╔═╡ 0c263746-b0a3-42df-a52b-9f9f51341db2
# the `mul!` interfaces can take two extra factors.
function right_mul!(A, B::HouseholderMatrix)
A .= A .- (A * (B.β .* B.v)) * B.v'
return A
end
# ╔═╡ 6e6b7827-86a1-4f20-801e-7d9c385d0d26
Base.getindex(A::HouseholderMatrix, i::Int, j::Int) = A.β * A.v[i] * conj(A.v[j])
# ╔═╡ db07252c-d1c1-46af-a16e-9a7d1e91ce4f
md"""# Review: Solving linear equations
Given $A\in \mathbb{R}^{n\times n}$ and $b \in \mathbb{R}^n$, find $x \in \mathbb{R}^n$ s.t.
```math
Ax = b
```
1. LU factorization with Gaussian Elimination (with Pivoting)
2. Sensitivity analysis: Condition number
2. Computing matrix inverse with Guass-Jordan Elimination
"""
# ╔═╡ 039e70f8-b8cf-11ed-311e-4d770652d6a9
md"# Linear Least Square Problem"
# ╔═╡ 1285a0ff-2290-49fb-bd16-74ebb155e6ff
md"## Data Fitting"
# ╔═╡ c12b4f4e-81d7-4b8a-8f77-b4e940199064
md"""
Given $m$ data points $(t_i, y_i)$, we wish to find the $n$-vector $x$ of parameters that gives the "best fit" to the data by the model function $f(t, x)$, with
```math
f: \mathbb{R}^{n+1} \rightarrow \mathbb{R}
```
```math
\min_x\sum_{i=1}^m (y_i - f(t_i, x))^2
```
"""
# ╔═╡ 19083b13-3b40-43ea-9535-975c2f1be8bb
md"## Example"
# ╔═╡ 26461708-def3-44b5-bb8f-4eb9f75c66d5
md"""
```math
f(x) = x_0 + x_1 t + x_2 t^2
```
"""
# ╔═╡ f0b7e196-80dd-4cd2-a8ce-3b99eee32580
md"""
```math
Ax = \left(\begin{matrix}
1 & t_1 & t_1^2\\
1 & t_2 & t_2^2\\
1 & t_3 & t_3^2\\
1 & t_4 & t_4^2\\
1 & t_5 & t_5^2\\
\vdots & \vdots & \vdots
\end{matrix}\right)
\left(\begin{matrix} x_1 \\ x_2 \\ x_3\end{matrix}\right) \approx
\left(\begin{matrix}y_1\\ y_2\\ y_3 \\ y_4 \\ y_5\\\vdots\end{matrix}\right) = b
```
"""
# ╔═╡ e4e444bf-0d07-4f6c-a104-ac0569928347
md"# Normal Equations"
# ╔═╡ 5124f2d6-37e3-4cf9-82df-eb50372271cb
md"The goal: minimize $\|Ax - b\|_2^2$"
# ╔═╡ dbd8e759-f5bf-4239-843f-2c394e7665c1
md"""
```math
A^T Ax = A^T b
```
"""
# ╔═╡ 58834440-1e0a-432b-9be2-41db98fa2742
md"## Pseudo-Inverse"
# ╔═╡ 81b6f4cb-a6c8-4a86-91f7-ac88646651f8
md"
```math
A^{+} = (A^T A)^{-1}A^T
```
```math
x = A^+ b
```
"
# ╔═╡ 291caf11-bacd-4171-8408-410b50f49183
md"Pseudoinverse"
# ╔═╡ 800b3257-0449-4d0d-8124-5b6ca7882902
md"The julia version"
# ╔═╡ e6435900-79be-46de-a7aa-7308df1e486a
md"## Example"
# ╔═╡ 6d7d33ff-1b2b-4f03-b4d4-a7f31dfd3b74
md"## The geometric interpretation"
# ╔═╡ 1684bff0-7ad0-4921-be48-a4bfdcbde81d
md"The residual is $b-Ax$"
# ╔═╡ eeb922e4-2e63-4d97-88c8-3951613695f5
md"""
```math
A^T(b - Ax) = 0
```
"""
# ╔═╡ a5034aeb-e74e-47ed-9d0a-4eb3d076dfbe
md"## Solving Normal Equations with Cholesky decomposition"
# ╔═╡ bb097284-3e30-489c-abac-f0c6b71edfd9
md"""
Step 1: Rectangular → Square
```math
A^TAx = A^T b
```
Step 2: Square → Triangular
```math
A^T A = LL^T
```
Step 3: Solve the triangular linear equation
"""
# ╔═╡ 0f6b8814-77a1-4b1f-8183-42bc6ea412e0
md"## Issue: The Condition-Squaring Effect"
# ╔═╡ 04acb542-dc1f-4c45-b6fd-62f387a81963
md"The conditioning of a square linear system $Ax = b$ depends only on the matrix, while the conditioning of a least squares problem $Ax \approx b$ depends on both $A$ and $b$."
# ╔═╡ 080677b7-cac7-4bbe-a4b0-71e18ca41b1b
md"""
```math
A = \left(\begin{matrix}1 & 1\\ \epsilon & 0 \\ 0 & \epsilon \end{matrix}\right)
```
"""
# ╔═╡ 5933200f-5aab-4937-b3df-9af1f81a5eaf
md"The definition of thin matrix condition number"
# ╔═╡ 68d9c2b1-bccf-48ec-9428-e0c65a1618ad
md"""
## The algorithm matters
"""
# ╔═╡ 96f7d3c9-fecc-4b5e-94ff-e8e9af74ce63
md"$x^2 - 2px - q$"
# ╔═╡ cb7a0e40-0d26-4330-abd0-cd730261b6b4
md"""
Algorithm 1:
```math
p - \sqrt{p^2 + q}
```
Algorithm 2:
```math
\frac{q}{p+\sqrt{p^2+q}}
```
"""
# ╔═╡ b0c7ed86-2127-46a6-9f98-547cdf591d23
md"# Orthogonal Transformations"
# ╔═╡ b84c4a00-37ea-453a-b69d-555ffcd8b358
md"""
```math
A = QR
```
```math
Rx = Q^{T}b
```
"""
# ╔═╡ 7b48e6ea-6fb7-44b5-9407-1fb38bf4f009
md"""
## Gist of QR factoriaztion by Householder reflection.
"""
# ╔═╡ 64be680f-3a97-4b92-b3fd-9c7a27bccb01
md"""
Let $H_k$ be an orthogonal matrix, i.e. $H_k^T H_k = I$
```math
H_n \ldots H_2H_1 A = R
```
```math
Q = H_1^{T} H_2 ^{T}\ldots H_n^{T}
```
"""
# ╔═╡ 6d519ffa-ea7e-4a95-a50f-f9421651cd20
md"""
## Review of Elimentary Elimination Matrix
```math
M_k = I_n - \tau e_k^T
```
```math
\tau = \left(0, \ldots, 0, \tau_{k+1},\ldots,\tau_n\right)^T, ~~~ \tau_i = \frac{v_i}{v_k}.
```
Keys:
* Gaussian elimination is a recursive algorithm.
"""
# ╔═╡ a2832af2-c007-45d4-8fd7-210f85e3913e
md"""
## Householder reflection
Let $v \in \mathbb{R}^m$ be nonzero, An $m$-by-$m$ matrix $P$ of the form
```math
P = 1-\beta vv^T, ~~~\beta = \frac{2}{v^Tv}
```
is a Householder reflection.
"""
# ╔═╡ 2ee2e080-659d-4d85-9733-065efe6d4ce8
md"(the picture of householder reflection)"
# ╔═╡ 73bd9d1b-4890-48cf-8ecb-83dd6e8025ba
md"## Properties of Householder reflection"
# ╔═╡ 93c9f34c-ce1d-4940-8a24-1a5ce8aa7e01
md"Householder reflection is symmetric and orthogonal."
# ╔═╡ eb46cec9-5812-43aa-b192-2c84d5c5061e
md"## Project a vector to $e_1$"
# ╔═╡ d7c22484-3970-4c11-864c-a582d4034f7d
md"""
```math
P x = \beta e_1
```
```math
v = x \pm \|x\|_2 e_1
```
"""
# ╔═╡ f0dabeb6-2c30-4556-aeb8-03c51106f012
function householder_matrix(v::AbstractVector{T}) where T
v = copy(v)
v[1] -= norm(v, 2)
return HouseholderMatrix(v, 2/norm(v, 2)^2)
end
# ╔═╡ a20de17c-33ca-4807-918f-3a58d641ed69
let
A = Float64[1 2 2; 4 4 2; 4 6 4]
hm = householder_matrix(view(A,:,1))
hm * A
end
# ╔═╡ edecc73a-021f-4e0e-8d2e-dbafe537f0eb
md"## Triangular Least Squares Problems"
# ╔═╡ d9331fb3-8c04-4082-bdf5-0a1d09a65276
md"## QR Factoriaztion"
# ╔═╡ c10b85f2-be07-4fd4-a66c-50ac8e54fdb8
md"## Givens Rotations"
# ╔═╡ 2d41b937-1406-4db8-a453-f0d7ca042434
function draw_vectors(initial_vector, final_vector, angle)
@drawsvg begin
origin()
circle(0, 0, 100, :stroke)
setcolor("gray")
a, b = initial_vector
Luxor.arrow(Point(0, 0), Point(a, -b) * 100)
setcolor("black")
c, d = final_vector
Luxor.arrow(Point(0, 0), Point(c, -d) * 100)
Luxor.text("θ = $angle", 0, 50; valign=:center, halign=:center)
end 600 400
end
# ╔═╡ 51e387ff-1619-4c3f-8e52-748c0bddd9cf
@bind angle Slider(0:0.03:2*3.14; show_value=true)
# ╔═╡ 925d3781-a469-4943-b951-1688d705cb97
md"""
```math
G = \left(\begin{matrix}
\cos\theta & -\sin\theta\\
\sin\theta & \cos\theta
\end{matrix}\right)
```
"""
# ╔═╡ bef1e66b-bf43-4e05-a286-693626c61ea6
rotation_matrix(angle) = [cos(angle) -sin(angle); sin(angle) cos(angle)]
# ╔═╡ 874cbe3e-516e-4f8c-8ad8-e781a5d4af0d
let
initial_vector = [1.0, 0.0]
final_vector = rotation_matrix(angle) * initial_vector
@info final_vector
draw_vectors(initial_vector, final_vector, angle)
end
# ╔═╡ 50bfec97-0cf8-4a6e-a0e1-13ee391dce69
md"""
## Eliminating the $y$ element
"""
# ╔═╡ 7ae46225-cbbb-4595-adbc-7fd679bf965f
atan(0.1, 0.5)
# ╔═╡ 385a17c7-2394-492a-8e89-0f402311f5c4
let
initial_vector = randn(2)
angle = atan(initial_vector[2], initial_vector[1])
final_vector = rotation_matrix(-angle) * initial_vector
draw_vectors(initial_vector, final_vector, -angle)
end
# ╔═╡ 06627dd0-f22d-4fe5-8050-d0a84cac12fe
md"""
```math
\left(
\begin{matrix}
1 & 0 & 0 & 0 & 0\\
0 & c & 0 & s & 0\\
0 & 0 & 1 & 0 & 0\\
0 & -s & 0 & c & 0\\
0 & 0 & 0 & 0 & 1
\end{matrix}
\right)
\left(
\begin{matrix}
a_1\\a_2\\a_3\\a_4\\a_5
\end{matrix}
\right)=
\left(
\begin{matrix}
a_1\\\alpha\\a_3\\0\\a_5
\end{matrix}
\right)
```
where $s = \sin(\theta)$ and $c = \cos(\theta)$.
"""
# ╔═╡ 963cb350-b9b5-4dbe-8b5f-63ce38440e86
md"## Givens QR Factorization"
# ╔═╡ 5d40252a-4dc3-420d-bd8d-d11abdb07c9b
struct GivensMatrix{T} <: AbstractArray{T, 2}
c::T
s::T
i::Int
j::Int
n::Int
end
# ╔═╡ 64695822-e79c-4e34-912f-2179c674116d
Base.size(g::GivensMatrix) = (g.n, g.n)
# ╔═╡ 16ee76bf-3968-414b-aa0f-e82fbf3f7911
Base.size(g::GivensMatrix, i::Int) = i == 1 || i == 2 ? g.n : 1
# ╔═╡ d5812ce2-6333-4777-8016-7978af44a753
function elementary_elimination_matrix_1(A::AbstractMatrix{T}) where T
n = size(A, 1)
# create Elementary Elimination Matrices
M = Matrix{Float64}(I, n, n)
for i=2:n
M[i, 1] = -A[i, 1] ./ A[1, 1]
end
return M
end
# ╔═╡ 4e6a21ac-a27a-48a9-b714-6f66b24437c1
function lufact_naive_recur!(L, A::AbstractMatrix{T}) where T
n = size(A, 1)
if n == 1
return L, A
else
# eliminate the first column
m = elementary_elimination_matrix_1(A)
L .= L * inv(m)
A .= m * A
# recurse
lufact_naive_recur!(view(L, 2:n, 2:n), view(A, 2:n, 2:n))
end
return L, A
end
# ╔═╡ a10a2522-c4ea-4027-bbd3-3d0762341424
let
A = [1 2 2; 4 4 2; 4 6 4]
L = Matrix{Float64}(I, 3, 3)
R = copy(A)
lufact_naive_recur!(L, R)
L * R ≈ A
end
# ╔═╡ b2e92d06-8731-491c-adbe-ec9f778247c1
function givens(A, i, j)
x, y = A[i, 1], A[j, 1]
norm = sqrt(x^2 + y^2)
c = x/norm
s = y/norm
return GivensMatrix(c, s, i, j, size(A, 1))
end
# ╔═╡ d55be015-9a20-4efd-9be2-a5ecf9545400
function left_mul!(A::AbstractMatrix, givens::GivensMatrix)
for col in 1:size(A, 2)
vi, vj = A[givens.i, col], A[givens.j, col]
A[givens.i, col] = vi * givens.c + vj * givens.s
A[givens.j, col] = -vi * givens.s + vj * givens.c
end
return A
end
# ╔═╡ 92e842e9-42b8-45e6-937e-3d2049df9b09
function right_mul!(A::AbstractMatrix, givens::GivensMatrix)
for row in 1:size(A, 1)
vi, vj = A[row, givens.i], A[row, givens.j]
A[row, givens.i] = vi * givens.c + vj * givens.s
A[row, givens.j] = -vi * givens.s + vj * givens.c
end
return A
end
# ╔═╡ e6cd8de6-20c6-4d36-93ba-b1a9ed808fc2
function householder_qr!(Q::AbstractMatrix{T}, a::AbstractMatrix{T}) where T
m, n = size(a)
@assert size(Q, 2) == m
if m == 1
return Q, a
else
# apply householder matrix
H = householder_matrix(view(a, :, 1))
left_mul!(a, H)
# update Q matrix
right_mul!(Q, H')
# recurse
householder_qr!(view(Q, 1:m, 2:m), view(a, 2:m, 2:n))
end
return Q, a
end
# ╔═╡ 5ce1edef-5b0e-48ce-b269-855726cc5e15
@testset "householder QR" begin
A = randn(3, 3)
Q = Matrix{Float64}(I, 3, 3)
R = copy(A)
householder_qr!(Q, R)
@info R
@test Q * R ≈ A
@test Q' * Q ≈ I
end
# ╔═╡ 296749ef-7973-4ac9-8632-825fccbd3476
let
A = randn(3, 3)
g = givens(A, 2, 3)
left_mul!(copy(A), g)
end
# ╔═╡ f3c5297d-c371-41af-988b-595fb47ac4d7
function givens_qr!(Q::AbstractMatrix, A::AbstractMatrix)
m, n = size(A)
if m == 1
return Q, A
else
for k = m:-1:2
g = givens(A, k-1, k)
left_mul!(A, g)
right_mul!(Q, g)
end
givens_qr!(view(Q, :, 2:m), view(A, 2:m, 2:n))
return Q, A
end
end
# ╔═╡ bfca07d3-6479-4835-8b10-314facfcfea1
@testset "givens QR" begin
n = 3
A = randn(n, n)
R = copy(A)
Q, R = givens_qr!(Matrix{Float64}(I, n, n), R)
@test Q * R ≈ A
@test Q * Q' ≈ I
@info R
end
# ╔═╡ 0a753edc-4507-46e8-ab0f-fcdd5f3fa21f
md"## Gram-Schmidt Orthogonalization"
# ╔═╡ 8bcdaf5f-6e69-471e-9fca-063ece7f563a
md"""
```math
q_k = \left(a_k - \sum_{i=1}^{k-1} r_{ik}q_i\right)/r_{kk}
```
"""
# ╔═╡ e4a1cb08-1e6c-45b1-9937-12b13bba1645
md"## Algorithm: Classical Gram-Schmidt Orthogonalization"
# ╔═╡ c32925a7-28ca-4c23-9ab8-43db8e0dc0c3
function classical_gram_schmidt(A::AbstractMatrix{T}) where T
m, n = size(A)
Q = zeros(T, m, n)
R = zeros(T, n, n)
R[1, 1] = norm(view(A, :, 1))
Q[:, 1] .= view(A, :, 1) ./ R[1, 1]
for k = 2:n
Q[:, k] .= view(A, :, k)
# project z to span(A[:, 1:k-1])⊥
for j = 1:k-1
R[j, k] = view(Q, :, j)' * view(A, :, k)
Q[:, k] .-= view(Q, :, j) .* R[j, k]
end
# normalize the k-th column
R[k, k] = norm(view(Q, :, k))
Q[:, k] ./= R[k, k]
end
return Q, R
end
# ╔═╡ a7a4c219-d4dd-4491-90f9-824924124ff2
@testset "classical GS" begin
n = 10
A = randn(n, n)
Q, R = classical_gram_schmidt(A)
@test Q * R ≈ A
@test Q * Q' ≈ I
@info R
end
# ╔═╡ 21f0d7df-396e-47cc-beb8-0fa13fd8bc40
md"## Algorithm: Modified Gram-Schmidt Orthogonalization"
# ╔═╡ bd12051d-f8ad-4055-8461-b1495ca95ce6
function modified_gram_schmidt!(A::AbstractMatrix{T}) where T
m, n = size(A)
Q = zeros(T, m, n)
R = zeros(T, n, n)
for k = 1:n
R[k, k] = norm(view(A, :, k))
Q[:, k] .= view(A, :, k) ./ R[k, k]
for j = k+1:n
R[k, j] = view(Q, :, k)' * view(A, :, j)
A[:, j] .-= view(Q, :, k) .* R[k, j]
end
end
return Q, R
end
# ╔═╡ 8d4e7395-f05b-45dd-b762-da4cd1f40b29
@testset "modified GS" begin
n = 10
A = randn(n, n)
Q, R = modified_gram_schmidt!(copy(A))
@test Q * R ≈ A
@test Q * Q' ≈ I
@info R
end
# ╔═╡ cbab862d-f6f1-4238-b007-f1341455a85f
let
n = 100
A = randn(n, n)
Q1, R1 = classical_gram_schmidt(A)
Q2, R2 = modified_gram_schmidt!(copy(A))
@info norm(Q1' * Q1 - I)
@info norm(Q2' * Q2 - I)
end
# ╔═╡ c806e238-5f84-4cab-8e13-d9a15d4ee2b0
md"# Eigenvalue/Singular value decomposition problem"
# ╔═╡ 21d4d322-3af7-4ab2-90a4-b465f009167b
md"""
```math
Ax = \lambda x
```
"""
# ╔═╡ 36e59b38-07a5-43ea-9b73-599f6b78b938
md"## Power method"
# ╔═╡ e5998180-d4e9-4e9d-a965-b02d92c3a188
matsize = 10
# ╔═╡ 836f7624-e0b9-4ee3-9f11-a9b148af4266
A10 = randn(matsize, matsize); A10 += A10'
# ╔═╡ c84c3f0b-8b82-4710-bf27-7667506ef357
eigen(A10).values
# ╔═╡ deaaf582-3387-41b1-83ba-8290aa84236d
vmax = eigen(A10).vectors[:,end]
# ╔═╡ 1625ece0-5a1c-416f-b716-68c1f9f9478d
let
x = normalize!(randn(matsize))
for i=1:20
x = A10 * x
normalize!(x)
end
1-abs2(x' * vmax)
end
# ╔═╡ 5787c430-d48b-43b8-97e4-e95b1d66f578
md"""
## Rayleigh Quotient Iteration
"""
# ╔═╡ 0e874ac9-c3cb-4d65-8424-d425b6ff4748
let
x = normalize!(randn(matsize))
U = eigen(A10).vectors
for k=1:5
sigma = x' * A10 * x
y = (A10 - sigma * I) \ x
x = normalize!(y)
end
(x' * U)'
end
# ╔═╡ 537f7520-4e65-4d9f-8905-697d957f2772
md"## Symmetric QR decomposition"
# ╔═╡ ca22eba8-be14-40b1-b8fe-ead89b323952
function householder_trid!(Q, a)
m, n = size(a)
@assert m==n && size(Q, 2) == n
if m == 2
return Q, a
else
# apply householder matrix
H = householder_matrix(view(a, 2:n, 1))
left_mul!(view(a, 2:n, :), H)
right_mul!(view(a, :, 2:n), H')
# update Q matrix
right_mul!(view(Q, :, 2:n), H')
# recurse
householder_trid!(view(Q, :, 2:n), view(a, 2:m, 2:n))
end
return Q, a
end
# ╔═╡ a5c83d11-580e-4066-9bec-9ed8202e4e46
@testset "householder tridiagonal" begin
n = 5
a = randn(n, n)
a = a + a'
Q = Matrix{Float64}(I, n, n)
Q, T = householder_trid!(Q, copy(a))
@test Q * T * Q' ≈ a
end
# ╔═╡ d8fb96fb-bc78-4072-afe9-8427fac0f6ac
md"""## The SVD algorithm
```math
A = U S V^T
```
1. Form $C = A^T A$,
2. Use the symmetric QR algorithm to compute $V_1^T C V_1 = {\rm diag}(\sigma_i^2)$,
3. Apply QR with column pivoting to $AV_1$ obtaining $U^T(AV_1)\Pi = R$.
"""
# ╔═╡ ac65b656-8ab5-4866-b011-25711260f110
md"""
# Assignments
### 1. Review
Suppose that you are computing the QR factorization of the matrix
```math
A = \left(\begin{matrix}
1 & 1 & 1\\
1 & 2 & 4\\
1 & 3 & 9\\
1 & 4 & 16
\end{matrix}\right)
```
by Householder transformations.
* Problems:
1. How many Householder transformations are required?
2. What does the first column of A become as a result of applying the first Householder transformation?
3. What does the first column of A become as a result of applying the second Householder transformation?
4. How many Givens rotations would be required to computing the QR factoriazation of A?
### 2. Coding
Computing the QR decomposition of a symmetric triangular matrix with Givens rotation. Try to minimize the computing time and estimate the number of FLOPS.
For example, if the input matrix size is $T \in \mathbb{R}^{5\times 5}$
```math
T = \left(\begin{matrix}
t_{11} & t_{12} & 0 & 0 & 0\\
t_{21} & t_{22} & t_{23} & 0 & 0\\
0 & t_{32} & t_{33} & t_{34} & 0\\
0 & 0 & t_{43} & t_{44} & t_{45}\\
0 & 0 & 0 & t_{54} & t_{55}
\end{matrix}\right)
```
where $t_{ij} = t_{ji}$.
In your algorithm, you should first apply Givens rotation on row 1 and 2.
```math
G(t_{11}, t_{21}) T = \left(\begin{matrix}
t_{11}' & t_{12}' & t_{13}' & 0 & 0\\
0 & t_{22}' & t_{23}' & 0 & 0\\
0 & t_{32} & t_{33} & t_{34} & 0\\
0 & 0 & t_{43} & t_{44} & t_{45}\\
0 & 0 & 0 & t_{54} & t_{55}
\end{matrix}\right)
```
Then apply $G(t_{22}', t_{32})$ et al.
"""
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Luxor = "ae8d54c2-7ccd-5906-9d76-62fc9837b5bc"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[compat]
Luxor = "~3.7.0"
Plots = "~1.38.6"
PlutoUI = "~0.7.50"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.8.5"
manifest_format = "2.0"
project_hash = "f3ccd548493bd3f31c742b8b993a90fd0da8dd95"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.Cairo]]
deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"]
git-tree-sha1 = "d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b"
uuid = "159f3aea-2a34-519c-b102-8c37f9878175"
version = "1.0.5"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "c6d890a52d2c4d55d326439580c3b8d0875a77d9"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.15.7"
[[deps.ChangesOfVariables]]
deps = ["ChainRulesCore", "LinearAlgebra", "Test"]
git-tree-sha1 = "485193efd2176b88e6622a39a246f8c5b600e74e"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.6"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "9c209fb7536406834aa938fb149964b985de6c83"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.1"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Random", "SnoopPrecompile"]
git-tree-sha1 = "aa3edc8f8dea6cbfa176ee12f7c2fc82f0608ed3"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.20.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "600cc5508d66b78aae350f7accdb58763ac18589"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.10"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.Compat]]
deps = ["Dates", "LinearAlgebra", "UUIDs"]
git-tree-sha1 = "7a60c856b9fa189eb34f5f8a6f6b5529b7942957"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.6.1"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.1+0"
[[deps.Contour]]
git-tree-sha1 = "d05d9e7b7aedff4e5b51a029dced05cfb6125781"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.2"
[[deps.DataAPI]]
git-tree-sha1 = "e8119c1a33d267e16108be441a287a6981ba1630"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.14.0"
[[deps.DataStructures]]