-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathca_system backup 1.jl
3508 lines (2980 loc) · 116 KB
/
ca_system backup 1.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.30
#> [[frontmatter.author]]
#> name = "Kishore Shenoy"
#> url = "kichappa.github.io"
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
# ╔═╡ 8bab643a-9618-4d04-ad1d-0cdd3963a630
# ╠═╡ show_logs = false
begin
ENV["PYTHON"] = ""
# Pkg.add(["Conda", "PyCall"])
# Pkg.build("PyCall")
using Conda, PyCall
Conda.add(["numpy"])
end
# ╔═╡ 9083379c-842e-4f7c-936f-1f9e66861af0
begin
using Plots
using PlutoPlotly
using OffsetArrays
using LaTeXStrings
using PlutoUI
using ColorTypes
using CUDA
CUDA.allowscalar(false)
using Random
using Printf
md"Just Importing libraries here..."
end
# ╔═╡ 4727903f-a54b-4d73-8998-fa99bb2481aa
md"# CA for Topography and Enemies"
# ╔═╡ c8c9a170-7cc7-4bb3-b9dc-1654f4c2cefd
begin
# code to display a 2D array as an image
function show_image(A, color_range=:viridis)
Plots.heatmap(1:size(A, 1), 1:size(A, 2), A, aspect_ratio=:equal, color=color_range, backend=:gr)
end
md"Defining show_image() that can plot the 2D version of our model."
end
# ╔═╡ d83db108-12df-4094-990d-474accf6e976
md"Max Threads, $(@bind max_threads NumberField(1:32, default=26))"
# ╔═╡ df27f8a4-f258-43b4-acdc-b8ea0f9ffc88
md"## Initial State"
# ╔═╡ e633b8e0-3774-462f-9d6e-1f586a17730a
md"Bush density, $(@bind b_density NumberField(1:100, default=9))"
# ╔═╡ e5c741d7-7c52-4097-8d02-89d76495d53f
function neighbour_sum(A, pos)
i, j=pos
neighbours = [[i-1,j],[i-1,j+1],[i,j+1],[i+1,j+1],[i+1,j],[i+1,j-1],[i,j-1],[i-1,j-1]]
sum=0
for neighbour in neighbours
i, j = neighbour
if(i>0 && i<=size(A, 1) && j>0 && j<=size(A, 2))
# println("A($i, $j)=")
# println("$(A[i, j])\n")
sum+=A[i,j]
end
end
return sum
end
# ╔═╡ 29fb1a62-86bf-4bab-bb7e-dbbfd5024917
function conway(A)
m, n = size(A)
B=copy(A)
# for t in 1:T
for i in 1:m
for j in 1:n
# life_decision = 0
# for di in -1:1, dj in -1:1
# i_n, j_n = i + di, j + dj
# if 1 <= i_n <= m && 1 <= j_n <= n && !(di==0 && dj===0)
# life_decision += A[i_n, j_n]
# end
# end
# if life_decision < 2 || life_decision > 3
# B[i, j] = 0
# elseif life_decision == 3
# B[i, j] = 1
# else
# B[i, j] = A[i, j]
# end
life_decision = neighbour_sum(A, [i,j])
if(life_decision < 2 || life_decision > 3)
B[i,j] = 0
elseif(life_decision === 3)
B[i,j]=1
else
B[i,j]=B[i,j]
end
end
end
# end
return B
end
# ╔═╡ fd3512a7-8d52-4d25-9ad8-0cc80555da7f
function kernel(A, B, m, n)
i = threadIdx().x + (blockIdx().x - 1) * blockDim().x
j = threadIdx().y + (blockIdx().y - 1) * blockDim().y
if i <= m && j <= n
# B[i,j]=A[i, j]
life_decision = 0
for di in -1:1, dj in -1:1
i_n, j_n = i + di, j + dj
if 1 <= i_n <= m && 1 <= j_n <= n && !(di==0 && dj===0)
life_decision += A[i_n, j_n]
end
end
if life_decision < 2 || life_decision > 3
B[i, j] = 0
elseif life_decision == 3
B[i, j] = 1
else
B[i, j] = A[i, j]
end
end
return
end
# ╔═╡ 2a3753d3-c08c-4e85-907e-9ebb5a67dab3
function conway_gpu(A)
m, n = size(A)
A = CuArray(A)
B = similar(A) # Create a GPU array of the same size and type as A
threads_x = min(max_threads, m) # Limit to max_threads threads in the x dimension
threads_y = min(max_threads, n) # Limit to max_threads threads in the y dimension
blocks_x = ceil(Int, m / threads_x)
blocks_y = ceil(Int, n / threads_y)
@cuda threads=(threads_x, threads_y) blocks=(blocks_x, blocks_y) kernel(A, B, m, n)
return collect(B)
end
# ╔═╡ 8327cfec-51df-4c38-839a-b7212ddb24e7
md"``X_{\max}, Y_{\max}``, L = $(@bind L NumberField(0:100; default=100))"
# ╔═╡ 701891a4-6a87-427e-af9b-487dec1dee4d
md"Time of simulation, ``T_{\text{max}}``"
# ╔═╡ 4ec0a200-78df-4cfd-9efe-105dad6f4ef3
function encode_agent(agent_pos, B)
B_out = copy(B)
x, y = agent_pos
B_out[x, y] = 2
return B_out
end
# ╔═╡ fffa26a7-ecf6-4be0-ab7c-423665caf7a5
md"## Topography"
# ╔═╡ 72a7cb99-5483-4c82-9554-007c2ba44413
md"Number of height points, $(@bind altPs NumberField(0:100; default=7))"
# ╔═╡ cd4ee775-74d9-417f-9c97-6c8d321d7580
md"Max height, $(@bind max_height NumberField(0:100; default=L/10))"
# ╔═╡ ba6660df-59b7-4c70-b30f-b8548d63b0d2
begin
function alt_kernel(A, B, m, n, alt_p, k, power)
i = threadIdx().x + (blockIdx().x - 1) * blockDim().x
j = threadIdx().y + (blockIdx().y - 1) * blockDim().y
if i <= m && j <= n
B[i, j] = 0
norm = 0
for ki in 1:k
d = ((alt_p[ki, 2] - i)^2 + (alt_p[ki, 1] - j)^2)^0.5
if (d > 0)
B[i,j] += alt_p[ki, 3]/d^power
norm += 1/d^power
else
B[i,j] = alt_p[ki, 3]
return
end
end
B[i, j] /= norm
end
return
end
function topography_gpu(A, alt_p, power)
m, n = size(A)
k, _ = size(alt_p)
A_gpu = CuArray(A)
B = similar(A_gpu) # Create a GPU array of the same size and type as A
if !isnothing(max_threads)
if !isnothing(m)
threads_x = min(max_threads, m)
else
threads_x = max_threads
end
else
if !isnothing(m)
threads_x = min(32, m)
else
threads_x = 26
end
end
if !isnothing(max_threads)
if !isnothing(n)
threads_y = min(max_threads, n)
else
threads_y = max_threads
end
else
if !isnothing(n)
threads_y = min(32, n)
else
threads_y = 26
end
end
# threads_x = min(max_threads, m) # Limit to max_threads threads in the x dimension
# threads_y = min(max_threads, n) # Limit to max_threads threads in the y dimension
blocks_x = ceil(Int, m / threads_x)
blocks_y = ceil(Int, n / threads_y)
@cuda threads=(threads_x, threads_y) blocks=(blocks_x, blocks_y) alt_kernel(A_gpu, B, m, n, CuArray(alt_p), k, power)
return collect(B)
end
md"Kernel and Method to generate Topography"
end
# ╔═╡ 82d0e800-deb1-42fe-b1d3-2018d8639ff8
md"neighbourhood radius, `n_radius` $(@bind n_radius NumberField(0:1000; default=3))"
# ╔═╡ 8f0937f0-813b-4256-a8b9-afb22e092a42
md"Topography of the system"
# ╔═╡ 6d4076dc-68c8-42f8-a43e-222e3410bdbf
md"Topography contour"
# ╔═╡ 11f7bf70-4a39-451c-9bdb-9369742dcce0
md"Random Seed, $(@bind seed NumberField(0:1000, default=758))"
# ╔═╡ cb6482b5-c003-4ad2-8d8b-a60f3946b255
md"Power to raise the distance to control point... $(@bind power NumberField(0:1000; default=3))"
# ╔═╡ 9a877efd-b3cc-4d7e-ae9a-89d2e8a53356
md"Topography superposed with vegetation looks like this"
# ╔═╡ 08c8c238-8a24-4743-aed5-0e2649758b61
md"### Slopes"
# ╔═╡ 81653527-a1fb-49ab-99db-5fdda6b669fd
md"""exploration radius, `e_radius = ` $(@bind e_radius NumberField(0:1000; default=3))"""
# ╔═╡ c8171ca3-c2d7-4220-b073-1ec76f559b25
md"""
The taylor series expansion of $f(x+h)$ at $h=0$ is,
$$f(x+h)=\frac{1}{24} h^4 f^{(4)}(x)+\frac{1}{6} h^3 f^{(3)}(x)+\frac{1}{2} h^2 f''(x)+h f'(x)+f(x)+O\left(h^5\right)$$
We can calculate the slope, $f'(x)$, at $x$ in the following manner,
$$\frac{f(x+h)-f(x-h)}{2 h} = f'(x)+\frac{1}{6} h^2 f^{(3)}(x)+O\left(h^4\right)$$
This is accurate with an error term $\propto h^2$. To improve, we use a neighbourhood of radius 2. That is, we use the fact that,
$$\frac{f(x+2h)-f(x-2 h)}{4 h}=f'(x)+\frac{2}{3} h^2 f^{(3)}(x)+O\left(h^4\right)$$
Like so,
$$\frac{1}{3} \left(4\cdot\frac{f(x+h)-f(x-h)}{2 h}-\frac{f(x+2h)-f(x-2 h)}{4 h}\right)=f'(x)-\frac{1}{30} h^4 f^{(5)}(x)+O\left(h^5\right)$$
"""
# ╔═╡ 15f17206-db9f-4896-9e32-93d025501917
begin
function slope_kernel(A, Bx, By, m, n)
i = threadIdx().x + (blockIdx().x - 1) * blockDim().x
j = threadIdx().y + (blockIdx().y - 1) * blockDim().y
if 3 <= i <= m-2 && 3 <= j <= n-2
# caluclate second order approximation of differential
xph = A[i+1,j]
xmh = A[i-1,j]
xp2h = A[i+2,j]
xm2h = A[i-2,j]
yph = A[i,j+1]
ymh = A[i,j-1]
yp2h = A[i,j+2]
ym2h = A[i,j-2]
dfbydx = 1/3*(4*(xph-xmh)/2 - (xp2h-xm2h)/4)
dfbydy = 1/3*(4*(yph-ymh)/2 - (yp2h-ym2h)/4)
# B[i, j] = atan(dfbydy, dfbydx)
norm = (dfbydx^2+dfbydy^2)^0.5
Bx[j, i] = dfbydy/norm
By[j, i] = dfbydx/norm
elseif 2 <= i <= m-1 && 2 <= j <= n-1
xph = A[i+1,j]
xmh = A[i-1,j]
yph = A[i,j+1]
ymh = A[i,j-1]
dfbydx = (xph-xmh)/2
dfbydy = (yph-ymh)/2
# B[j, i] = atan(dfbydy, dfbydx)
norm = (dfbydx^2+dfbydy^2)^0.5
Bx[j, i] = dfbydy/norm
By[j, i] = dfbydx/norm
elseif 1 <= i <= m && 1 <= j <= n
Bx[j, i] = 0.0
By[j, i] = 0.0
end
return
end
function slope_gpu(topo)
m, n = size(topo)
# println("Sizes of m, n = ", m, " ",n)
topo_gpu = CuArray(topo)
outp = fill((0.0, 0.0), n, n)
output_x = CuArray(fill(0.0, n, n))
output_y = CuArray(fill(0.0, n, n))
if !isnothing(max_threads)
if !isnothing(m)
threads_x = min(max_threads, m)
else
threads_x = max_threads
end
else
if !isnothing(m)
threads_x = min(32, m)
else
threads_x = 26
end
end
if !isnothing(max_threads)
if !isnothing(n)
threads_y = min(max_threads, n)
else
threads_y = max_threads
end
else
if !isnothing(n)
threads_y = min(32, n)
else
threads_y = 26
end
end
# threads_x = min(max_threads, m) # Limit to max_threads threads in the x dimension
# threads_y = min(max_threads, n) # Limit to max_threads threads in the y dimension
blocks_x = ceil(Int, m / threads_x)
blocks_y = ceil(Int, n / threads_y)
@cuda threads=(threads_x, threads_y) blocks=(blocks_x, blocks_y) slope_kernel(topo_gpu, output_x, output_y, m, n)
return collect(output_x), collect(output_y)
end
md"Kernel and method to generate topography slopes using central differences"
end
# ╔═╡ 73014c35-ab99-47e2-bfcb-9076c0720bdf
md"## Enemies & Hill Climb... racing?"
# ╔═╡ daf19ff1-0012-4b12-b61f-1d9517178bf5
md"Let's first see how we can make our model realistically traverse the topography.
Since it's unlikely that a troop can climb any slope, we will try to make them move in the direction with the max feasible slope.
Let's deal with the following question: Should they do a random walk or should there be an \"ulterior\" motive? Time to explore!
What will a random walk look like?"
# ╔═╡ 5b8de4a5-f6d7-407a-8709-4e0d392e21b9
md"Set climbable slope to... $(@bind max_slope NumberField(1:10, default=7))%"
# ╔═╡ e9055da6-3c24-4fe9-919c-1040916c79c3
md"Let there be... $(@bind n_enem NumberField(1:10, default=5)) enemy clusters"
# ╔═╡ 477ae165-07d6-4a64-8ce4-8c4b4c25011e
begin
function neighbourhoods(radius, inc=0)
n = []
for r in 0:radius
for i in 0:r
if (inc!==0 || r !== 0)
if(i !== 0)
push!(n, [-i, abs(r-i)], [i, abs(r-i)])
if (r-i !== 0)
push!(n, [-i, -abs(r-i)], [i, -abs(r-i)])
end
else
push!(n, [i, abs(r-i)])
if (r-i !== 0)
push!(n, [i, -abs(r-i)])
end
end
end
end
end
return n
end
md"Definition of neighbourhood function that returns a von neumann neighbourhood set"
end
# ╔═╡ 1add5389-3a8b-40b7-b999-8df22bb45900
begin
function topo_bush_kernel(topo, bushes, out, m, n)
i = threadIdx().x + (blockIdx().x - 1) * blockDim().x
j = threadIdx().y + (blockIdx().y - 1) * blockDim().y
if 1 <= i <= m && 1 <= j <= n
out[i, j] = topo[i,j] + bushes[i,j]*1
end
return
end
function topo_bush_gpu(topo, bushes, enemies=nothing, preceedEnemies=false)
m, n = size(topo)
# println(topo)
# println("Sizes of m, n = ", m, " ",n)
# println(min(max_threads, m))
topo_gpu = CuArray(topo)
bushes_gpu = CuArray(bushes)
output_gpu = similar(topo_gpu)
if !isnothing(max_threads)
if !isnothing(m)
threads_x = min(max_threads, m)
else
threads_x = max_threads
end
else
if !isnothing(m)
threads_x = min(32, m)
else
threads_x = 26
end
end
if !isnothing(max_threads)
if !isnothing(n)
threads_y = min(max_threads, n)
else
threads_y = max_threads
end
else
if !isnothing(n)
threads_y = min(32, n)
else
threads_y = 26
end
end
blocks_x = ceil(Int, m / threads_x)
blocks_y = ceil(Int, n / threads_y)
@cuda threads=(threads_x, threads_y) blocks=(blocks_x, blocks_y) topo_bush_kernel(topo_gpu, bushes_gpu, output_gpu, m, n)
output = collect(output_gpu)
if !isnothing(enemies) && preceedEnemies
enemies_m, _ = size(enemies)
for e in 1:enemies_m
for nh in neighbourhoods(enemies[e, 3] * Int(n/L), 1)
Y, X = enemies[e, 1] * Int(n/L) + nh[1], enemies[e, 2] * Int(n/L) + nh[2]
output[X, Y] = topo[X, Y]
end
end
end
return output
end
md"Kernel and GPU handler for superposing bushes onto the topography"
end
# ╔═╡ 86078a29-e2a6-470b-8757-b2efe2bf9eb8
md"Let's attempt to plot the enemies just like how we plotted bushes"
# ╔═╡ c0bc8f94-9636-461a-9b34-fe0ccfefcb69
md"That doesn't look so great now, does it?
Let's plot the agents along with the bushes in a more beautiful manner. Green represents bushes and white for enemies."
# ╔═╡ 924c9d77-af8c-44b7-9053-b48aae4ad475
ENV["JULIA_CUDA_DEBUG"] = "2"
# ╔═╡ 9f30ffe2-6546-480b-a89d-0f557469e82d
begin
function color_kernel(colors_A_gpu, alt_p_gpu, A_gpu, enemiesInA_gpu, m, n, max_height, power)
i = threadIdx().x + (blockIdx().x - 1) * blockDim().x
j = threadIdx().y + (blockIdx().y - 1) * blockDim().y
if 1 <= i <= m && 1 <= j <= n
colors_A_gpu[i, j]=0.0
alt_ps_m, _ = size(alt_p_gpu)
norm = 0
if (enemiesInA_gpu[j, i]!=0)
colors_A_gpu[i, j] = max_height+10
elseif(A_gpu[i, j]!=0)
colors_A_gpu[i, j] = -10
else
flag = 1
for k in 1:alt_ps_m
d = ((alt_p_gpu[k, 2] - i)^2 + (alt_p_gpu[k, 1] - j)^2)^0.5
if (d > 0 && flag==1)
colors_A_gpu[i, j] += alt_p_gpu[k, 3]/d^power
norm += 1/d^power
else
colors_A_gpu[i, j] = alt_p_gpu[k, 3]
flag = 0
end
end
if(flag==1)
colors_A_gpu[i, j] /= norm
end
end
end
return
end
function color_gpu(alt_p, A, enemiesInA, max_height, power)
m, n = size(A)
alt_p_gpu = CuArray(alt_p)
A_gpu = CuArray(A)
colors_A_gpu = similar(A_gpu)
enemiesInA_gpu = CuArray(enemiesInA)
threads_x = min(max_threads, m) # Limit to max_threads threads in the x dimension
threads_y = min(max_threads, n) # Limit to max_threads threads in the y dimension
blocks_x = ceil(Int, m / threads_x)
blocks_y = ceil(Int, n / threads_y)
@cuda threads=(threads_x, threads_y) blocks=(blocks_x, blocks_y) color_kernel(colors_A_gpu, alt_p_gpu, A_gpu, enemiesInA_gpu, m, n, max_height, power)
return collect(colors_A_gpu)
end
end
# ╔═╡ a077d240-36e0-41cd-a4ff-f7e0ca62ca4e
md"Let's follow a \"gradient ascend\" method where the clusters just follow the direction with maximum ascend in hopes of reaching the peak."
# ╔═╡ 2fe91b37-1c3f-49ce-bfa2-702a180b78a0
begin
md"``X``, ``Y`` subdivisions, ``n`` = $(@bind n NumberField(0:100; default=100))"
end
# ╔═╡ 4167489e-715b-4e62-8e56-3f2cd1317ccd
begin
Random.seed!(seed)
# sample code for a 2D array
A_L = rand(Float64, L, L) .< (b_density/100)
A = zeros(n, n)
for i in 1:n
for j in 1:n
A[i, j] = A_L[Int(ceil(i/(n/L))), Int(ceil(j/(n/L)))]
end
end
# use show_image to display the array A
show_image(A)
# show_image(A, [(0,0,0), (1,1,1)])
end
# ╔═╡ 0f344406-4816-4cd6-ae8e-83a8b918fa11
function next_pos(current_pos, B, seed)
i, j=current_pos
# # println("Seed = $seed")
# # Random.seed!(seed)
# d = rand(-1:1, (2,1))
# println("d=$d")
# println("x0, y0= $(current_pos)")
# x, y=current_pos+d
# println("Old x, y= $([x, y])")
neighbors = [[-1,0],[0-1,0+1],[0,0+1],[0+1,0+1],[0+1,0],[0+1,0-1],[0,0-1],[0-1,0-1]]
direction = [0, 0]
for neighbor in neighbors
i_n, j_n = neighbor
direction += B[i_n+i, j_n+j]*[i_n, j_n]
end
# println("Direction=$direction")
direction[1] = sign(direction[1])*ceil(abs(direction[1])/8)
direction[2] = sign(direction[2])*ceil(abs(direction[2])/8)
direction = 1 * direction
# println("NormDirection=$direction")
if direction[1]==0 && direction[2]==0
direction = rand(-1:1, (2,1))
end
x = i + direction[1]
y = j + direction[2]
x=min(max(x, 1), n)
y=min(max(y, 1), n)
# println("New x, y= $([x, y])")
return [x, y]
end
# ╔═╡ 0f0779fa-d610-429f-acd3-ac82b7842b14
begin
Random.seed!(seed)
alt_pos = rand(1:n, (altPs,2));
alt_h = rand(Float64, (altPs,1))*max_height;
hcat(alt_pos, alt_h)
alt_p = hcat(alt_pos, alt_h);
md"Generating random control points..."
end
# ╔═╡ b1538261-175d-4892-ab3d-2963f239b8df
alt_p
# ╔═╡ 8532f267-7e5f-45bb-8d82-6f86cfff7cc4
begin
topo = zeros(Float64, n, n);
topo = topography_gpu(topo, alt_p, power)
md"Let's define the topography using the control points"
# plotly()
# show_image(topo, :grays)
end
# ╔═╡ be20aaf3-473e-4be5-adcc-3db9eb3de213
begin
Random.seed!(seed)
enem_pos = rand(1:L, (n_enem,2));
enem_z = [topo[row[1], row[2]] for row in eachrow(enem_pos)]
# enem_T = fill(1.0, (n_enem,1)) # temperature
enem_r = rand(1:3, (n_enem,1));
enemies = hcat(enem_pos, enem_r);
md"Generating random enemy clusters. The look like so..."
end
# ╔═╡ cb0bb5cd-a02b-457d-b47a-be623e8d50ed
enemies
# ╔═╡ 1036ebbb-a16e-4674-b786-9aa9325b0090
enemies
# ╔═╡ 12351738-ddd3-4051-8880-504ecff343af
begin
plotly()
Plots.plot(1:n, 1:n,topo, st=:surface, ratio=1, zlim=[0,L], xlim=[0,n], ylim=[0,n],xlabel="X", ylabel="Y", zlabel="Z")
end
# ╔═╡ 3750d105-df07-4af7-9143-82b065fbb041
begin
plotly()
Plots.contour(1:n, 1:n,topo, levels=60, xlim=[0,n], ylim=[0,n], ratio=1, fill=true)
end
# ╔═╡ 230af3ed-9267-497c-a697-e422bcf04665
begin
dx, dy = slope_gpu(topo);
slope = [(dx[i, j], dy[i, j]) for i in 1:n, j in 1:n];
md"Calculating the slope with a double central difference method"
end
# ╔═╡ c2a9fa1f-a405-4767-aec2-42196a70cc61
begin
using DelimitedFiles;
writedlm("slope.txt", slope);
md"Let's write the slopes into a txt file for debugging"
end
# ╔═╡ 8a586d49-86c9-4f7f-b438-15ba8181ed2c
begin
x_coordinates = [el[1] for el in slope];
y_coordinates = [el[2] for el in slope];
quiver(transpose(repeat(reshape(1:n, 1, n), n, 1)),repeat(reshape(1:n, 1, n), n, 1), quiver=( x_coordinates, y_coordinates), arrow_size=1,ratio=1, zlim=[0,L], xlim=[0,n], ylim=[0,n])
end
# ╔═╡ a22d6084-18ed-4f71-886d-2ffc40ce599f
begin
function gen_e_in_A(enemies, n, L)
enemiesInA = zeros(n, n)
r = Int(n/L)
for e in 1:size(enemies)[1]
for nh in neighbourhoods(enemies[e, 3] * r, 1)
enemiesInA[
enemies[e, 1] * r + nh[1],
enemies[e, 2] * r + nh[2]
] = 1
end
end
return enemiesInA
end
function gen_a_in_A(agents, n, L)
agentsInA = zeros(n, n)
r = Int(n/L)
# for a in 1:size(agents)[1]
# for ii in 1: r
# for jj in 1:r
# if(1<= (agents[a, 2]-1)*r+ii <= n) && (1<= (agents[a, 3]-1)*r+jj <= n)
# agentsInA[(agents[a, 2]-1)*r+ii, (agents[a, 3]-1)*r+jj] = 1
# end
# end
# end
# end
for a in 1:size(agents)[1]
for nh in neighbourhoods(1 * r, 1)
if (1<=(agents[a, 2] * r + nh[1])<= n)&&(1<=(agents[a, 3] * r + nh[2])<= n)
agentsInA[
agents[a, 2] * r + nh[1],
agents[a, 3] * r + nh[2]
] = 1
end
end
end
return agentsInA
end
enemiesInA = gen_e_in_A(enemies, n, L)
function color(i, j, alt_ps, A, enemiesInA)
z=0.0
m, _ = size(alt_ps)
norm = 0
if (enemiesInA[i, j]!=0)
return max_height+10
elseif(A[j, i]!=0)
return -10
end
for k in 1:m
d = ((alt_ps[k, 1] - i)^2 + (alt_ps[k, 2] - j)^2)^0.5
if (d > 0)
z += alt_ps[k, 3]/d^power
norm += 1/d^power
else
z = alt_ps[k, 3]
return z
end
end
z /= norm
# println(typeof(z))
return z
end
min_v = 10/(max_height+20)
max_v = (max_height+10)/(max_height+20)
custom_colorscale = [
(0.00, "#3bff00"), # Green
(min_v - 0.000000001, "#3bff00"), # Green
(min_v, "#222224"), # Blue
(min_v + 1*(max_v-min_v)/5, "#3E2163"), # Blue
(min_v + 2*(max_v-min_v)/5, "#88236A"),# Yellow
(min_v + 3*(max_v-min_v)/5, "#D04544"),# Yellow
(min_v + 4*(max_v-min_v)/5, "#F78D1E"),# Yellow
(max_v - 0.000000001, "#F1E760"),# Yellow
(max_v, "#ffffff"), # Blue
(1.00, "#ffffff"), # Blue
]
function colors_alias(x, y)
return color(x, y, alt_p, A, enemiesInA)
end
x = 1:n
y = 1:n
# Plots.surface(x = x, y = y, topo_bush_gpu(topo, A, enemies, true), colorscale=custom_colorscale, surfacecolor = colors_alias.(x', y), ratio=1, zlim=[0,L], xlim=[0,n], ylim=[0,n], xlabel="X", ylabel="Y", zlabel="Z", showscale=false)
end
# ╔═╡ 84bc9a37-dce3-40cf-85ae-b9107339aabe
Plots.contour(1:n, 1:n,topo, levels=60, ratio=1, xlim=[0,n], ylim=[0,n], fill=true, showscale=false)
# ╔═╡ 6f603c0b-b852-473f-9099-b6292ad395b9
enemies
# ╔═╡ 076eb88e-fa80-40a0-9873-74329bf9b5a5
md"Clock $(@bind t2 Clock())"
# ╔═╡ 18b40b26-9338-4616-8deb-1a5c9a6a7ae8
md"## Python for Agents"
# ╔═╡ 1cd0c84c-2cca-4251-b718-822477ab0b31
md"Let's import python things"
# ╔═╡ 5d68976b-cacd-4ac5-88e2-b669e2a29490
begin
py"""
import numpy as np
class Agent:
def __init__(self, unique_id, x, y, view_sight, gather_sight, env_len, type_='agent'):
self.unique_id = unique_id
self.x = x # new position
self.y = y # new position
self.prevx = -1 # one step previous position
self.prevy = -1
#self.pattern_index = 0
# self.type_ = type_
self.view = view_sight
self.gather = gather_sight
self.env = None
self.env_len = env_len # length of environment
self.new_enemy = list() # for newly discovered enemies
self.enemies_seen = list() # for already analized enemies
self.bushes = list()
self.target = 0 # flag is agent is following an enemy
self.target_id = None # id of the enemy follwing
self.target_dist = -1
self.target_x = ""
self.target_y = ""
self.move_x = ""
self.move_y = ""
self.enemy_end_1 = None
self.enemy_end_2 = None
def deterministic_search(self): # "deterministic" movement of the agents
# eight possible moves are there
possible_moves = [
(self.x + 1, self.y), # movement to the right
(self.x + 1, self.y + 1),
(self.x + 1, self.y - 1),
(self.x - 1, self.y), # movement to the left
(self.x - 1, self.y + 1),
(self.x - 1, self.y - 1),
(self.x, self.y + 1), # movement in y-direction only
(self.x, self.y - 1)
]
# Filter out moves that go outside the environment boundaries
valid_moves = [
(x, y) for x, y in possible_moves[self.pattern_index] if 0 <= x < self.env_len and 0 <= y < self.env_len
]
# Filter out moves that correspond to bushes (since bushes are not in enemy camps)
valid_moves = [move for move in valid_moves if move not in self.bushes]
# Update the pattern index for the next move
self.pattern_index = (self.pattern_index + 1) % len(possible_moves)
# Return the first valid move if any, otherwise stay in the current position
return valid_moves[0] if valid_moves else (self.x, self.y)
def random_search(self, seed): # "stochastic" movement of the agents
# eight possible moves are there
np.random.seed(seed=seed)
possible_moves = [
(self.x + 1, self.y), # movement to the right
(self.x + 1, self.y + 1),
(self.x + 1, self.y - 1),
(self.x - 1, self.y), # movement to the left
(self.x - 1, self.y + 1),
(self.x - 1, self.y - 1),
(self.x, self.y + 1), # movement in y-direction only
(self.x, self.y - 1)
]
# Filter out moves that go outside the environment boundaries
valid_moves = [(x, y) for x, y in possible_moves if 0 <= x < self.env_len and 0 <= y < self.env_len]
# Filter out moves that correspond to bushes (since bushes are not in enemy-camps)
valid_moves = [move for move in valid_moves if move not in self.bushes]
lmoves = len(valid_moves)
if lmoves == 0:
return (self.x, self.y)
rng = np.random.randint(0, lmoves)
return valid_moves[rng]
def get_enemy_cells(self):
id = self.target_id
cell_list = []
topy = max(0, self.y-self.view)
boty = min(self.env_len, self.y+self.view+1)
leftx = max(0, self.x-self.view)
rightx = min(self.env_len, self.x+self.view+1)
for i in range(topy, boty):
for j in range(leftx, rightx):
if (self.env[i][j][0] == 2): # change with enemy label in environment
if self.env[i][j][1] == id:
cell_list.append((i, j))
return cell_list
def get_enemy_distance(self, cell_list):
min_dist = 4*self.view
min_eu_dist = 4*self.view
ei, ej = -1, -1
for loc in cell_list:
(i, j) = loc
min_eu_dist = min(min_eu_dist, abs(self.x-i)+abs(self.y-j))
if min_dist > max(abs(self.x-i), abs(self.y-j) ):
min_dist = max(abs(self.x-i), abs(self.y-j) )
ei, ej = i,j
return [min_dist, min_eu_dist, ei,ej]
def is_in_limit(self, pos, radius):
(pi, pj) = pos
if(pi<self.x-radius or pi>self.x+radius or pj<self.y-radius or pj>self.y+radius):
return False
return True
def approach_direction(self, pos, move_x, move_y):
(pi, pj) = pos
# should also add another condition to check if the bush is adjacent to an enemy
# better to avoid such bush
if (move_x=="" and move_y=="up"):
if (pj>self.y):
return True
else:
return False
if (move_x=="" and move_y=="down"):
if (pj<self.y):
return True
else:
return False
if (move_x=="right" and move_y==""):
if (pi>self.x):
return True
else:
return False
if (move_x=="left" and move_y==""):
if (pi<self.x):
return True
else:
return False
if (move_x=="right" and move_y=="up"):
if (pi>=self.x and pj>=self.y):
return True
else:
return False
if (move_x=="right" and move_y=="down"):
if (pi>=self.x and pj<=self.y):
return True
else:
return False
if (move_x=="left" and move_y=="up"):
if (pi<=self.x and pj>=self.y):
return True
else:
return False
if (move_x=="left" and move_y=="down"):
if (pi<=self.x and pj<=self.y):
return True
else:
return False
return False
def set_corner(self, ci, cj, label):
if(label==1):
if(self.enemy_end_1 is not None):
if(abs(self.y-cj)<abs(self.y-self.enemy_end_1[1])):
self.enemy_end_1 = (ci, cj)
else:
self.enemy_end_1 = (ci, cj)
else:
if(self.enemy_end_2 is not None):
if(abs(self.x-ci)<abs(self.x-self.enemy_end_1[0])):
self.enemy_end_2 = (ci, cj)
else:
self.enemy_end_2 = (ci, cj)
def check_corner(self):
for i in range(max(0,self.x-self.gather), min(self.env_len, self.x+self.gather+1)):
for j in range(max(0,self.y-self.gather), min(self.env_len, self.y+self.gather+1)):
if self.env[i][j][0] == 2 and self.env[i][j][1] == self.target_id:
if(i==0 or i==self.env_len-1):
self.set_corner(i,j,label=2)
if(j==0 or j==self.env_len-1):
self.set_corner(i,j,label=1)
if(self.env[i-1][j][0] != 2 and self.env[i+1][j][0] != 2 and self.env[i][j-1][0] != 2):
self.set_corner(i,j,label=1)
if(self.env[i-1][j][0] != 2 and self.env[i+1][j][0] != 2 and self.env[i][j+1][0] != 2):
self.set_corner(i,j,label=1)
if(self.env[i-1][j][0] != 2 and self.env[i][j-1][0] != 2 and self.env[i][j+1][0] != 2):
self.set_corner(i,j,label=2)
if(self.env[i+1][j][0] != 2 and self.env[i][j+1][0] != 2 and self.env[i][j-1][0] != 2):
self.set_corner(i,j,label=2)
def strategic_search(self, seed):
# Implement a search function when the enemy is detected
# Will implement the spliting of the searching agent team
# may need to define a new class
np.random.seed(seed=seed)