-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGWU-Data-Analysis-2023-02-03.jl
More file actions
1800 lines (1364 loc) · 55.2 KB
/
Copy pathGWU-Data-Analysis-2023-02-03.jl
File metadata and controls
1800 lines (1364 loc) · 55.2 KB
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
# ╔═╡ 97339d68-a310-11ed-0c4c-7dd426dd4301
using PlutoUI; PlutoUI.TableOfContents()
# ╔═╡ 93a598ab-b722-40f0-bd58-f536c9bf859e
using Measurements
# ╔═╡ e87a112b-8743-4c7c-950d-c9b19a2f2dab
using Unitful
# ╔═╡ 54dca801-a079-4e79-a9f2-677b7067fd22
using PythonCall
# ╔═╡ 8fed09a1-9575-497e-859a-5d39158af649
using BenchmarkTools
# ╔═╡ 367d07de-ec8e-4c75-ad6a-c37fc5477094
# ╔═╡ 62aed81e-12d5-4b91-9a9e-f8866af1e3d7
md"""
## Running Julia
"""
# ╔═╡ dd8ca693-30e4-4d5e-9927-608b86162230
md"""
**===================================================================================**
### Starting Julia
Enter `julia` at the terminal prompt. Set the number of threads to `auto`. Threads will be discussed later in Parallel Computing.
> julia --threads=auto
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.7.3 (2022-05-06)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
julia>
!!! tip
The command line option "-q" can be used to remove the start-up banner.
"""
# ╔═╡ 72dbc6c2-22e9-485f-ae40-1ff008cee3b3
md"""
**===================================================================================**
### Stopping Julia
To exit Julia, enter `<Ctl-D>` or `exit()`
```julia
julia> <Ctl-D>
```
!!! tip
Don't do this now!
"""
# ╔═╡ 5d2679d7-fd7c-4ee2-a83e-3120f8df286e
md"""
**===================================================================================**
### The command line or REPL (Read-Eval-Print-Loop)
Our first command:
```julia
println("Hello World")
```
"""
# ╔═╡ 700513c1-f8eb-46da-b0e3-10e4a888afd6
println("Hello World")
# ╔═╡ d0f131ef-555b-4dee-a591-617ce36395d5
md"""
!!! note
Unlike Jupyter and the REPL, Pluto prints the result above the line, not below.
Our first calculation
```julia
a = 4
```
"""
# ╔═╡ 1ae81446-759e-4a52-b51e-2f7cc96f5472
a = 4
# ╔═╡ 33e3d1b2-851b-47cc-855c-0eda2be59cb1
md"""
```julia
b = 2
```
"""
# ╔═╡ e7f21345-6f45-44c8-801a-140b680ca676
b = 2
# ╔═╡ 9aeaff07-9997-4b7d-92ba-a9005158bb5f
md"""
```julia
a + b
```
"""
# ╔═╡ 412e3233-f7c1-4e4a-a2af-198fd2ade430
a + b
# ╔═╡ 22fe494f-af4a-4d67-8d47-81292ac4e56e
md"""
**===================================================================================**
### Other REPL Modes
#### Help, '?'
For help mode,
julia> ?
help?> println
search: println printstyled print sprint isprint
println([io::IO], xs...)
Print (using print) xs to io followed by a newline. If io is not supplied, prints to the default output stream stdout.
See also printstyled to add colors etc
Examples
≡≡≡≡≡≡≡≡≡≡
julia> println("Hello, world")
Hello, world
julia> io = IOBuffer();
julia> println(io, "Hello", ',', " world.")
julia> String(take!(io))
"Hello, world.\n"
Enter 'delete' or 'backspace' to exit help
"""
# ╔═╡ 00e8c94b-6fcf-41aa-8aa9-338b4a14aeb5
# ╔═╡ 3748c949-e09b-4cf1-9dbf-1154a871d671
md"""
#### Shell, ';'
For shell mode,
```julia
julia> ;
shell> pwd
/Users/myhomedir
```
Enter 'delete' or 'backspace' to exit shell
"""
# ╔═╡ 0a9bf528-912d-4782-928c-5107bd3ac0ba
; ls
# ╔═╡ ffd301ba-9af1-4e64-a8bf-cd7dcceaede8
md"""
## Package Manager, `]`
```julia
julia> ]
pkg>
```
For package manager help,
```julia
pkg> ? `return`
```
Returns a brief summary of package commands
To add a package,
```julia
pkg> add <package>
pkg> add <package1>, <package2>
```
When adding a package, the Julia on-line repository will be searched. The package and its dependencies will then be downloaded, compiled, and installed. This may take anywhere from a few seconds to a few minutes depending on the size of the package and its dependencies.
To use or load a package (after it has been added),
```julia
using <package>
using <package1>, <package2>
```
A feature of the 'using' command is that it will add the package, if it hasn't alaredy been added.
The Measurements package enables variables to have both values and errors.
Let's add the Measurements package using the `using` statement.
"""
# ╔═╡ 6af4d494-cf25-4acc-ba93-37afa65ccd69
md"""
To check the manifest:
```julia
pkg> status
```
or
```julia
pkg> st
```
"""
# ╔═╡ 2a688d2c-d4a9-4018-947d-8547acedd11c
md"""
To update a package in the manifest:
```julia
pkg> update <package>
```
or
```julia
pkg> up <package>
```
To update all packages in the manifest,
```julia
pkg> up
```
To garbage collect packages not used for a significant time,
```julia
pkg> gc
```
**===================================================================================**
## Composability
Let's do some more calculations.
```julia
m1 = measurement(4.5, 0.1)
```
"""
# ╔═╡ 0a4f1f80-521b-421d-844d-3f4e8c071db4
m1 = measurement(4.5, 0.1)
# ╔═╡ 40b0c3a6-7091-49dd-bc45-394af1fe933d
md"""Typing 'measurements' is rather awkward. There must be a better way. How about the following?
```julia
m2 = 15 ± 0.3
```
where the plus-minus character is entered using LaTex syntax followed by tab, i.e., \pm<tab>.
"""
# ╔═╡ 79f16ae3-d4df-4fe3-ab56-fcfe340b7e7c
m2 = 15 ± 0.3
# ╔═╡ 6c7faa97-1f9f-4604-90cd-94a0bef55ce4
md"""
One of the features of Julia is that it understands unicode. For example, expressions in a printed document that contain greek characters can be entered as greek characters in your code. Let's calculate the following expression.
```julia
α = m1 + m2
```
"""
# ╔═╡ 82375bad-7883-4db4-8693-401b8925d90f
α = m1 + m2
# ╔═╡ b625dc4a-4267-4716-9d90-cf7579ff8669
md"""
!!! note
Notice that the error of the result α has been propogated correctly.
Let's add another package called Unitful, which enables attaching units to variables.
"""
# ╔═╡ 3b7d830b-fc62-4786-8ac3-90be3a0fe665
md"""
Now let's create two new values m3 and m4 with units attached, and then multiply them together to create a third variable β.
```julia
m3 = (32 ± 0.1)u"m/s"
m4 = (9.8 ± 0.3)u"s"
β = m3 * m
```
"""
# ╔═╡ 79b291a1-4a44-4431-bb6f-74f8b215f897
m3 = (32 ± 0.1)u"m/s"
# ╔═╡ 7efdf535-2135-4c69-85cb-d2614903d4fd
m4 = (9.8 ± 0.3)u"s"
# ╔═╡ 6e9f75ea-f009-4c05-bf03-fd6c66214ce9
β = m3 * m4
# ╔═╡ c5f5fdbc-3439-4c99-843d-5ef6dc3c59b7
md"""
The variable β's value now has an associated error and unit.
Let's see if this works with one dimensional arrays or vectors.
```julia
γ = [10 ± 0.1, 20 ± 0.2, 30 ± 0.3]u"m/s" .* [15 ± 0.01, 25 ± 0.02, 25 ± 0.03]u"s"
```
Note the dot '.' before the multiplication character '*'. This means element-wise multiplication.
"""
# ╔═╡ ad6b69da-d37c-4e3e-9f0f-186f8b6d3b00
γ = [10 ± 0.1, 20 ± 0.2, 30 ± 0.3]u"m/s" .* [15 ± 0.01, 25 ± 0.02, 25 ± 0.03]u"s"
# ╔═╡ 12061b16-9c5c-475a-bf87-82f8e9d167eb
md"""
!!! note
What have we learned about the Julia command line and features?
* Julia has four command line modes: **REPL**, **help**, **shell**, and **package manager**.
* Julia understands **unicode**.
* Julia packages are **composable**. It means that independent packages are compatible and work together without modification, as demonstrated by the Measurements and Unitful packages.
"""
# ╔═╡ b94b3f48-80c2-44b3-ba5d-896913ee7bb5
md"""
**===================================================================================**
## Interoperability
**Calling Python from Julia**
Julia has two packages for calling Python code from Julia: PyCall & PythonCall. PyCall has an easier learning curve, but has a few limitations. Whereas, PythonCall has better performance, because it is more complete and allows for more control.
Both packages have symmetric interfaces, so the user can call Python from Julia and Julia from Python. This session will only focus on calling Python from Julia.
```julia
using PythonCall
```
"""
# ╔═╡ 4426caeb-9b03-4a9a-8e7d-5c8cc9303b59
md"""
By default importing the module will initialize a conda environment in your Julia environment, install Python into it, load the corresponding Python library, and initialize an interpreter.
Here is an example using Python's "re" module. Because `PyCall` and `PythonCall` both define pyimport, this example must qualify which one we are using, namely PythonCall's `pyimport`.
```julia
let
re = PythonCall.pyimport("re")
words = re.findall("[a-zA-Z]+", "PythonCall.jl is great")
sentence = Py(" ").join(words)
pyconvert(String, sentence) # convert Python string to Julia string
end
```
Try it.
"""
# ╔═╡ 3f058e45-d5f1-4f8c-a56a-a3de4d65f68d
let
re = PythonCall.pyimport("re")
words = re.findall("[a-zA-Z]+", "PythonCall.jl is great")
sentence = Py(" ").join(words)
pyconvert(String, sentence) # convert Python string to Julia string
end
# ╔═╡ 84593e6e-5a29-435a-850e-13475e38bf53
md"""
**Wrapper Types**
A wrapper is a Julia type that wraps a Python object, but gives it Julia semantics. For example, the PyList type wraps Python's list object.
```julia
let
x = pylist([3,4,5])
y = PyList{Union{Nothing, Int64}}(x)
push!(y, nothing)
append!(y, 1:2)
x
end
```
Try it.
"""
# ╔═╡ 80563da7-d13c-499f-aade-c2423338eebf
let
x = pylist([3,4,5])
y = PyList{Union{Nothing, Int64}}(x)
push!(y, nothing)
append!(y, 1:2)
x
end
# ╔═╡ 6bfc1a81-d594-4a7a-9b59-b85e089d8e8a
md"""
There are wrappers for other container types, such as PyDict and PySet.
```julia
let
x = PythonCall.pyimport("array").array("i", [3,4,5])
y = PythonCall.PyArray(x)
println(sum(y))
y[1] = 0
x
end
```
Try this example too.
"""
# ╔═╡ cecec5b2-fc47-4a50-8b29-c613828802ec
let
x = PythonCall.pyimport("array").array("i", [3,4,5])
y = PythonCall.PyArray(x)
println(sum(y))
y[1] = 0
x
end
# ╔═╡ baa960f9-58e7-4f50-9de0-34ad663b43fb
md"""
PyArray directly wraps the underlying data buffer, so array operations such as indexing are about as fast as an ordinary Array.
#### Installing Python packages
Assuming you are using `CondaPkg.jl`, PythonCall uses it to automatically install any Python packages. For example,
```julia
using CondaPkg
# enter package manager
conda add some_package
```
"""
# ╔═╡ cc45c201-1819-472f-99ff-d51143d3440c
md"""
**===================================================================================**
## Optimization and Macros
Julia is a high-performance language. However, like any computer language, certain constructs are faster and will better take adva
ntage of your computer's resources. This tutorial will overview how you can use Julia and some of its unique features to enable bl
azing-fast performance.
However, to achieve good performance, there are a couple of things to keep in mind.
```julia
using BenchmarkTools
```
"""
# ╔═╡ 6aad639a-f7da-4ffb-b68a-53a53b9fe22b
md"""
**Global Variables and Type Instabilities**
First global variables in Julia are almost always a bad idea. First, from a coding standpoint, they are very hard to reason about since they could change at any moment. However, for Julia, they are also a performance bottleneck. Let's consider a simple function that updates a global array to demonstrate the issue.
```julia
begin
gl = rand(1000)
function global_update()
for i in eachindex(gl)
gl[i] += 1
end
end
end
```
"""
# ╔═╡ 88ae8198-b1aa-4838-a619-1ee926973239
begin
gl = rand(1000)
function global_update()
for i in eachindex(gl)
gl[i] += 1
end
end
end
# ╔═╡ 9296b12e-74aa-4a14-bcfe-612368916919
md"""
Now let's check the performance of this function. To do this, we will use the excellent benchmarking package [`BenchmarTools.jl`](https://github.com/JuliaCI/BenchmarkTools.jl) and the macro `@benchmark`, which runs the function multiple times and outputs a histogram of the time it took to execute the function
```julia-repl
julia> @benchmark global_update()
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
Range (min … max): 96.743 μs … 8.838 ms ┊ GC (min … max): 0.00% … 97.79%
Time (median): 105.987 μs ┊ GC (median): 0.00%
Time (mean ± σ): 123.252 μs ± 227.353 μs ┊ GC (mean ± σ): 5.14% ± 2.76%
▄█▇█▇▅▄▃▄▅▃▂▃▅▆▅▅▄▃▃▂▂▂ ▁▁▁ ▁ ▁ ▂
████████████████████████████▇██▇▇██▇███████▇▇█▇▇█▇▇▇▇▆▇▇▆▆▅▆▅ █
96.7 μs Histogram: log(frequency) by time 211 μs <
Memory estimate: 77.77 KiB, allocs estimate: 3978.
```
!!! note
This was run on a Intel Core i7 i7-1185G7 processors so your benchmarks may differ.
Try this benchmark
"""
# ╔═╡ 939909cc-adc4-46bf-ab09-6f70fcb7c9ed
@benchmark global_update()
# ╔═╡ 21a75052-236a-4899-b48c-c9e12298f3d9
md"""
Looking at the histogram, we see that the minimum time is 122 μs to update a vector! We can get an idea of why this is happening by looking at the total number of allocations we made while updating the vector. Since we are updating the array in place, there should be no allocations.
To see what is happening here, Julia provides several code introspection tools.
Here we will use `@code_warntype`
```julia
@code_warntype global_update()
```
"""
# ╔═╡ a0b57cff-1cf2-4c40-a59b-e7e1d351870c
@code_warntype global_update()
# ╔═╡ b4cab1ca-bfe4-442b-94b6-f7271ce19f45
md"""
which should give the following output
```julia
MethodInstance for Main.var"workspace#12".global_update()
from global_update() in Main.var"workspace#12"
Arguments
#self#::Core.Const(Main.var"workspace#12".global_update)
Locals
@_2::Any
i::Any
Body::Nothing
1 ─ %1 = Main.var"workspace#12".eachindex(Main.var"workspace#12".gl)::Any
│ (@_2 = Base.iterate(%1))
│ %3 = (@_2 === nothing)::Bool
│ %4 = Base.not_int(%3)::Bool
└── goto #4 if not %4
2 ┄ %6 = @_2::Any
│ (i = Core.getfield(%6, 1))
│ %8 = Core.getfield(%6, 2)::Any
│ %9 = Base.getindex(Main.var"workspace#12".gl, i)::Any
│ %10 = (%9 + 1)::Any
│ Base.setindex!(Main.var"workspace#12".gl, %10, i)
│ (@_2 = Base.iterate(%1, %8))
│ %13 = (@_2 === nothing)::Bool
│ %14 = Base.not_int(%13)::Bool
└── goto #4 if not %14
3 ─ goto #2
4 ┄ return nothing
```
`@code_warntype` tells us where the Julia compiler could not infer the variable type. If this happens, Julia cannot efficiently compile the function, and we end up with performance comparable to Python. The above example highlights the type instabilities in red and denotes accessing the global variable `gl`. These globals are a problem for Julia because their type could change anytime. As a result, Julia defaults to leaving the type to be the `Any` type.
Typically the standard way to fix this issue is to pass the offending variable as an argument to the function.
```julia
function better_update!(x)
for i in eachindex(x)
x[i] += 1
end
end
```
"""
# ╔═╡ 4e9d3ae6-a748-4c0d-be4b-f55d36416b90
function better_update!(x)
for i in eachindex(x)
x[i] += 1
end
end
# ╔═╡ 91122ecd-aa85-4c8c-8081-efc408bc27fa
md"""
Benchmarking this now
```julia
@benchmark better_update!(gl)
```
"""
# ╔═╡ 8a1a1068-f0b7-4b25-b536-946d5b71014e
@benchmark better_update!(gl)
# ╔═╡ ed3f056f-2533-4afd-8924-bea5522d2b67
md"""
By passing the array as a function argument, Julia can infer the type and compile an efficient version of the function, achieving a 1000x speedup on my machine (Ryzen 7950x).
```julia
@code_warntype better_update!(gl)
```
"""
# ╔═╡ 73bc014e-5fbe-4e56-8541-ac4ea7a1de73
@code_warntype better_update!(gl)
# ╔═╡ 2a0dc186-5f81-43d7-b35d-114d81ca189f
md"""
We see that the red font is gone. This is a general thing to keep in mind when using Julia. Try not to use the global scope in performance-critical parts. Instead, place the computation inside a function.
**Types**
Julia is a typed but dynamic language. The use of types is part of the reason that Julia can produce fast code. If Julia can infer the types inside the body of a function, it will compile efficient machine code. However, if this is not the case, the function will become **type unstable**. We saw this above with our global example, but these type instabilities can also occur in other seemingly simple functions.
For example let's start with a simple sum
```julia
function my_sum(x)
s = 0
for xi in x
s += xi
end
return
end
```
"""
# ╔═╡ 607282b1-b131-4673-b587-e5153526b479
# ╔═╡ 89bbe72c-6ac1-42e8-9bad-9622f9a0ddc8
md"""
Analyzing this with `@code_warntype` shows a small type instability.
```julia
@code_warntype my_sum(gl)
```
!!! tip
Remember to look for red-highlighted characters
"""
# ╔═╡ 5b9b2e83-40c9-41b7-bf7c-afa532381c3a
# ╔═╡ f4f6a0f4-2122-4ff8-9502-277c259bdc12
md"""
In this case, we see that Julia inserted a type instabilities since it could not determine the specific type of `s`. This is because when we initialized `s`, we used the value `0` which is an integer. Therefore, when we added xi to it, Julia determined that the type of `s` could either be an `Int` or `Float`.
!!! note
In Julia 1.8, the compiler is actually able to do something called [`union splitting`](https://julialang.org/blog/2018/08/union-splitting/), preventing this type instability from being a problem. However, it is still good practice to write more generic code.
To fix this we need to initialize `s` to be more generic. That can be done with the `zero` function in Julia.
```julia
function my_sum_better(x)
s = zero(eltype(x))
for xi in x
s += xi
end
return s
end
```
"""
# ╔═╡ b1c9394d-c8d2-41b0-b660-2a306f37938b
# ╔═╡ d150d0ad-a56c-4980-93b7-3f4aeb5b99fc
md"""
Running `@code_warntype` we now get
```julia
@code_warntype my_sum_better(gl)
```
"""
# ╔═╡ d1c0bf38-5f71-4b60-9237-8d49674b711a
# ╔═╡ 578e9229-c627-44ee-808a-665093b60163
md"""
`zero` is a generic function that will create a `0` element that matches the type of the elements of the vector `x`.
One important thing to note is that while Julia uses types to optimize the code, using types in the function arguments does not impact performance at all.
To see this let's look at an explicit version of `my_sum`
```julia
function my_sum_explicit(x::Vector{Float64})
s = zero(eltype(x))
for xi in x
s += xi
end
return s
end
```
"""
# ╔═╡ 6af8a79d-de65-4ab2-8b02-39bb713769ff
# ╔═╡ 1ba4ae23-68d9-4b71-ac58-7cc7b05c5a6c
md"""
We can now benchmark both of our functions
```julia
@benchmark my_sum_better($gl)
```
"""
# ╔═╡ 648426de-1ae8-4d71-94a4-bad3246949bf
# ╔═╡ 4172daff-f72b-43a5-b9b2-bdee69c30cc6
md"""
```julia
@benchmark my_sum_explicit($gl)
```
"""
# ╔═╡ 3a3b1298-4e7f-4105-9012-5ee7f98bdb42
# ╔═╡ cb9ce792-96b1-4864-9ab6-bc9bcd8ef1da
md"""
We can even make sure that both functions produce the same code using `@code_llvm` (`@code_native`), which outputs the LLVM IR (native machine code).
```julia
@code_llvm my_sum_better(gl)
```
"""
# ╔═╡ 6a0165e3-a5f3-45eb-8fa1-0295c63a750e
# ╔═╡ dd31c043-d7ab-4cdb-a541-3c9d8874f13e
md"""
```julia
@code_llvm my_sum_explicit(gl)
```
"""
# ╔═╡ 95cf7746-4e62-4fd8-a178-d089811ba30a
# ╔═╡ aa122d78-4dd1-4d90-8fba-6739cc520579
md"""
Being overly specific with types in Julia is considered bad practice since it prevents composability with other libraries in Julia
. For example,
```julia
my_sum_explicit(Float32.(gl))
```
"""
# ╔═╡ 2cf80da8-260d-4a09-aeba-e214578306d7
# ╔═╡ b5ca6168-9b97-4554-9c17-42e79e9ca4b9
md"""
gives a method error because we told the compiler that the function could only accept `Float64`. In Julia, types are mostly used for `dispatch` i.e., selecting which function to use.
Julia uses `multiple dispatch`, which uses the function name and all required arguments to select the proper function to execute. On the other hand, Python uses `single dispatch`, which uses the function name and only the first argument to select the function.
For example, the `add` operator in Python has two operators: `__add__` and `__radd__`. The second version of the function is necessary when the first can't perform the call. The `add` operator in Julia has two functions: `add(arg1, arg2)` and `add(arg2, arg1)`, i.e., two functions of the same name with their argruments swapped. **That is multiple dispatch.**
**Additional Tools**
In addition to `@code_warntype` Julia also has a number of other tools that can help diagnose type instabilities or performance problems:
- [`Cthulhu.jl`](https://github.com/JuliaDebug/Cthulhu.jl): Recursively moves through a function and outputs the results of type inference.
- [`JET.jl`](https://github.com/aviatesk/JET.jl): Employs Julia's type inference system to detect potential performance problems as well as bugs.
- [`ProfileView.jl`](https://github.com/timholy/ProfileView.jl) Julia profiler and flame graph for evaluating function performance.
"""
# ╔═╡ cb3a5dd2-8e56-404e-9c4e-db34c26ce1fa
md"""
**===================================================================================**
## Parallel Computing
Julia is particularly able to exploit various types of parallelism to accelerate the performance of a program.
In this tutorial, we will overview how to enable parallelism in various Julia programs.
Julia has a strong parallel computing infrastructure that enable HPC using vectorization,
threading, distributed computing, and even GPU acceleration.
**Single Processor Parallelism (SIMD)**
To get started, we will discuss low-level parallelism related to a single core called
*SIMD* or **Single Instruction Multiple Data**. SIMD is when the computer can apply a
single instruction to multiple data sets in a single instruction cycle. For instance,
suppose we have two vectors of number in Julia `a` and `b`. Then the following graph
compares how a serial instruction v.s. a vectorized instruction would be run on the computer.
!!! note
**CPU cycle**: Can be thought of the smallest unit of time on which a CPU behaves. In a single CPU cycle, the computer usually does a fetch-decode-execute step. Briefly, this means that you can think of the CPU doing a single simpler operation, like addition, multiplication, etc.
"""
# ╔═╡ 582ff185-6da5-4aa9-929a-9ad2b84acf3e
Resource("https://github.com/sefffal/AASJuliaWorkshop/raw/main/vectorization.png")
# ╔═╡ ce7e5c95-face-406d-91d8-c97ba3d6a8f3
md"""
While the serial computation loops through each element in the list and applies the
addition operation each CPU clock cycle, the vectorized version realizes that it can
group multiple datasets (array elements) together and perform the same operation.
This can lead to 2x, 4x, or greater speedups depending on the specific CPU architecture
(related to AVX, AVX2, AVX512).
So what does Julia do? Let's start with the simple example above:
!!! note
Vectorization in this setting is usually different from vectorization in Python/R. In python vectorization refers to placing all your variables in some vector container, like a numpy array, so that the resulting operation is run using a C/Fortran library.
```julia
function serial_add!(out, x, y)
for i in eachindex(x, y)
out[i] = x[i] + y[i]
end
return out
end
```
"""
# ╔═╡ 19572955-bd07-4c79-a124-a6f7771d8b05
# ╔═╡ dc9a555e-5bf9-406e-8af9-a32d885f67b6
md"""
!!! note
Note that we append the function with `!` this is a Julia convention which signals that we are mutating the arguments.
First we will allocate some variables for this tutorial.
```julia
begin
N = 2^10
x = rand(N)
y = rand(N)
out = zeros(y)
end
```
"""
# ╔═╡ 687721b3-93d5-4f7f-832b-b0db1d7bb88d
# ╔═╡ f0d4631a-d7b1-4319-bda6-9af2c323841b
md"""
Now let's benchmark our serial add to get a baseline for our performance.
```julia
@benchmark serial_add!($out, $x, $y)
```
"""
# ╔═╡ 0cd6d228-ce36-49ff-b35c-88a7937a914e
# ╔═╡ 1596de4f-dd5b-4236-885a-8bf70e0eb9cf
md"""
Analyzing this on a Ryzen 7950x, it appears that the summation is 53.512 ns, or each
addition takes only 0.05ns! Inverting this number would naively suggest that the computer I am using has a 19 GHz processor!
SIMD is the reason for this performance. Namely Julia's was able to automatically apply its auto-vectorization routines to use SIMD to accelerate the program.
To confirm that Julia was able to vectorize the loop we can use the introspection tool
```julia
@code_llvm serial_all!(out, x, y)
```
"""
# ╔═╡ caedac68-1dad-4ebb-9546-8c763733a916
# ╔═╡ 1aa3a8c6-2e0b-4944-92a4-10a7a06cb365
md"""
This outputs the LLVM IR and represents the final step of Julia's compilation pipeline
before it is converted into native machine code. While the output of `@code_llvm` is
complicated to check that the compiler effectively used SIMD we can look for something
similar to
```
%wide.load30 = load <4 x double>, <4 x double>* %55, align 8
; └
; ┌ @ float.jl:383 within `+`
%56 = fadd <4 x double> %wide.load, %wide.load27
```
This means that for each addition clock, we are simultaneously adding four elements of the array together. As a sanity check, this means that I have a 19/4 = 4.8 GHz processor which is roughly in line with the Ryzen 7950x reported speed.
**Vectorizing Julia Code with Packages**
Proving that a program can SIMD however can be difficult, and sometimes the compiler
won't effectively auto-vectorize the code. Julia however provides a number of tools that
can help the user to more effectively use SIMD. The most low-level of these libraries
is [`SIMD.jl`](https://github.com/eschnett/SIMD.jl). However, most users never need to use SIMD.jl directly (for an introduction
see <http://kristofferc.github.io/post/intrinsics/>. Instead most Julia users will use more-upstream packages, such as [`LoopVectorization.jl`](https://github.com/JuliaSIMD/LoopVectorization.jl).
To see `LoopVectorization` in action let's change our above example to the slightly more complicated function.
```julia
function serial_sinadd(out, x, y)
for i in eachindex(out, x, y)
out[i] = x[i] + sin(y[i])
end
return out
end
```
"""
# ╔═╡ 9720d3c9-444f-45a7-a586-5ece2fd45f42
# ╔═╡ aa14adc1-ad37-4217-a2c1-99ccf0c9a1a1
md"""
Again lets start with a baseline evaluation
```julia
@benchmark serial_sinadd($out, $x, $y)
```
"""
# ╔═╡ 4a9da04b-f0f7-4c04-b451-dfd3a2094133
# ╔═╡ 773f0d5d-ce3c-4059-9880-4802dd624357
md"""
Running this example will show that the code is a lot slower than our previous example! Part of this is because `sin` is expensive, however we can also check whether the code was vectorized using the `@code_llvm`.
```julia
@code_llvm serial_sinadd(out, x, y)
```
"""
# ╔═╡ 31034523-c379-4fd9-a77f-a5c0964b85db
# ╔═╡ 8d1e882b-d074-4f99-88d9-2b03abc31dbe
md"""
Analyzing the output does show that Julia/LLVM was unable to automatically vectorize the expression. The reason for this is complicated and won't be discussed. However, we can fix this with
loop vectorization and its `@turbo` macro
```julia
function serial_sinadd_turbo(out, x, y)
@turbo for i in eachindex(out, x, y)
out[i] = x[i] + sin(y[i])
end
return out
end
```
"""
# ╔═╡ ad3d9bbf-6813-4cde-aa1c-8ce9f20f65dc
# ╔═╡ dc1d12b6-6fd9-4140-b6fa-187d608fc6b7
md"""
```julia
@benchmark serial_sinadd_turbo($out, $x, $y)
```
"""
# ╔═╡ 078e1a26-9580-4eed-8117-71493092f45e
# ╔═╡ 3f959b86-b3ee-4111-ba25-d5838aa41189
md"""
And boom we get large speed increase (factor of 2 on a Ryzen 7950x) by simply adding the `@turbo` macro to our loop.