;; The buffalo herding and hunting model
;; Peter M. Roy - Ver 1.0 - pete@iems.nwu.edu
;; ************ Extends Wolf-Sheep Predation & Flocking models (Wilensky, U., 1998) ************
;; Last Update: 20 Jan 2003

;; Change - 20 Jan 2003 - CH001
;; Returned beast shape to default because they were difficult to see when grass was on.
;; Created - 19 Jan 2003
;; All code



;; Declare some global variables to store data
globals 
[ 
    ticks         ;; A counter for the time elapsed in our world
    hunted        ;; Number of buffalo hunted by hyena
    gored         ;; Number of hyenas killed by buffalo 
    escapes       ;; Number of missed hyena-deaths due to presence of another hyena
    flock-profit  ;; Number of missed buffalo-deaths due to presence of flock
    
    ;; The next three variables will hold the maximum turn angles possible for the three flocking rules.
    max-align-turn        
    max-cohere-turn       
    max-separate-turn     
]
 
breeds [ buffalo hyena ]         ;; The species in the model world

turtles-own 
[ 
    energy         ;; All species of turtles have energy
]

buffalo-own             ;; some special characteristics of buffalo
[ 
    grabbed?           ;; Logical counter to prevent 2 different hyena from eating same buffalo
    flockmates         ;; Agentset of nearby buffaloes
    nearest-neighbor   ;; Closest buffalo in flockmates set
]  

patches-own 
[ 
    countdown         ;; for regrown grass
]

to setup 
    ca  
        ;; limitations on the turn
        set max-align-turn 45        
        set max-separate-turn 45
        set max-cohere-turn 45
    ask patches [ set pcolor green ]        ;; a nice green background
    if grass? 
    [
        ask patches 
        [
            set countdown random grass-delay ;; initialize grass grow clocks randomly
            set pcolor 50 + (random 9)    ;; 10 different levels of grass
        ]
    ]

;; Change # CH001 - commented out three lines

;;    ;; set the shapes of both to beast. 
;;    set-default-shape buffalo "beast"    
;;    set-default-shape hyena "beast"

;; End change CH001

    ;; Create buffalo and set their characteristics
    create-custom-buffalo init-buffalo  
    [ 
        set color brown            
        set label-color blue                             ;; Color for the plot
        set energy random (2 * buffalo-metabolism)       
        setxy random ceiling ( screen-size-x / 4 ) random ceiling ( screen-size-y / 4 )         ;; Put the flock in a concentrated area to begin with
        set grabbed? false
    ] 
    ;; Create hyena and set their characteristics   
    create-custom-hyena init-hyena  
    [ 
        set color orange           
        set energy random (2 * hyena-metabolism)
        setxy random screen-size-x random screen-size-y
    ]
    display-labels
    do-plot
end                ;; setup proc ends

to go
    ask buffalo 
    [
        buffalo-move            ;; execute the buffalo-move proc
        if grass? 
        [
            set energy energy - 1  ;; deduct energy for buffalo only if grass? switch is on
            eat-grass
        ]
        reproduce-buffalo       ;; execute the proc that controls buffalo reproduction
        death                   
    ] 
    ask hyena
    [
        hyena-move            ;; hyena-movement (random)
        set energy energy - 1 ;; hyena lose energy as they move
        catch-buffalo         ;; the proc for hunting
        reproduce-hyena       ;; execute the proc that controls hyena reproduction
        death  
    ]
    if grass? 
    [ 
        ask patches [ grow-grass ]  
    ]
    do-plot  ;; update the population plot
    every 0.5        
        [ display-labels ]
    set ticks ticks + 1
    if not any turtles [ stop ]            ;; no point in continuing if all die out. 
end

to buffalo-move  ;; buffalo procedure
    flock       ;; flock proc
end

to hyena-move  ;; hyena procedure
        rt random 360.0        ;; pick an orientation
        fd 1                   ;; go forward
