-
Notifications
You must be signed in to change notification settings - Fork 0
/
stochastic.jl
2126 lines (1733 loc) · 67.2 KB
/
stochastic.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.14
using Markdown
using InteractiveUtils
# ╔═╡ 26c3d3fe-af66-4d79-8aaa-5f5b0784bab0
using CairoMakie
# ╔═╡ 0bee0d4b-272d-406f-b9fd-b947b901278b
using StatsBase
# ╔═╡ 9b0a5eee-a0d0-4b5e-83cf-7badb1753688
using PlutoUI: Slider
# ╔═╡ 30c0a8df-2340-4f66-a415-9375d0a6c893
using Distributions
# ╔═╡ c708e88a-4771-4144-8765-a78aa730e7f9
using LinearAlgebra
# ╔═╡ 6259db20-c705-4e7c-ba8f-18cc8b733f8b
using Random: AbstractRNG, Xoshiro, default_rng, randexp
# ╔═╡ aa7a9420-f7e1-4a44-9375-882c79f97e1a
using LsqFit
# ╔═╡ 7c145e9e-5d12-11ed-3c4b-796dde8540c7
md"""
# Random Variables
Useful links for this section:
- [Random docs](https://docs.julialang.org/en/v1/stdlib/Random/#Random-Numbers)
- [Mathematical operations docs](https://docs.julialang.org/en/v1/manual/mathematical-operations/#Mathematical-Operations-and-Elementary-Functions)
- [Histogram docs](https://juliastats.org/StatsBase.jl/stable/empirical/#Empirical-Estimation-1)
- [Plotting docs](https://docs.makie.org/stable/)
- [Plotting example gallery](https://beautiful.makie.org/dev/)
In Julia, the [rand](https://docs.julialang.org/en/v1/stdlib/Random/#Base.rand) function samples a number in [0,1). press SHIFT + RETURN with the cursor in the cell below to sample a new number.
"""
# ╔═╡ 9128a75c-bcc4-4131-bdd0-73a6a8490165
rand()
# ╔═╡ f89e1123-2dd8-4c40-b501-909829e8c714
md"## Exercise 1: Bernoulli Trial
Below is a function definition and evaluation. Right now the function only returns *true* no matter what random number rand spits out."
# ╔═╡ 985916d7-8105-48d7-a3c9-9447afa50416
bernoulli(ω, p) = true
# ╔═╡ f3e091d6-5359-40b2-817e-db2848d70f90
bernoulli(rand(), 0.5)
# ╔═╡ f1ff8af1-6954-4771-9981-db2e295360a3
# this counts how often bernoulli(rand(), 0.7) returns true out of 1_000 evaluations
# If you've implemented the function correctly this should return 0.7
count([bernoulli(rand(), 0.7) for _ in 1:1_000]) / 1_000
# ╔═╡ 6382e7e4-2508-4bf6-9b09-41692268089b
md"Here are some examples of how to define functions in Julia."
# ╔═╡ bed0c3f8-0017-4fdd-b520-e4a265677140
# This is a one line function definition
# f adds the inputs x, y and z and subtracts 5
f(x, y, z) = x + y + z - 5
# ╔═╡ 0642ade6-1869-4848-bc85-f60a85ec15ff
f(0.6, 0.1, 10)
# ╔═╡ 154cd13b-391d-46c2-83d6-241ca23a154e
# Functions often do more complicated things and may require multiple lines
# I show the return staement here, but you can delete return and just keep
# max(a,b) at the end. The last line of a function is automatically returned.
function g(x, y)
a = 2x
b = 5y + x
return max(a, b) # returns the larger of a and b
end
# ╔═╡ 08548873-ffd7-4f0c-83cd-8ba4c8d536c6
g(5, 7)
# ╔═╡ bbfdd8d8-f27f-4830-b468-df189c778de8
md"To return something else, try changing the bernoulli function above to return *false* instead. To do the first exercise, you may find the less than or equals (<=) comparison operator useful.
To be able to use greek letters and other symbols, type \\omega and press TAB. You can get all kinds of greek letters and mathematical symbols this way."
# ╔═╡ a666d797-ecf3-441f-9406-f616305f2d31
rand() <= 0.9
# ╔═╡ a736afcc-b477-45f9-ae5b-0fdd31b4f4f7
md"One major use of the *true* and *false* values is to conditionally execute code. For example,"
# ╔═╡ ca39bb7a-39e6-4756-810b-20813aede18f
if bernoulli(rand(), 0.8)
println("80% of the time I'm happy! :)")
else
println("But 20% of the time I'm sad :(")
end
# ╔═╡ 57ea1a43-33ec-46d9-a26c-9a52d5fb52f1
md"## Exercise 2: Uniform Distribution"
# ╔═╡ e09214e7-82b3-4119-8b97-ff92da6c9f3f
uniform(ω, a, b) = ω
# ╔═╡ e12a61f0-b0bc-4fad-8712-64668dad552b
# Not quite right yet
5 <= uniform(rand(), 5, 9) <= 9
# ╔═╡ f35904f0-a884-4979-a464-2ac04fcd5cf7
md"To generate a uniformly distributed variable, you may find the basic mathematical operations useful. Below are some examples. For more details, click on the docs link at the beginning of this section."
# ╔═╡ 4cf08f8c-b7ee-4700-b556-b61abe166b15
# This is a variable representing the number 2.3
foo = 2.3
# ╔═╡ 04a883ff-f076-47a3-9c7a-b645abb6e2c3
# It can be multiplied
foo * 3
# ╔═╡ b45f6141-c1ee-4ec0-949f-b4fbc7b512e3
# Or divided. Get π by typing \pi and then TAB
foo / π
# ╔═╡ 7d0b767d-61c4-4041-909e-1fb2a177ccf9
# Or added and subtracted
foo + 3 - 20 <= 0
# ╔═╡ 41d77d2a-b38b-46a7-97a1-a3e530df33fb
# and much more...
sqrt(sin(log(foo^3)))
# ╔═╡ 9e61d9c4-1308-46d5-b32d-7e8419a48f67
md"## Making a Histogram
Let's test whether your random variable is doing the right thing by sampling many times and plotting the distribution of the samples we get.
To make a list or vector of samples, you can use a list comprehension as below. I also provide some further examples so you can see how list comprehensions and Vectors work."
# ╔═╡ 08cb36a2-4b14-4003-b2f1-131f87e82db2
[i for i in 1:5]
# ╔═╡ 8d59dc93-cc98-4e58-aaf0-3112758c7cb5
# Note that these a:b objects are not Vectors, they are called ranges.
# However, they behave like a Vector and they can be converted to one with collect
# In fact, anything you can iterate over can be turned into a Vector with collect
5:8, collect(5:8)
# ╔═╡ bca187e3-04c6-4a30-81ba-c639f288db3e
1:10 isa Vector
# ╔═╡ ce084ee6-1b2f-40da-8a70-1005dd861f05
# we don't need the variable, so we use underscore _ to signal this fact
[2 for _ in 1:5]
# ╔═╡ fca887ee-28d2-4c21-9938-b892d87380eb
# cube each number from 0 to 0.5, going in steps of size 0.1
[x^3 for x in 0.0:0.1:0.5]
# ╔═╡ dca96c3e-e674-4124-a794-ad1ea5daecb8
md"vectors can be iterated over and indexed into as follows."
# ╔═╡ 9dd88140-fc85-4896-bd3a-90a79d4c86b3
squares = [n^2 for n in 1:10]
# ╔═╡ 0cc8e35a-412f-4675-b9db-1c79ed305821
for x in squares
if isodd(x)
println("forward")
else
println("backward")
end
end
# ╔═╡ 5f8ce592-ab59-49f1-babb-ae7d759bebbf
# get the first entry
squares[1]
# ╔═╡ edb3721e-8fc2-4cf4-b925-bc2c729fc401
# get the last entry
squares[end]
# ╔═╡ db53f578-7050-4831-8c98-8e5e243eb606
# get the third to fifth entry
squares[3:5]
# ╔═╡ 681ddd77-9da9-4777-b0f5-64169fc47e3c
# set the 9th entry
squares[9] = -1
# ╔═╡ f4631d98-dad4-41c9-ac78-af0aee40a119
# and the 2nd to 3rd entries
squares[2:3] = [-2, -3]
# ╔═╡ 81fe6e9a-2af8-40b2-a364-a9512537aeeb
squares
# ╔═╡ 7d29e024-975f-4d61-8c5a-d3c9a6dfb0e2
md"Back to our samples... Let's make a histogram and plot it."
# ╔═╡ 93e93bcb-29cd-4b26-9047-0d7ff9c0ebb1
md"## Exercise 6: Exponential Distribution"
# ╔═╡ fd3754b0-f8cd-428d-9c97-f5d2583eb82f
# not quite right jet. This should be sampled exponentially
myrandexp(ω) = sqrt(ω)
# ╔═╡ b545f815-545e-44bf-be76-25ee69881bf8
samples = [myrandexp(rand()) for _ in 1:100_000]
# ╔═╡ c994b386-e183-471c-b161-5a4b5a3374ff
samples isa Vector
# ╔═╡ 3af8c14b-fa91-457a-87e3-d29866cc3e49
# Make a histogram
hist = fit(Histogram, samples)
# ╔═╡ 53073c14-bf67-4f84-9a56-7d179dc77301
plot(hist)
# ╔═╡ d216cf65-2de7-46c7-8b0c-f1e3a355ab5f
# compare to the built in randexp()
randexp()
# ╔═╡ 9ec38300-de96-4860-9893-1a8a00166004
md"## Exercise 9: Semicircle"
# ╔═╡ 831a9d8f-3eeb-4f1c-8c50-fb09413ee689
function semicircle(rng::AbstractRNG)
x = rand(rng)
y = rand(rng)
# accept some, reject others
return x
end
# ╔═╡ 4912e73b-d15c-4024-9bb2-e355d0de663d
let fig = Figure(), n = 500
ax = Axis(fig[1, 1]; aspect=DataAspect(), xlabel="x", ylabel="y")
pdf(x) = sqrt(1 - x^2)
rxs = 2 .* rand(n) .- 1
rys = rand(n)
idx = rys .^2 .+ rxs .^2 .< 1
notidx = map(!identity, idx)
scatter!(ax, rxs[idx], rys[idx], color=:red, label="accepted")
scatter!(ax, rxs[notidx], rys[notidx], color=:black, label="rejected")
xs = -1:0.01:1
ys = pdf.(xs)
lines!(ax, xs, ys; label="pdf")
axislegend(ax)
fig
end
# ╔═╡ 0391e8fe-0a18-4782-a797-157d253417af
let n = 100_000 # estimating π
p = 4 * count(_ -> rand()^2 + rand()^2 <= 1, 1:n) / n
(π = p, error = abs(π - p) / π)
end
# ╔═╡ 01004f3b-fb1e-4da0-801e-786eb12a1e76
md"# Monte Carlo"
# ╔═╡ 4e88f8a9-fe2d-40b8-829d-b5d636127e83
function walk(
jump,
rng::AbstractRNG,
x0s::AbstractVector{T},
nt::Integer,
p
) where T
# initialise memory for trajectories
xs = map(_ -> Vector{T}(undef, nt), x0s)
for i in 1:length(x0s) # for each trajectory
x = x0s[i] # init position
xs[i][1] = x # # save initial position
for j in 2:nt # for each time step: jump and save
x = jump(rng, x, p)
xs[i][j] = x
end
end
return xs
end
# ╔═╡ f8acef37-ce4a-49f7-81df-745ba26b50a8
function walk(jump, x0s::AbstractVector{T}, nt::Integer, p) where T
walk(jump, default_rng(), x0s, nt, p)
end
# ╔═╡ c75338b4-6bf0-4ef3-a07f-4736e3bcd4dd
opendiffuse(rng::AbstractRNG, x, p) = x + p.σ * randn(rng)
# ╔═╡ f0a0c065-600a-44e7-afec-9a43c1c02698
discrete(rng::AbstractRNG, x, p) = rand(rng, Bool) ? x + p.σ : x - p.σ
# ╔═╡ 9086bcd0-3fc4-4ba9-8f30-2f78b5ead628
function boxdiffuse(rng::AbstractRNG, x, p)
y = x + p.σ * randn(rng)
y = y < 0.0 ? -y : y
while y > p.L
y = p.L - (y - p.L)
y = y < 0.0 ? -y : y
end
return y
end
# ╔═╡ 7b2c2c89-ff31-4f15-99b9-3a46eee4d19e
ohrnstein_uhlenbeck(rng, x, p) = x - p.a * x + p.σ * randn(rng)
# ╔═╡ 9286d291-cc9b-450a-aae5-7bf8fa32f185
periodic(rng, x, p) = x - p.a * sin(x) + p.σ * randn(rng)
# ╔═╡ a1a66164-d290-40f9-8f76-0fe3aef90564
pareto(rng, x, p) = x + p.σ * (rand(rng, Pareto(p.α)) - 1) * rand(rng, (-1, 1))
# ╔═╡ d7d7a506-993a-48a7-8215-d0c1a192dcf7
kelly(rng, x, p) = rand(rng) <= p.p ? x * (1.0 + p.f * p.b) : x * (1.0 - p.f)
# ╔═╡ a3bc1aa1-0795-4e7e-a55a-9e76366ce0f2
rw = walk(opendiffuse, 0.1 * randn(100), 100, (σ = 0.1,))
# ╔═╡ f1b1ecb1-4147-48c6-a9bc-b4949372094c
let fig = Figure()
# add the following after fig[1, 1] to plot with y axis using log scale
# ; yscale=log10
ax = Axis(fig[1, 1])
for i in 1:length(rw)
lines!(ax, rw[i], color=(:black, 0.2))
end
fig
end
# ╔═╡ fa122c23-f3c8-4bdb-a6ed-585bb694da6f
let fig = Figure()
ax = Axis(fig[1, 1])
N = length(rw[1])
μs = [mean([xs[i] for xs in rw]) for i in 1:N]
lines!(ax, μs)
fig
end
# ╔═╡ 6ee96f9d-4e8a-4c9a-aa44-c30f14496b97
getvars(rw) = [var([xs[i] for xs in rw]) for i in 1:length(rw[1])]
# ╔═╡ e20309dd-03d0-4003-b383-581fadaf74d0
let fig = Figure()
ax = Axis(fig[1, 1])
lines!(ax, getvars(rw))
fig
end
# ╔═╡ 98179e10-52fa-44b7-9155-7300c27cd5a7
linmodel(x, p) = x .* p[1] .+ p[2]
# ╔═╡ 05873c45-3276-4df6-8cf0-3c97b55aa48d
function getslope(vars)
fit = curve_fit(linmodel, 1:length(vars), vars, [1.0, 0.0])
fit.param[1]
end
# ╔═╡ 6fe7dcc5-805a-4d09-8baa-949952762d4c
let fig = Figure()
ax = Axis(fig[1, 1])
σs = 0.1:0.1:1.0
slopes = [getslope(getvars(
walk(opendiffuse, 0.1 * randn(1_000), 10, (σ = σ,))
)) for σ in σs]
scatter!(ax, σs .^ 2, slopes)
fig
end
# ╔═╡ f2f81a76-a2c8-40e8-8282-be7bf869370c
md"# Markov Chains"
# ╔═╡ b62f7c11-07b8-4dd9-b6c7-bc8a13ea7faf
T = [0.2 0.2; 0.8 0.8]
# ╔═╡ 8f001bf1-b456-4fbd-b025-8faee9754768
p0 = [0.5, 0.5]
# ╔═╡ 3e9244ab-1160-4381-820f-4ae01df68383
p = T^1000 * p0
# ╔═╡ 099de66c-9163-4fdc-9f94-52d83ce345cf
sum(p)
# ╔═╡ 854bdeba-0c10-4631-995e-81ca747d8c4f
E = eigen(T)
# ╔═╡ 557f84d7-7526-4978-942c-c2d0fe328dc8
pstat = E.vectors[:, 2]
# ╔═╡ 6ac10e92-8687-4a99-b64c-4979f96826aa
T * pstat ≈ pstat
# ╔═╡ 9ebe8846-ee64-44be-8726-fafcee2488b2
let fig = Figure(), p0 = [1, 0], T = T, nsteps = 10
ax = Axis(fig[1, 1]; xlabel = "t", ylabel = "p")
heat = zeros(nsteps, length(p0))
heat[1, :] .= p0
for i in 2:nsteps
mul!(view(heat, i, :), T, view(heat, i-1, :))
end
xs = 1:nsteps
ys = 1:length(p0)
hmap = heatmap!(ax, xs, ys, heat)
Colorbar(fig[1, 2], hmap; width = 15, ticksize = 15)
fig
end
# ╔═╡ ca0fb426-6214-4818-9db7-d7a57b2f9b7e
md"# Poker"
# ╔═╡ f0e60438-584c-476f-a832-3e59bc42010e
struct Game
die::Int
b1::Float64
b2::Float64
end
# ╔═╡ 5983efa0-5cf3-4fb5-abcd-5390a578e95d
game = Game(6, 2.5, 5.0)
# ╔═╡ 87d0ddbb-07d5-4f60-938a-0930478800e7
game.die
# ╔═╡ aa3a4673-f16e-4efc-910a-c94fa7e2939a
game.b1
# ╔═╡ 46d31d61-eb5a-47e5-8bb7-6c06bb31091a
# ╔═╡ 46d9aac7-18d2-4a04-8c15-dc83aa23b86f
function winner(dA, dB, df)
end
# ╔═╡ 49980be2-be66-49c9-a131-21d580dd2813
function play(
rng::AbstractRNG,
(; die, b1, b2)::Game,
pr1::Vector{Float64},
pc1::Vector{Float64},
pr2::Vector{Float64},
pc2::Vector{Float64},
nrounds::Int
)
if !(die == length(pr1) == length(pc1) == length(pr2) == length(pc2))
throw(ArgumentError("die and probability lengths must match"))
end
if !all(p -> 0 <= p <= 1, pr1) || !all(p -> 0 <= p <= 1, pc1) ||
!all(p -> 0 <= p <= 1, pr2) || !all(p -> 0 <= p <= 1, pc2)
throw(ArgumentError("Probabilities must take values between 0 and 1"))
end
# player A's profit == - player B's profit
pft = 0.0
for _ in 1:nrounds
dA = rand(rng, 1:die)
if rand(rng) <= pr1[dA] # A raises b1
dB = rand(rng, 1:die)
if rand(rng) <= pc1[dB] # B calls b1
if rand(rng) <= pr2[dB] # B raises b2
if rand(rng) <= pc2[dA] # A calls b2
pay = sign(dA - dB) * (b1 + b2 + 1.0)
else # A folds to b2 raise
pay = -(1.0 + b1)
end
else # B checks
pay = sign(dA - dB) * (b1 + 1.0)
end
else # B folds to b1 raise
pay = 1.0
end
else # A folds initially
pay = -0.5
end
pft += pay
end
return pft
end
# ╔═╡ d3378855-4ca5-4e82-9785-57ab9747ef8e
function eprofit((; die, b1, b2)::Game, pr1, pc1, pr2, pc2)
if !(die == length(pr1) == length(pc1) == length(pr2) == length(pc2))
throw(ArgumentError("die and probability lengths must match"))
end
pft = 0.0
for dA in 1:die
for dB in 1:die
s = sign(dA - dB) # =1 if A wins, -1 if B wins and 0 if tie
pft -= 0.5 * (1-pr1[dA]) # A folds initially
pft += 1.0 * pr1[dA] * (1-pc1[dB]) # B folds to b1 raise
# probability of getting to second betting round
ps2 = pr1[dA] * pc1[dB]
# B checks
pft += s * (b1 + 1.0) * ps2 * (1-pr2[dB])
# A folds to b2 raise
pft -= (1.0 + b1) * ps2 * pr2[dB] * (1-pc2[dA])
# A calls b2 raise
pft += s * (b1 + b2 + 1.0) * ps2 * pr2[dB] * pc2[dA]
end
end
return pft / die^2
end
# ╔═╡ c4bbf394-0811-4966-8488-7d3864d266f8
# grad points in direction of improving prfoit for A and B respectively,
# so both players want to change their strategies in the direction of grad
function gradprofit!(
∇pr1, ∇pc1, ∇pr2, ∇pc2,
(; die, b1, b2)::Game,
pr1, pc1, pr2, pc2
)
if !(die == length(pr1) == length(pc1) == length(pr2) == length(pc2)) ||
!(die == length(∇pr1) == length(∇pc1) == length(∇pr2) == length(∇pc2))
throw(ArgumentError("die, grad and probability lengths must match"))
end
fill!(∇pr1, 0.0)
fill!(∇pc1, 0.0)
fill!(∇pr2, 0.0)
fill!(∇pc2, 0.0)
for dA in 1:die
for dB in 1:die
s = sign(dA - dB) # =1 if A wins, -1 if B wins and 0 if tie
# pft -= 0.5 * (1-pr1[dA]) # A folds initially
∇pr1[dA] += 0.5
# pft += 1.0 * pr1[dA] * (1-pc1[dB]) # B folds to b1 raise
∇pr1[dA] += 1.0 * (1-pc1[dB])
∇pc1[dB] += 1.0 * pr1[dA]
# B checks
# pft += s * (b1 + 1.0) * pr1[dA] * pc1[dB] * (1-pr2[dB])
∇pr1[dA] += s * (b1 + 1.0) * pc1[dB] * (1-pr2[dB])
∇pc1[dB] -= s * (b1 + 1.0) * pr1[dA] * (1-pr2[dB])
∇pr2[dB] += s * (b1 + 1.0) * pr1[dA] * pc1[dB]
# A folds to b2 raise
# pft -= (1.0 + b1) * pr1[dA] * pc1[dB] * pr2[dB] * (1-pc2[dA])
∇pr1[dA] -= (1.0 + b1) * pc1[dB] * pr2[dB] * (1-pc2[dA])
∇pc1[dB] += (1.0 + b1) * pr1[dA] * pr2[dB] * (1-pc2[dA])
∇pr2[dB] += (1.0 + b1) * pr1[dA] * pc1[dB] * (1-pc2[dA])
∇pc2[dA] += (1.0 + b1) * pr1[dA] * pc1[dB] * pr2[dB]
# A calls b2 raise
# pft += s * (b1 + b2 + 1.0) * pr1[dA] * pc1[dB] * pr2[dB] * pc2[dA]
∇pr1[dA] += s * (b1 + b2 + 1.0) * pc1[dB] * pr2[dB] * pc2[dA]
∇pc1[dB] -= s * (b1 + b2 + 1.0) * pr1[dA] * pr2[dB] * pc2[dA]
∇pr2[dB] -= s * (b1 + b2 + 1.0) * pr1[dA] * pc1[dB] * pc2[dA]
∇pc2[dA] += s * (b1 + b2 + 1.0) * pr1[dA] * pc1[dB] * pr2[dB]
end
end
return inv(die^2) .* (∇pr1, ∇pc1, ∇pr2, ∇pc2)
end
# ╔═╡ 565575d7-4bf7-41a4-89d4-5d9a9e331f06
function gradprofit(game::Game, pr1, pc1, pr2, pc2)
∇pr1 = Vector{Float64}(undef, game.die)
∇pc1 = Vector{Float64}(undef, game.die)
∇pr2 = Vector{Float64}(undef, game.die)
∇pc2 = Vector{Float64}(undef, game.die)
gradprofit!(∇pr1, ∇pc1, ∇pr2, ∇pc2, game, pr1, pc1, pr2, pc2)
end
# ╔═╡ 47f410d9-9fac-437c-a273-72c52ca36236
function gradascent!(praise, pcall, N, bet, niter, rate)
rgrad = Vector{Float64}(undef, N)
cgrad = Vector{Float64}(undef, N)
for _ in niter
rgrad, ∇cgrad = gradprofit!(rgrad, cgrad, N, bet, praise, pcall)
praise .= clamp.(praise .+ rate .* rgrad, 0.0, 1.0)
pcall .= clamp.(pcall .+ rate .* cgrad, 0.0, 1.0)
end
praise, pcall
end
# ╔═╡ c5258501-01e5-4f7f-a408-ed54c7d4ce6a
begin
mypr1 = [0.0, 0.0, 0.0, 0.5, 1.0, 1.0]
mypc1 = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0]
mypr2 = [0.0, 0.0, 0.0, 1.0, 0.0, 1.0]
mypc2 = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0]
end
# ╔═╡ ddedae38-867a-4771-96c6-4d6953805955
let nrounds = 10_000_000
play(default_rng(), game, mypr1, mypc1, mypr2, mypc2, nrounds) / nrounds
end
# ╔═╡ f1330b02-b271-43fe-8c66-01773c3d4818
@profview play(default_rng(), game, mypr1, mypc1, mypr2, mypc2, 10_000_000)
# ╔═╡ f296db36-7ae6-4f70-a8de-c959daf32254
eprofit(game, mypr1, mypc1, mypr2, mypc2)
# ╔═╡ 315a94c7-2ba5-4ccd-bd24-bab1cfd12bc8
gradprofit(game, mypr1, mypc1, mypr2, mypc2)
# ╔═╡ ec17738d-2f28-42a1-b3f9-b231edb394c4
function optimise!(praise, pcall, N, bet, niter)
rgrad = Vector{Float64}(undef, N)
cgrad = Vector{Float64}(undef, N)
for _ in niter
∇rpft, ∇cpft = gradprofit(N, bet, praise, pcall)
for i in 1:N
∂pr = ∇rpft[i]
if ∂pr > 0.0
praise[i] = 1.0
elseif ∂pr < 0.0
praise[i] = 0.0
else
praise[i] = rand()
end
∂pc = ∇cpft[i]
if ∂pc > 0.0
pcall[i] = 1.0
elseif ∂pc < 0.0
pcall[i] = 0.0
else
# since grad is zero, any probability is equally good
pcall[i] = rand()
end
end
end
praise, pcall
end
# ╔═╡ 4fe533dc-3ccc-4a0c-b868-ac1b2bb014f9
optimise!(rand(2), rand(2), 2, 2.0, 20)
# ╔═╡ ce97e2ed-3d99-424b-92bd-99224bec7a5b
clamp(-2.0, 0.0, 1.5)
# ╔═╡ 824836d2-9d47-4ce4-ae96-8d3933381bce
gradascent!(rand(2), rand(2), 2, 2.0, 100_000, 10.0)
# ╔═╡ c4d79a40-7173-4fc7-8ea7-d1b95f88bbfd
fuzz(ps::Vector, fz) = ps .* (1 .- fz) .+ (1 .- ps) .* fz
# ╔═╡ bfcb7dd2-3d08-4eac-bd3c-40b4fbd71b82
fuzz(fill(0.4, 10), 0.2)
# ╔═╡ 83862c32-40e1-4bd3-89d6-8882d7b7ea1a
let N = 10, bet = 10.0, nrounds = 1_000_000
g = Game(N, bet)
pro, pco = optimise!(rand(N), rand(N), N, bet, 100)
prg, pcg = gradascent!(rand(N), rand(N), N, bet, 10_000, 100.0)
∇rpft, ∇cpft = gradprofit(N, bet, prg, pcg)
praise = prg
pcall = pco
gpft = play(g, praise, pcall, nrounds) ./ nrounds
epft = eprofit(N, bet, praise, pcall)
(
(praise, pcall),
(pro, pco),
(prg, pcg),
(∇rpft, ∇cpft),
gpft, epft
)
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
LsqFit = "2fda8390-95c7-5789-9bda-21331edee243"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
[compat]
CairoMakie = "~0.9.2"
Distributions = "~0.25.76"
LsqFit = "~0.13.0"
PlutoUI = "~0.7.48"
StatsBase = "~0.33.21"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.8.2"
manifest_format = "2.0"
project_hash = "9edc8ebdaf323159a2dd679a78c4ed43778fb7d5"
[[deps.AbstractFFTs]]
deps = ["ChainRulesCore", "LinearAlgebra"]
git-tree-sha1 = "69f7020bd72f069c219b5e8c236c1fa90d2cb409"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.2.1"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.AbstractTrees]]
git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.3.4"
[[deps.Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "195c5505521008abea5aee4f96930717958eac6f"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.4.0"
[[deps.Animations]]
deps = ["Colors"]
git-tree-sha1 = "e81c509d2c8e49592413bfb0bb3b08150056c79d"
uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340"
version = "0.4.1"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.ArrayInterfaceCore]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "c46fb7dd1d8ca1d213ba25848a5ec4e47a1a1b08"
uuid = "30b0a656-2188-435a-8636-2ec0e6a096e2"
version = "0.1.26"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Automa]]
deps = ["Printf", "ScanByte", "TranscodingStreams"]
git-tree-sha1 = "d50976f217489ce799e366d9561d56a98a30d7fe"
uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b"
version = "0.8.2"
[[deps.AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "66771c8d21c8ff5e3a93379480a2307ac36863f7"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.0.1"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[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.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.CairoMakie]]
deps = ["Base64", "Cairo", "Colors", "FFTW", "FileIO", "FreeType", "GeometryBasics", "LinearAlgebra", "Makie", "SHA", "SnoopPrecompile"]
git-tree-sha1 = "d5fcc28d94729c8828c7651e81d6b119fe9e87f5"
uuid = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
version = "0.9.2"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_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 = "e7ff6cadf743c098e08fca25c91103ee4303c9bb"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.15.6"
[[deps.ChangesOfVariables]]
deps = ["ChainRulesCore", "LinearAlgebra", "Test"]
git-tree-sha1 = "38f7a08f19d8810338d4f5085211c7dfa5d5bdd8"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.4"
[[deps.ColorBrewer]]
deps = ["Colors", "JSON", "Test"]
git-tree-sha1 = "61c5334f33d91e570e1d0c3eb5465835242582c4"
uuid = "a2cac450-b92f-5266-8821-25eda20663c8"
version = "0.4.0"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Random"]
git-tree-sha1 = "1fd869cc3875b57347f7027521f561cf46d1fcd8"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.19.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 = "d08c20eef1f2cbc6e60fd3612ac4340b89fea322"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.9"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["Dates", "LinearAlgebra", "UUIDs"]
git-tree-sha1 = "3ca828fe1b75fa84b021a7860bd039eaea84d2f2"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.3.0"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "0.5.2+0"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "fb21ddd70a051d882a1686a5a550990bbe371a95"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.4.1"
[[deps.Contour]]
git-tree-sha1 = "d05d9e7b7aedff4e5b51a029dced05cfb6125781"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.2"
[[deps.DataAPI]]
git-tree-sha1 = "46d2680e618f8abd007bce0c3026cb0c4a8f2032"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.12.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "d1fff3a548102f48987a52a2e0d114fa97d730f0"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.13"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DensityInterface]]
deps = ["InverseFunctions", "Test"]
git-tree-sha1 = "80c3e8639e3353e5d2912fb3a1916b8455e2494b"
uuid = "b429d917-457f-4dbc-8f4c-0cc954292b1d"
version = "0.4.0"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "8b7a4d23e22f5d44883671da70865ca98f2ebf9d"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.12.0"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.Distributions]]
deps = ["ChainRulesCore", "DensityInterface", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "Test"]
git-tree-sha1 = "04db820ebcfc1e053bd8cbb8d8bccf0ff3ead3f7"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.76"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "c36550cb29cbe373e95b3f40486b9a4148f89ffd"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.2"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.DualNumbers]]
deps = ["Calculus", "NaNMath", "SpecialFunctions"]
git-tree-sha1 = "5837a837389fccf076445fce071c8ddaea35a566"
uuid = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74"
version = "0.6.8"
[[deps.EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e3290f2d49e661fbd94046d7e3726ffcb2d41053"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.4+0"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "bad72f730e9e91c08d9427d5e8db95478a3c323d"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.4.8+0"
[[deps.Extents]]
git-tree-sha1 = "5e1e4c53fa39afe63a7d356e30452249365fba99"
uuid = "411431e0-e8b7-467b-b5e0-f676ba4f2910"
version = "0.1.1"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Pkg", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "74faea50c1d007c85837327f6775bea60b5492dd"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.2+2"
[[deps.FFTW]]
deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"]
git-tree-sha1 = "90630efff0894f8142308e334473eba54c433549"
uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341"
version = "1.5.0"
[[deps.FFTW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea"
uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a"
version = "3.3.10+0"
[[deps.FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "7be5f99f7d15578798f338f5433b6c432ea8037b"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.16.0"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"]