Agent-based modelling, Konstanz, 2024
30 April 2024
LearningEnvironment:VariationalLearners interacting:P1 and P2 now need to be represented inside the learner:Write three functions:
speak(x::VariationalLearner): takes a variational learner as argument and returns a string uttered by the learnerlearn!(x::VariationalLearner, s::String): makes variational learner x learn from string sinteract!(x::VariationalLearner, y::VariationalLearner): makes x utter a string and y learn from that stringAnswer (learn!)
function learn!(x::VariationalLearner, s::String)
g = sample(["G1", "G2"], Weights([x.p, 1 - x.p]))
if g == "G1" && s != "S2"
x.p = x.p + x.gamma * (1 - x.p)
elseif g == "G1" && s == "S2"
x.p = x.p - x.gamma * x.p
elseif g == "G2" && s != "S1"
x.p = x.p - x.gamma * x.p
elseif g == "G2" && s == "S1"
x.p = x.p + x.gamma * (1 - x.p)
end
return x.p
endlearn! (generic function with 1 method)
rand() without arguments returns a random float between 0 and 1rand(x) with argument x returns a random element of xpop, then we can use rand(pop) to pick a random agentfor loopsfor loop is used to repeat a code block a number of timesfor loop and the functions we defined above, it is now very easy to iterate or evolve a population of agents:Write the same thing using an array comprehension instead of a for loop.
Answer
pop = [VariationalLearner(0.1, 0.01, 0.4, 0.1) for i in 1:1000]
[interact!(rand(pop), rand(pop)) for t in 1:100]100-element Vector{Float64}:
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
⋮
0.09801
0.099
0.10900000000000001
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099
0.099