end


to eat-grass  ;; buffalo procedure
    ;; buffalo eat grass, affect the patch color
    if pcolor > 50 
    [ 
        set pcolor pcolor - 1  
        set energy energy + buffalo-metabolism  ;; buffalo gain energy by eating
    ] 
end

to reproduce-buffalo  ;; buffalo procedure
    if random 100 < buffalo-reproduce     ;; throw "dice" to see if you will reproduce
    [  
        set energy (energy / 2)          ;; divide energy between parent and offspring
        hatch 1                         ;; hatch an offspring and move it forward 1 step
        [ 
            rt random 360 
            fd 1 
        ]   
    ]
end
 
to reproduce-hyena  ;; hyena procedure
    if random 100 < hyena-reproduce 
    [                              ;; throw "dice" to see if you will reproduce
        set energy (energy / 2 )  ;; divide energy between parent and offspring
        hatch 1 
        [ 
            rt random 360 
            fd 1 
        ]  ;; hatch an offspring and move it forward 1 step
    ]
end

to catch-buffalo  ;; hyena procedure
    locals [prey]
    set prey random-one-of buffalo-here             ;; grab a random buffalo
                           with [not grabbed?]  ;; that no one else is grabbing
    if prey != nobody                             ;; did we get one?    
    [ 
        ifelse count neighbors with [any turtles-here with [breed = buffalo ] ] > 4
        [        ;; hyena is outnumbered by at least 8 buffalo in his immediate neighborhood
            set flock-profit (flock-profit + 1) ;; update counter
            ifelse count neighbors with [ any turtles-here with [breed = hyena ] ] < 2
            [    ;; hyena has no other hyena backing up his attack
                    set gored (gored + 1)    ;; update the counter
                    die            ;;    hyena gored to death because outnumbered by buffalo
            ]
            [    ;; hyena has backup
                set escapes (escapes + 1)    ;; do nothing - hyena escapes because it has other hyena for support, but cannot hunt buffalo in such high concentration
            ]
        ]        
        [        ;; hyena can hunt
            set grabbed?-of prey true                 ;; prevent other hyena from grabbing it
            ask prey [ die ]                          ;; kill it
            set hunted (hunted + 1)                    ;; update the counter
            set energy energy + hyena-metabolism      ;; get energy from eating
        ]
    ]
end

to death  ;; turtle procedure
  ;; when energy dips below zero, die
  if energy < 0 [ die ] 
end

to grow-grass  ;; patch procedure
    ;; IMPROV: Rewrite this for shades of green.
    ;; countdown on brown patches, if reach 0, grow some grass
    if pcolor < 59 [ 
    ifelse countdown <= 0
      [ set pcolor pcolor + 1 
        set countdown grass-delay ] 
      [ set countdown (countdown - 1) ] 
  ] 
end

to do-plot 
    set-current-plot "populations"
    set-current-plot-pen "buffalo" 
    plot count buffalo
    set-current-plot-pen "hyena"
    plot count hyena
    if grass? 
    [
        set-current-plot-pen "grass / 4"
        plot count patches with [ pcolor = green ] / 4  ;;
    ]
    set-current-plot-pen "gored"
    plot gored
end

to display-labels
  ifelse show-energy?
  [
    ifelse grass?
    [
      ask turtles
      [ set label round energy ]
    ]
    [
      ask hyena
      [ set label round energy ]
      ask buffalo
      [ set label no-label ]
    ]
  ]
  [
    ask turtles
    [ set label no-label ]
  ]
end

;; ----------- begin the flocking control procedures --------------------

to flock  ;; buffalo procedure
    find-flockmates
    if any flockmates
        [ 
            find-nearest-neighbor 
            ifelse distance nearest-neighbor < minimum-separation
                [ 
                    separate 
                ]
                [ 
                    align
                    cohere 
                ]
        ]
    fd 1
end

