Skip to content

Instantly share code, notes, and snippets.

@sdwfrost
Last active August 29, 2015 13:56
Show Gist options
  • Save sdwfrost/9093551 to your computer and use it in GitHub Desktop.
Save sdwfrost/9093551 to your computer and use it in GitHub Desktop.
An example of an SIR epidemiological model in Agentscript
<html>
<head>
<title>SIR Model</title>
<script src="http://agentscript.org/lib/agentscript.js"></script>
<script src="http://agentscript.org/tools/coffee-script.js"></script>
<script type="text/coffeescript">
u = ABM.util # ABM.util alias, u.s is also ABM.shapes accessor.
log = (arg) -> console.log arg
class MyModel extends ABM.Model
setVision: (@vision) -> @patches.cacheRect @vision, true
setup: -> # called by Model.constructor
u.randomSeed()
@population = 100
@nums = 99
@numi = 1
@numr = 0
@size = 1.0 # size in patch coords
@speed = .1 # move forward this amount in patch coords
@wiggle = u.degToRad(30) # degrees/radians to wiggle
@startCircle = false # initialize agents randomly or in circle
@setVision 3
@agents.setDefault "size", @size
# @agents.setUseSprites()
@anim.setRate 30, false
for p in @patches
p.color = [0,0,0]
for a in @agents.create @population
a.shape = "person"
a.state = "S"
if @startCircle
a.forward @patches.maxX/2 # start in circle
else
a.setXY @patches.randomPt()... # set random location
@agents[0].state = "I"
for a in @agents
if a.state is "I"
a.color=[255,0,0]
else
a.color=[0,0,255]
step: -> # called by Model.animate
@updateAgents(a) for a in @agents
updateAgents: (a) -> # a is agent
if a.state is "S"
neighbours = @agents.inRadius a, @vision
if neighbours.length isnt 0
[nearestNeighbour, d] = u.minOneOf neighbours, ((f) -> f.distance a), true
if nearestNeighbour.state is "I"
@infectAgent(a)
else
if a.state is "I"
if u.randomFloat(1.0) < 0.01
@recoverAgent(a)
a.rotate u.randomCentered @wiggle
a.forward @speed
infectAgent: (a) -> # a is agent
a.state="I"
a.color=[255,0,0]
@nums--
@numi++
log "#{@nums} #{@numi} #{@numr}"
recoverAgent: (a) -> # a is agent
a.state="R"
a.color=[0,255,0]
@numi--
@numr++
log "#{@nums} #{@numi} #{@numr}"
model = new MyModel("layers", 13, -16, 16, -16, 16, true, false)
.debug()
.start()
</script>
</head>
<body>
<div id="layers"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment