-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0-julia-intro.jl
2951 lines (2423 loc) · 102 KB
/
0-julia-intro.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.26
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
# ╔═╡ 42b4beca-a43f-41de-8068-40caf8847b73
begin
using Plots
using PlutoUI
using PlutoTeachingTools
using PlutoTest
using ShortCodes
end
# ╔═╡ a81c1305-c953-43fd-8057-c7afbb25d6e6
begin
using BenchmarkTools
using LinearAlgebra
end
# ╔═╡ cb2c5fb1-4fd0-4a39-9243-646d7d8096d3
using QuantumEspresso_jll
# ╔═╡ 6719ddf8-ba5d-4694-9d47-c3106039fdc6
begin
using Libdl
using Printf
using CondaPkg
using PythonCall
CondaPkg.add("numpy")
const np = pyimport("numpy")
end;
# ╔═╡ 6340a213-17dc-4b8e-8848-8bc50aa620fa
begin
using IntervalArithmetic: interval
using Measurements
using DifferentialEquations
end
# ╔═╡ 01dd3582-349c-4613-9768-869d09168e4f
begin
using GenericLinearAlgebra
using SparseArrays
using CUDA
end
# ╔═╡ ba51d134-6ee7-4921-afaf-09094a6ac3ba
md"""
# A concise Julia introduction
"""
# ╔═╡ b3c5bc68-c92e-4e35-a94f-5b18163b2f8f
md"""
!!! danger "Presentation materials"
The content of this talk is also available as a static website on
[https://mfherbst.github.io/julia-for-materials/](https://mfherbst.github.io/julia-for-materials/),
as interactive Pluto notebooks on
[github.com/mfherbst/julia-for-materials](https://github.com/mfherbst/julia-for-materials)
and as a [youtube recording](https://www.youtube.com/watch?v=dujepKxxxkg).
"""
# ╔═╡ 3948dd91-dc26-4531-ba4d-2a8955add0b6
LocalResource("Logos.png")
# ╔═╡ de1fdecc-1752-4baa-b353-ae26519c4506
md"""Pluto notebooks install all packages and run all cells on startup. Since we do some benchmarks in here, this will likely take some time. Best grab a coffee ;)."""
# ╔═╡ 79995a06-14d4-44a8-89c1-5c66286d0e0a
TableOfContents()
# ╔═╡ c6271577-8ea0-487a-9cf4-116dc3c6d962
md"""
## About Julia
- In February 2022 Julia has [turned 10 years](https://julialang.org/blog/2022/02/10years/).
- Project started by Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman over the **frustration of the state of scientific software**:
> We are power Matlab users. Some of us are Lisp hackers. Some are Pythonistas, others Rubyists, still others Perl hackers. There are those of us who used Mathematica before we could grow facial hair. There are those who still can't grow facial hair. We've generated more R plots than any sane person should. C is our desert island programming language.
>
> We love all of these languages; they are wonderful and powerful. For the work we do — scientific computing, machine learning, data mining, large-scale linear algebra, distributed and parallel computing — each one is perfect for some aspects of the work and terrible for others. Each one is a trade-off.
>
> **We are greedy: we want more.**
[Why we created Julia](https://julialang.org/blog/2012/02/why-we-created-julia/) -- Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman
"""
# ╔═╡ 8b838733-2ec0-42f0-9dab-48bb24514173
md"""
- What is a **good scientific programming** language:
- Fast and scalable
- Interactive
- Easy to write and read
- Vanishing division between users and developers
- All existing languages feature various tradeoffs along these points:
- State of the art: Mix of programming languages (e.g. FORTRAN & Python)
- **Two language problem:**
- Where do you cut?
- When do you go from the prototyping language to the production language?
- Dealbreaker for iterative performance improvements
- Extra barrier for newcomers (learning one language is hard, now try two or more)
- **People compose if software composes**
"""
# ╔═╡ 6731e40b-4e51-46de-ae45-c9929b476059
md"""## Arrays and linear algebra
One of the striking features about Julia is the built-in support for arbitrary-dimensional arrays, linear algebra and the seamless and efficient integration with user code.
"""
# ╔═╡ 1501bc67-642a-48bc-b355-e6513d379682
α = [1, 2, 3]
# ╔═╡ 049f14d5-18e3-4493-b618-03a42fffe35d
β = randn(3)
# ╔═╡ dd7d5b1c-1658-4fd7-aa83-2723c7043862
α + 2β # Just add
# ╔═╡ 6866b606-76ed-44e3-87d8-62e4c3bc9a01
α .* β # vectorised operations
# ╔═╡ dfc8d867-ce37-41a0-b5c2-2bc44adac8e9
md"So far so obvious, but we can also apply custom functions in a vectorised way:"
# ╔═╡ 724e0d7b-1445-4772-ae3e-673f4122f740
myfun(x) = x^2 + 2
# ╔═╡ 9e83f0e2-322d-4500-bf74-88603ef00b33
myfun.(cos.(α))
# ╔═╡ d647f360-c00c-4970-b735-954b76d7f584
md"**Loops are actually fast:**"
# ╔═╡ bdd7caff-3b42-4487-a89f-33638ff4059f
function myadd!(C, A, B)
for i in eachindex(A, B)
C[i] = A[i] + B[i]
end
end
# ╔═╡ 734c3156-a510-4116-b129-67532dfb70c1
let
n = 100
A = rand(n, n)
B = rand(n, n)
C = zeros(n, n)
@btime $C .= $A .+ $B
@btime myadd!($C, $A, $B)
end;
# ╔═╡ 995e081d-d74c-44db-8d02-e55bb69b44cc
md"**Standard linear algebra** is just available, e.g. transposition, diagonalisation:"
# ╔═╡ d9e3a5bc-6665-4b37-99f9-a1c4e5607a9b
begin
C = randn(3, 3)
C = C + C'
end
# ╔═╡ 6972cc50-ab7a-4d2a-84b7-aa5231762061
eigen(C)
# ╔═╡ 1d2eae8d-2bb9-4756-894a-5511ed67049d
md"But crucially we have many variants, that (depending on the type) automatically do the right thing:"
# ╔═╡ 5e24f293-b814-40f9-afcd-597230909e28
eigen(Symmetric(C))
# ╔═╡ 9c72c38a-37d7-42a8-8b8a-8d1488c7f332
eigen(Diagonal([1., 2., 3.]))
# ╔═╡ 03b972e2-bf97-49d8-8839-389e335097f6
@which eigen(C)
# ╔═╡ 513beaeb-af44-42a8-827f-a8dafa486b03
@which eigen(Symmetric(C))
# ╔═╡ 88bb95eb-1112-4455-8483-094ba7f1d5be
length(methods(eigen))
# ╔═╡ 23b99435-30df-4c1d-8375-00377f694810
md"""## Reactive notebooks"""
# ╔═╡ c54bb3ca-1ce9-44a2-9fe4-42dac9ad2a01
md"Interactivity is easy ..."
# ╔═╡ 29fa6317-a637-47c4-97cd-b1494ba21517
@bind ω PlutoUI.Slider(1:0.1:10; show_value=true, default=2.3)
# ╔═╡ 12ade949-c5a5-4bff-a1e7-b7a7e191c52a
let
t = collect(0:0.01:2π)
Plots.plot(sin.(ω .* t); label=nothing)
end
# ╔═╡ edc6bc46-4bfa-4052-83b8-57e8682c10ae
md"Debug step by step ..."
# ╔═╡ 1d113418-bc56-4bc0-bd28-30b888462cf6
@test 2 + (2^2) in [i ÷ 2 for i in 10:20]
# ╔═╡ f2f2196b-28d1-4f5f-92f1-7e082a2acd72
md"""## Excellent package management"""
# ╔═╡ c4781847-cb21-4ce4-b4fc-305492fd9143
Resource("https://imgs.xkcd.com/comics/python_environment.png")
# ╔═╡ 602b0f1c-bc9a-40c7-88f7-f443af42913a
md"""
- The package manager comes with the language
- Creates reproducible environments
- Handles dependencies and versions properly
- Unit testing and documentation easy to set up
- Includes management of **3rd party binary dependencies**
- E.g. we can just
"""
# ╔═╡ 0e53bfaa-e7d1-4452-8d47-896224eecccf
QuantumEspresso_jll.pwscf() do pwscf
withenv("ESPRESSO_PSEUDO" => joinpath(@__DIR__, "pseudos")) do
@time run(`$pwscf -in Fe_afm.pwi`)
end
end
# ╔═╡ 1b9e45b3-e2b3-43c2-9795-839c6156d975
md"""
## Seamless combination with existing codes
- Combining **C and Julia** works both ways (see examples above & below)
* Note: This includes package management
- Same is true for **Python and Julia**
* Again includes package management, see [**PythonCall**](https://cjdoris.github.io/PythonCall.jl/stable/), [**CondaPkg**](https://github.com/cjdoris/CondaPkg.jl) and [**JuliaCall**](https://cjdoris.github.io/PythonCall.jl/stable/) for details.
- Other supported languages include R and Java.
"""
# ╔═╡ 676aa47c-c36d-46f5-bc44-50a34303b3e7
md"""
## Julia's speed: Sums
"""
# ╔═╡ 3ecca9bd-bc70-460a-a795-28c4a6275ab9
md"""
Now, we would like to answer the question: *is Julia fast?*
But to some extent this is a misleading question, since one can write slow code in any language... so let's try to answer something else instead: *can Julia be fast?*
Our example will be to sum up the entries in a vector. Written in plain Julia just like:
"""
# ╔═╡ 5753e3a3-2499-4b9c-9c69-a6d400ea64db
function mysum(v)
result = zero(eltype(v))
for i in 1:length(v)
result += v[i]
end
result
end
# ╔═╡ cba77bab-1d67-4557-8b95-9466f0be59ba
begin
vlarge = randn(10^7) # Large vector of numbers
times = Dict() # Collection for timings
end;
# ╔═╡ 2d1e09dd-0348-4ac8-a663-0b799ec38162
md"""
First we do it in **plain C**.
"""
# ╔═╡ b0813754-1a15-4c46-993e-8882b9814a7d
begin
# Compile some C code and call it from julia ...
code = """
#include <stddef.h>
double c_sum(size_t n, double *v) {
double accu = 0.0;
for (size_t i = 0; i < n; ++i) {
accu += v[i];
}
return accu;
}
"""
# Compile to a shared library (with fast maths and machine-specific)
const Clib = tempname()
open(`gcc -fPIC -O3 -march=native -xc -shared -ffast-math -o $(Clib * "." * Libdl.dlext) -`, "w") do f
print(f, code)
end
# define a Julia function that calls the C function:
c_sum(v::Array{Float64}) = ccall(("c_sum", Clib), Float64, (Csize_t, Ptr{Float64}), length(v), v)
end
# ╔═╡ 0d935958-7f45-49ba-b630-0334b027a0c1
let
bench = @benchmark c_sum($vlarge)
times["C (naive)"] = minimum(bench.times) / 1e6
bench
end
# ╔═╡ 8c6804cf-5b9a-4793-8f2d-fdf35ad720ee
md"""
Now we try an explicitly and **fully vectorised C code**:
"""
# ╔═╡ 86c21556-ff39-4a2d-a5c6-251d74e60c5d
begin
code_vectorised = """
#include <stddef.h>
#include <immintrin.h>
double c_sum_vector(size_t n, double *v)
{
size_t i;
double result;
double tmp[4] __attribute__ ((aligned(64)));
__m256d sums1 = _mm256_setzero_pd();
__m256d sums2 = _mm256_setzero_pd();
for ( i = 0; i + 7 < n; i += 8 )
{
sums1 = _mm256_add_pd( sums1, _mm256_loadu_pd(v+i ) );
sums2 = _mm256_add_pd( sums2, _mm256_loadu_pd(v+i+4) );
}
_mm256_store_pd( tmp, _mm256_add_pd(sums1, sums2) );
return tmp[0] + tmp[1] + tmp[2] + tmp[3];
}
"""
# Compile to a shared library (with fast maths and machine-specific)
const Clib_vectorised = tempname()
open(`gcc -fPIC -O2 -march=native -xc -shared -ffast-math -o $(Clib_vectorised * "." * Libdl.dlext) -`, "w") do f
print(f, code_vectorised)
end
# define a Julia function that calls the C function:
c_sum_vectorised(v::Array{Float64}) = ccall(("c_sum_vector", Clib_vectorised), Float64, (Csize_t, Ptr{Float64}), length(v), v)
end
# ╔═╡ acff670e-5011-4212-8f52-95c1b5477d5d
let
bench = @benchmark c_sum_vectorised($vlarge)
times["C (vectorised)"] = minimum(bench.times) / 1e6
bench
end
# ╔═╡ 9b1329aa-4197-4949-bbb9-42a2275c7c2b
md"""
So how does the **Julia version** do?
"""
# ╔═╡ a86eb565-ff94-440f-8ef7-632a9dcd6c82
let
bench = @benchmark mysum($vlarge)
times["Julia (naive)"] = minimum(bench.times) / 1e6
bench
end
# ╔═╡ 51e1c815-bc3b-4373-a236-c3e7df5d46de
md"""
A bit disappointing... but unlike vectorised C we have not yet tried all tricks! Let's try an **optimised Julia version**.
"""
# ╔═╡ 36d82a73-b463-421f-aac3-7e2ce6905563
function fastsum(v)
result = zero(eltype(v))
@simd for i in 1:length(v) # @simd => instruction vectorisation in the loop
@inbounds result += v[i] # @inbounds => suppresses bound checks
end
result
end;
# ╔═╡ eef56f3f-4a45-4e03-a173-9dcaa605ab75
let
bench = @benchmark fastsum($vlarge)
times["Julia (simd)"] = minimum(bench.times) / 1e6
bench
end
# ╔═╡ 8c347867-f139-4c3a-b454-29d34f0a1be2
md"""
Notice, how this is still nicely readable code!
"""
# ╔═╡ b4245307-e080-4923-b540-b9b3288cfae4
md"""
So ... how does **python** perform in this comparison ?
"""
# ╔═╡ 449130fa-6a73-42a7-93b9-9adbca17e37e
let
bench = @benchmark ($(np.sum))($vlarge)
times["Python (numpy)"] = minimum(bench.times) / 1e6
bench
end
# ╔═╡ f0fdd605-6f29-4f5b-b9bd-d03554273854
md"""
But numpy is not real Python, **that's C in disguise**.
The naive version (like the one we wrote in Julia) would look something like this:
"""
# ╔═╡ 69806ad3-ce38-4d4f-984d-5985cfbb408e
begin
pycode = """def pysum(A):
s = 0.0
for a in A:
s += a
return s
"""
pyexec(strip(pycode), Main)
pysum(v) = pyeval("pysum(v)", Main, (; v))
end
# ╔═╡ 2f095034-9e3d-4f27-97f4-96cbeadbe681
let
bench = @benchmark ($pysum)($vlarge)
times["Python (naive)"] = minimum(bench.times) / 1e6
bench
end
# ╔═╡ 0f6c85be-7d32-4e0c-b085-a04227570a46
md"""
In summary:
"""
# ╔═╡ b6a35fc7-c2f9-4d39-baf8-10d8a94996d6
let
for k in sort(collect(keys(times)))
@printf "% 15s => %9.2f ms\n" k times[k]
end
end
# ╔═╡ 74b4e0e0-bae5-48e0-9746-f77a70988015
md"**Conclusion:** Julia is on the same speed level as C."
# ╔═╡ 8c4d9da1-62ca-4d57-9583-59341ab06d52
md"""
## Composable software from generic code
We just produced the following sum function, which was basically en par in speed with C or numpy:
```julia
function fastsum(v)
result = zero(eltype(v))
@simd for i in 1:length(v) # @simd => instruction vectorisation in the loop
@inbounds result += v[i] # @inbounds => suppresses bound checks
end
result
end
```
But unlike a C implementation, we are not at all restricted to using a particular data type ... and this let's us do crazy things **even though the code is equally fast**:
"""
# ╔═╡ e2d26a9d-be50-49d9-870f-d709cccadcbb
md"""
(a) **Elevated precision** ... let's consider a nasty case:
Some numbers designed to **sum to 1**:
"""
# ╔═╡ af10e42c-bd61-4acd-ba80-0798c3fbbd3b
function generate(N)
x = randn(N) .* exp.(10 .* randn(N))
x = [x; -x; 1.0]
x[sortperm(rand(length(x)))]
end
# ╔═╡ 72ec7c6a-5189-446f-b00e-b15761a205db
numbers = generate(10000);
# ╔═╡ 31a31c46-56a8-4f94-b19e-54d3ba9a319e
fastsum(numbers)
# ╔═╡ e6b5f14c-d254-4515-aed2-5a37e391e4bc
md"""... looks wrong, let's try elevated precision:"""
# ╔═╡ 8db81000-c957-4765-b3af-fa7408964b88
fastsum(big.(numbers))
# ╔═╡ 43ad5619-9b7a-4b61-bb46-b2d484c58ddd
md"""(b) **Tracking numerical error**"""
# ╔═╡ f126ecce-d639-4971-873b-aa0f99fd71c8
begin
fastsum(interval.(numbers))
end
# ╔═╡ b972089c-0990-4917-89b9-5ad790bcdbb9
md"""... ups clearly something wrong here! But now we know."""
# ╔═╡ 2a3dfa03-f4bd-47bf-b70e-5cd00e8402a5
md"""(c) **Error propagation**"""
# ╔═╡ 41b6c787-32f1-42a6-9dab-58fd23a5df7e
begin
vmeas = [1 ± 1e-10, 1.1 ± 1e-12, 1.2 ± 1e-10]
fastsum(vmeas)
end
# ╔═╡ 96e78c8e-7f85-4e16-9865-70fea98cfe6c
md"""
(d) **Unlocking new features**
Let us solve:
$$\frac{du(t)}{dt} = -cu(t)$$
"""
# ╔═╡ 0443c94a-0822-4b5d-9bc3-42371d2c6454
md"Use measurement error: $(@bind use_measurement_error CheckBox())"
# ╔═╡ ccd03c3a-82b9-430b-b818-58794efb4710
if use_measurement_error
c = 5.730 ± 2 # Half-life of Carbon-14 is 5730 years.
u0 = 1.0 ± 0.1
else
c = 5.730
u0 = 1.0
end;
# ╔═╡ 30cbc826-cece-4fcf-871b-eae7bbe8838f
md"""Selected:
- **`use_measurement_error` = $use_measurement_error**
- half-life is **c = $c**
- initial population is **u0 = $u0**.
"""
# ╔═╡ a99231cd-0e8b-48ee-be0e-0613933afe7f
begin
# Define the problem
radioactivedecay(u, p, t) = -c*u
# Pass to solver
tspan = (0.0, 1.0)
prob = ODEProblem(radioactivedecay, u0, tspan)
sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8);
plot(sol.t, sol.u, ylabel="u(t)", xlabel="t", lw=2, legend=false)
end
# ╔═╡ 9d639f9d-9396-4db3-9c14-45ace90883aa
md"""Now what if we have **measurement errors?** Just tick the box above and see ..."""
# ╔═╡ 3f3566f9-ec2b-4aa2-9e7e-3f61e37af8d6
md"""
Note that, in some sense, **Julia implemented that feature by itself**.
The authors of Measurements.jl and DifferentialEquations.jl never had any collaboration on this.
It **just works**.
"""
# ╔═╡ 90a6efec-b2f0-4220-8927-c5810f80e0f0
md"**Conclusion:** Julia's language design gives enormous flexibility with little effort."
# ╔═╡ 5665c6e6-68de-4811-bcf2-695710362421
md"""## Powerful HPC abstractions"""
# ╔═╡ 896e240a-ad02-42f3-a76e-a9615df1f2e4
LocalResource("julia_hpc.png")
# ╔═╡ 2b4baa3b-403b-4430-91fc-8abc4ece1693
md"""We consider the simple Davidson algorithm (iterative eigensolver), which can be implemented quite concisely:"""
# ╔═╡ 30f46bb0-e248-471d-b413-578d2b3c62d2
qrortho(X::AT) where {AT <: AbstractArray} = AT(qr(X).Q)
# ╔═╡ b849f68d-1d2d-4ddf-bf4a-d5c62697e37b
function rayleigh_ritz(X, AX, N)
F = eigen(Hermitian(X' * AX))
F.values[1:N], F.vectors[:, 1:N]
end
# ╔═╡ fabc2507-2ef2-4bc5-974f-fa542cbdac03
function davidson(A, SS::AbstractArray; tol=1e-5, maxsubspace=8size(SS, 2), verbose=true)
m = size(SS, 2)
for i in 1:100
Ass = A * SS
rvals, rvecs = rayleigh_ritz(SS, Ass, m)
Ax = Ass * rvecs
R = Ax - SS * rvecs * Diagonal(rvals)
if norm(R) < tol
return rvals, SS * rvecs
end
verbose && println(i, " ", size(SS, 2), " ", norm(R))
# Use QR to orthogonalise the subspace.
if size(SS, 2) + m > maxsubspace
SS = qrortho([SS*rvecs R])
else
SS = qrortho([SS R])
end
end
error("not converged.")
end
# ╔═╡ 2be08ff3-d1ef-4acd-a6b0-849f83d06c28
begin
nev = 2
A = randn(50, 50)
A = A + A' + 5I
end;
# ╔═╡ fc5adbc2-95bb-4fee-be6b-5e6f94b7a411
begin
# Generate two random orthogonal guess vectors
x0 = qrortho(randn(size(A, 2), nev))
# Run the problem
davidson(A, x0)
end
# ╔═╡ e39eb6f7-87dc-4aad-8d61-48ec57be76cb
begin
# Mixed precision!
λ, v = davidson(Matrix{Float32}(A), Float32.(x0), tol=1e-3)
println()
λ, v = davidson(Matrix{Float64}(A), v, tol=1e-13)
println()
λ, v = davidson(Matrix{BigFloat}(A), v, tol=1e-20)
λ
end
# ╔═╡ bf9071d7-5e02-4b6d-8a4c-832186a27d4d
begin
spA = sprandn(100, 100, 0.2)
spA = spA + spA' + 10I
spA
end
# ╔═╡ 84ee7a04-16fc-420f-b64d-4598254a0dd3
begin
spx0 = randn(size(spA, 2), nev)
spx0 = Array(qr(spx0).Q)
davidson(spA, spx0, tol=1e-4)
end
# ╔═╡ 5d167ac0-0387-4189-828d-5a01b7bf11c9
md"""Let's run with GPUs:"""
# ╔═╡ da419772-c2d1-483f-b31a-a9839f607570
if CUDA.has_cuda_gpu()
davidson(CuArray(A), CuArray(x0))
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
CondaPkg = "992eb4ea-22a4-4c89-a5bb-47a3300528ab"
DifferentialEquations = "0c46a032-eb83-5123-abaf-570d42b7fbaa"
GenericLinearAlgebra = "14197337-ba66-59df-a3e3-ca00e7dcff7a"
IntervalArithmetic = "d1acc4aa-44c8-5952-acd4-ba5d80a2a253"
Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoTeachingTools = "661c6b06-c737-4d37-b85c-46df65de6f69"
PlutoTest = "cb4044da-4d16-4ffa-a6a3-8cad7f73ebdc"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d"
QuantumEspresso_jll = "74603b90-2fcf-5710-a7d7-830b31b8b33c"
ShortCodes = "f62ebe17-55c5-4640-972f-b59c0dd11ccf"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[compat]
BenchmarkTools = "~1.3.2"
CUDA = "~4.2.0"
CondaPkg = "~0.2.18"
DifferentialEquations = "~7.7.0"
GenericLinearAlgebra = "~0.3.10"
IntervalArithmetic = "~0.20.8"
Measurements = "~2.9.0"
Plots = "~1.38.12"
PlutoTeachingTools = "~0.2.11"
PlutoTest = "~0.2.2"
PlutoUI = "~0.7.51"
PythonCall = "~0.9.13"
QuantumEspresso_jll = "~7.0.1"
ShortCodes = "~0.3.5"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.9.0"
manifest_format = "2.0"
project_hash = "e348ded55e38dbebbfc283252ab619fcca659915"
[[deps.ADTypes]]
git-tree-sha1 = "dcfdf328328f2645531c4ddebf841228aef74130"
uuid = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
version = "0.1.3"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "16b6dbc4cf7caee4e1e75c49485ec67b667098a0"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.3.1"
weakdeps = ["ChainRulesCore"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "76289dc51920fdc6e0013c872ba9551d54961c24"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.6.2"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.ArnoldiMethod]]
deps = ["LinearAlgebra", "Random", "StaticArrays"]
git-tree-sha1 = "62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae"
uuid = "ec485272-7323-5ecc-a04f-4719b315124d"
version = "0.2.0"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra", "Requires", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "917286faa2abb288796e75b88ca67edc016f3219"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.4.5"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.ArrayInterfaceCore]]
deps = ["LinearAlgebra", "SnoopPrecompile", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "e5f08b5689b1aad068e01751889f2f615c7db36d"
uuid = "30b0a656-2188-435a-8636-2ec0e6a096e2"
version = "0.1.29"
[[deps.ArrayLayouts]]
deps = ["FillArrays", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "4aff5fa660eb95c2e0deb6bcdabe4d9a96bc4667"
uuid = "4c555306-a7a7-4459-81d9-ec55ddd5c99a"
version = "0.8.18"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Atomix]]
deps = ["UnsafeAtomics"]
git-tree-sha1 = "c06a868224ecba914baa6942988e2f2aade419be"
uuid = "a9b6321e-bd34-4604-b9c9-b65b8de01458"
version = "0.1.0"
[[deps.BFloat16s]]
deps = ["LinearAlgebra", "Printf", "Random", "Test"]
git-tree-sha1 = "dbf84058d0a8cbbadee18d25cf606934b22d7c66"
uuid = "ab4f0b2a-ad5b-11e8-123f-65d77653426b"
version = "0.4.2"
[[deps.BandedMatrices]]
deps = ["ArrayLayouts", "FillArrays", "LinearAlgebra", "SnoopPrecompile", "SparseArrays"]
git-tree-sha1 = "6ef8fc1d77b60f41041d59ce61ef9eb41ed97a83"
uuid = "aae01518-5342-5314-be14-df237901396f"
version = "0.17.18"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "d9a9701b899b30332bbcb3e1679c41cce81fb0e8"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.3.2"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.BitTwiddlingConvenienceFunctions]]
deps = ["Static"]
git-tree-sha1 = "0c5f81f47bbbcf4aea7b2959135713459170798b"
uuid = "62783981-4cbd-42fc-bca8-16325de8dc4b"
version = "0.1.5"
[[deps.BoundaryValueDiffEq]]
deps = ["BandedMatrices", "DiffEqBase", "FiniteDiff", "ForwardDiff", "LinearAlgebra", "NLsolve", "Reexport", "SciMLBase", "SparseArrays"]
git-tree-sha1 = "ed8e837bfb3d1e3157022c9636ec1c722b637318"
uuid = "764a87c0-6b3e-53db-9096-fe964310641d"
version = "2.11.0"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.CEnum]]
git-tree-sha1 = "eb4cb44a499229b3b8426dcfb5dd85333951ff90"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.4.2"
[[deps.CPUSummary]]
deps = ["CpuId", "IfElse", "Static"]
git-tree-sha1 = "2c144ddb46b552f72d7eafe7cc2f50746e41ea21"
uuid = "2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9"
version = "0.2.2"
[[deps.CRlibm]]
deps = ["CRlibm_jll"]
git-tree-sha1 = "32abd86e3c2025db5172aa182b982debed519834"
uuid = "96374032-68de-5a5b-8d9e-752f78720389"
version = "1.0.1"
[[deps.CRlibm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e329286945d0cfc04456972ea732551869af1cfc"
uuid = "4e9b3aee-d8a1-5a3d-ad8b-7d824db253f0"
version = "1.0.1+0"
[[deps.CUDA]]
deps = ["AbstractFFTs", "Adapt", "BFloat16s", "CEnum", "CUDA_Driver_jll", "CUDA_Runtime_Discovery", "CUDA_Runtime_jll", "CompilerSupportLibraries_jll", "ExprTools", "GPUArrays", "GPUCompiler", "KernelAbstractions", "LLVM", "LazyArtifacts", "Libdl", "LinearAlgebra", "Logging", "Preferences", "Printf", "Random", "Random123", "RandomNumbers", "Reexport", "Requires", "SparseArrays", "SpecialFunctions", "UnsafeAtomicsLLVM"]
git-tree-sha1 = "280893f920654ebfaaaa1999fbd975689051f890"
uuid = "052768ef-5323-5732-b1bb-66c8b64840ba"
version = "4.2.0"
[[deps.CUDA_Driver_jll]]
deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"]
git-tree-sha1 = "498f45593f6ddc0adff64a9310bb6710e851781b"
uuid = "4ee394cb-3365-5eb0-8335-949819d2adfc"
version = "0.5.0+1"
[[deps.CUDA_Runtime_Discovery]]
deps = ["Libdl"]
git-tree-sha1 = "bcc4a23cbbd99c8535a5318455dcf0f2546ec536"
uuid = "1af6417a-86b4-443c-805f-a4643ffb695f"
version = "0.2.2"
[[deps.CUDA_Runtime_jll]]
deps = ["Artifacts", "CUDA_Driver_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"]
git-tree-sha1 = "5248d9c45712e51e27ba9b30eebec65658c6ce29"
uuid = "76a88914-d11a-5bdc-97e0-2f5a05c973a2"
version = "0.6.0+0"
[[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.Calculus]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad"
uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9"
version = "0.5.1"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "e30f2f4e20f7f186dc36529910beaedc60cfa644"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.16.0"
[[deps.CloseOpenIntervals]]
deps = ["Static", "StaticArrayInterface"]
git-tree-sha1 = "70232f82ffaab9dc52585e0dd043b5e0c6b714f1"
uuid = "fb6a15b2-703c-40df-9091-08a04967cfa9"
version = "0.1.12"
[[deps.CodeTracking]]
deps = ["InteractiveUtils", "UUIDs"]
git-tree-sha1 = "d730914ef30a06732bdd9f763f6cc32e92ffbff1"
uuid = "da1fd8a2-8d9e-5ec2-8556-3022fb5608a2"
version = "1.3.1"
[[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", "PrecompileTools", "Random"]
git-tree-sha1 = "be6ab11021cd29f0344d5c4357b163af05a48cba"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.21.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.CommonSolve]]
git-tree-sha1 = "9441451ee712d1aec22edad62db1a9af3dc8d852"
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
version = "0.2.3"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["UUIDs"]
git-tree-sha1 = "7a60c856b9fa189eb34f5f8a6f6b5529b7942957"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.6.1"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.2+0"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "96d823b94ba8d187a6d8f0826e731195a74b90e9"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.2.0"
[[deps.CondaPkg]]
deps = ["JSON3", "Markdown", "MicroMamba", "Pidfile", "Pkg", "TOML"]
git-tree-sha1 = "741146cf2ced5859faae76a84b541aa9af1a78bb"
uuid = "992eb4ea-22a4-4c89-a5bb-47a3300528ab"
version = "0.2.18"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "738fec4d684a9a6ee9598a8bfee305b26831f28c"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.2"
[deps.ConstructionBase.extensions]