to find-flockmates  ;; buffalo procedure
      set flockmates (buffalo in-radius vision) with [who != who-of myself]        ;; all I can see except myself
end

to find-nearest-neighbor ;; buffalo procedure
    set nearest-neighbor min-one-of flockmates [distance myself]    ;; pick nearest neighbor of among  flockmates
end

;;; SEPARATE

to separate  ;; buffalo procedure
    turn-away (heading-of nearest-neighbor) max-separate-turn    ;; turn away from where my nearest neighbor is heading, if I am too close to him
end

;;; ALIGN

to align  ;; buffalo procedure
    turn-towards average-flockmate-heading max-align-turn        ;; turn to the average of the herd
end

to-report average-flockmate-heading  ;; buffalo procedure
  ;; We can't just average the heading variables here.
  ;; For example, the average of 1 and 359 should be 0,
  ;; not 180.  So we have to use trigonometry.
  report atan mean values-from flockmates [sin heading]
              mean values-from flockmates [cos heading]
end

;;; COHERE

to cohere  ;; buffalo procedure
  turn-towards average-heading-towards-flockmates max-cohere-turn
end

to-report average-heading-towards-flockmates  ;; buffalo procedure
  ;; "towards myself" gives us the heading from the other buffalo
  ;; to me, but we want the heading from me to the other buffalo,
  ;; so we add 180
  report atan mean values-from flockmates [sin (towards myself + 180)]
              mean values-from flockmates [cos (towards myself + 180)]
end

;;; HELPER PROCEDURES

to turn-towards [new-heading max-turn]  ;; buffalo procedure
  turn-at-most (subtract-headings new-heading heading) max-turn
end

to turn-away [new-heading max-turn]  ;; buffalo procedure
  turn-at-most (subtract-headings heading new-heading) max-turn
end

;; turn right by "turn" degrees (left if "turn" is negative),
;; but never turn more than "max-turn" degrees
to turn-at-most [turn max-turn]  ;; buffalo procedure
  ifelse abs turn > max-turn
    [ ifelse turn > 0
        [ rt max-turn ]
        [ lt max-turn ] ]
    [ rt turn ]
end

;; To find the difference between two headings, we can't just
;; subtract the numbers, because 0 and 360 are the same heading.
;; For example, the difference between a heading of 5 degrees
;; and a heading of 355 degrees is 10 degrees, not 350 degrees.
to-report subtract-headings [h1 h2]
  ifelse abs (h1 - h2) <= 180
    [ report h1 - h2 ]
    [ ifelse h1 > h2
        [ report h1 - h2 - 360 ]
        [ report h1 - h2 + 360 ] ]
end

;; ---------------------- end flocking bit ------------------------- ;;

; ***NetLogo Model Copyright Notice***

; This model was created as part of the project: CONNECTED MATHEMATICS:
; MAKING SENSE OF COMPLEX PHENOMENA THROUGH BUILDING OBJECT-BASED PARALLEL
; MODELS (OBPML).  The project gratefully acknowledges the support of the
; National Science Foundation (Applications of Advanced Technologies
; Program) -- grant numbers RED #9552950 and REC #9632612.

; Copyright 1998 by Uri Wilensky. All rights reserved.
; Converted from StarLogoT to NetLogo, 2000.

; Permission to use, modify or redistribute this model is hereby granted,
; provided that both of the following requirements are followed:
; a) this copyright notice is included.
; b) this model will not be redistributed for profit without permission
;    from Uri Wilensky.
; Contact Uri Wilensky for appropriate licenses for redistribution for
; profit.

; To refer to this model in academic publications, please use:
; Wilensky, U. (1998).  NetLogo Wolf  Predation model.
; http://ccl.northwestern.edu/netlogo/models/WolfSheepPredation.
; Center for Connected Learning and Computer-Based Modeling,
; Northwestern University, Evanston, IL.

; ***NetLogo Model Copyright Notice***
@#$#@#$#@
GRAPHICS-WINDOW
449
10
941
502
20
20
12.0
1
10
0
0

CC-WINDOW
210
10
349
71
Command Center

SLIDER
16
125
179
158
init-buffalo
init-buffalo
0
250
110
1
1
NIL

SLIDER
16
160
179
193
buffalo-metabolism
buffalo-metabolism
0.0
50.0
1.0
1.0
1
NIL

SLIDER
16
195
179
228
buffalo-reproduce
buffalo-reproduce
1.0
20.0
5.0
1.0
1
NIL

SLIDER
200
98
354
131
init-hyena
init-hyena
0
250
49
1
1
NIL

SLIDER
200
134
354
167
hyena-metabolism
hyena-metabolism
0.0
100.0
83.0
1.0
1
NIL

SLIDER
200
170
354
203
hyena-reproduce
hyena-reproduce
0.0
20.0
5.0
1.0
1
NIL

SWITCH
52
262
146
295
grass?
grass?
0
1
-1000

SLIDER
149
262
361
295
grass-delay
grass-delay
0
100
30
1
1
NIL

BUTTON
374
10
443
43
setup
setup
NIL
1
T
OBSERVER

BUTTON
374
81
441
114
go
go
T
1
T
OBSERVER

PLOT
24
306
325
503
populations
time
pop.
0.0
100.0
0.0
100.0
true
true
PENS
"grass / 4" 1.0 0 -11352576 true
"buffalo" 1.0 0 -6524078 true
"hyena" 1.0 0 -44544 true
"gored" 1.0 0 -65536 true

MONITOR
366
233
442
282
buffalo
count buffalo
3
1

MONITOR
366
177
441
226
hyena
count hyena
3
1

MONITOR
366
122
442
171
grass / 4
count patches with [ pcolor > 50 ] / 4
0
1

TEXTBOX
63
104
154
123
Buffalo settings

TEXTBOX
228
80
341
98
Hyena settings

TEXTBOX
138
244
228
262
Grass settings

MONITOR
368
439
441
488
ticks
ticks
0
1

SWITCH
200
205
354
238
show-energy?
show-energy?
1
1
-1000

SLIDER
18
64
185
97
minimum-separation
minimum-separation
0
8
1.0
0.1
1
NIL

SLIDER
18
29
186
62
vision
vision
0
10.0
0.0
3.0
1
NIL

MONITOR
366
337
441
386
# gored
gored
0
1

MONITOR
367
285
441
334
#hunted
hunted
0
1

BUTTON
374
45
442
78
step
go
NIL
1
T
OBSERVER

MONITOR
336
388
441
437
Flocking Benefit
flock-profit
0
1

TEXTBOX
53
10
165
28
Flocking Controls

@#$#@#$#@
Predation Model with Flocking behavior (v 1.0) 

WHAT IS IT? 
-----------
This model extends (Wilensky, U. (1998).  NetLogo Wolf Sheep Predation model) to explore the stability of predator-prey ecosystems. Such systems are called unstable when they tend to result in extinction for one or more species involved.  In contrast, systems are stable when they tend to maintain themselves over time, despite fluctuations in population sizes. The basic Predation Model had two major variants, one in which the grazing rate of the prey (sheep) was considered and another where it was not. 

Realistically, preyed animals tend to exhibit flocking behavior as a defense against predators. This is especially true for middle-to-large sized animals where there is greater safety in numbers. (Nishimura, 1998) refers to a number of such scenarios, in particular quoting examples of Canadian musk oxen and African eland. Flocking behavior is modeled using (Wilensky, U. (1998), Flocking model)

( In version 1.0 of the model )Like the wolf-sheep predation model, this model presents two variants - the behavior with grazing rate considered and that without. 

HOW TO USE IT 
-------------
1. (For version 1.0)Set the GRASS? switch to TRUE to include grass in the model, or to FALSE to only include hyena (orange) and buffalo (brown).
2. Adjust the slider parameters (see below), or use the default settings.
3. Press the SETUP button.
4. Press the GO button to begin the simulation.
5. View the POPULATIONS plot to watch the populations fluctuate over time
6. Various monitors give output values.

Parameters:
INIT-BUFFALO : The initial size of buffalo population 
INIT-HYENA : The initial size of hyena population
(For version 1.0) BUFFALO-METABOLISM: The amount of energy buffalo get for every grass patch eaten
HYENA-METABOLISM: The amount of energy hyena get for every buffalo eaten
BUFFALO-REPRODUCE: The probability of a buffalo reproducing at each time step
HYENA-REPRODUCE: The probability of a hyena reproducing at each time step
(For version 1.0)GRASS?: Whether or not to include grass in the model
(For version 1.0)GRASS-DELAY: How long it takes for grass to regrow once it is eaten

Notes:
- one unit of energy is deducted for every step a hyena takes
- when grass is included, one unit of energy is deducted for every step a buffalo takes

ffTHINGS TO NOTICE 
----------------
* Relative population fluctuation.
* Flocking behavior of buffalo.

THINGS TO TRY
------------- 
* Adjusting the slider for minimum-separation affects the density of the flock. 
* Ajusting the vision affects. Vision = 0, is as good as no flocking. 
* Turn the grass on and off. 


EXTENDING THE MODEL
-------------------
* Hyena extinction is more due to decreased probability of finding prey. Hyena should hunt smarter. 
* Min-separation can be made to vary dynamically with the population (low population - tighter flocks due to perceived threat of extinction).

CREDITS AND REFERENCES
----------------------
Wilensky, U. (1998), NetLogo Wolf Sheep Predation model.
Wilensky, U. (1998), Flocking model
Nishimura,S. and Ikegami, T. (1998), Emergence of Collective Strategies in a Prey-Predator Game Model
@#$#@#$#@
default
true
0
Polygon -7566196 true true 150 5 40 250 150 205 260 250

sheep-shape
false
15
Rectangle -1 true true 90 75 270 225
Circle -1 true true 15 75 150
Rectangle -16777216 true false 81 225 134 286
Rectangle -16777216 true false 180 225 238 285
Circle -16777216 true false 1 88 92

wolf-shape
false
0
Rectangle -7566196 true true 15 105 105 165
Rectangle -7566196 true true 45 90 105 105
Polygon -7566196 true true 60 90 83 44 104 90
Polygon -16777216 true false 67 90 82 59 97 89
Rectangle -1 true false 48 93 59 105
Rectangle -16777216 true false 51 96 55 101
Rectangle -16777216 true false 0 121 15 135
Rectangle -16777216 true false 15 136 60 151
Polygon -1 true false 15 136 23 149 31 136
Polygon -1 true false 30 151 37 136 43 151
Rectangle -7566196 true true 105 120 263 195
Rectangle -7566196 true true 108 195 259 201
Rectangle -7566196 true true 114 201 252 210
Rectangle -7566196 true true 120 210 243 214
Rectangle -7566196 true true 115 114 255 120
Rectangle -7566196 true true 128 108 248 114
Rectangle -7566196 true true 150 105 225 108
Rectangle -7566196 true true 132 214 155 270
Rectangle -7566196 true true 110 260 132 270
Rectangle -7566196 true true 210 214 232 270
Rectangle -7566196 true true 189 260 210 270
Line -7566196 true 263 127 281 155
Line -7566196 true 281 155 281 192

beast
true
0
Rectangle -7566196 true true 102 81 195 222
Circle -7566196 true true 116 14 68
Rectangle -7566196 true true 77 90 101 104
Rectangle -7566196 true true 197 91 224 104
Rectangle -7566196 true true 196 196 224 208
Rectangle -7566196 true true 77 194 101 209

@#$#@#$#@
NetLogo 1.1 (Rev F)
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
