extensions [gis matrix profiler csv]

globals [
zones-dataset land-cover pop-density npp market                      ;; GIS datasets (FEWS livelihood zones, ESA-CCI land cover, GridPop, Simulated Npp,
county pa grain npp_new                                              ;; County Sape file Kenya, Cell-size, Output raster name
;max_cat max_cam                                                     ;; Max stocking density for cattle and camel when HSI = 1
PA_patch                                                             ;; A variable related to setting up PA access scenarios
cat_age cat_wt_age cam_age cam_wt_age
sh_age sh_wt_age gt_age gt_wt_age
cat-breed cat-milk                                                   ;; Breeding and milking schedule for cattle
shoat-breed shoat-milk                                               ;; Breeding and milking schedule for shoats
cam-breed cam-milk                                                   ;; Breeding and milking schedule for camels
;cat_energy cam_energy sh_energy gt_energy                            ;; Energy content in MJ of 1 kg of forage consumed by livestock species
cat-rep-rate sht-rep-rate cam-rep-rate                               ;; Monthly reporductive probability for cattle, shoats and camel
m_harvest                                                            ;; maize harvest calendar
cat_pool sh_pool gt_pool cam_pool                                    ;; Preference for a biomass pool relative to other livestock species
TLU                                                                  ;; Livestock specific TLU values [catttle sheep goat camel]
ca_calf_dr cam_calf_dr sh_lambs_dr gt_kids_dr                        ;; Death rate for calves (cattle, camel) , lambs and kids
hh_ae mem_calreq                                                     ;; Adult equivalents, Calorie requirements for each age-sex class
milk_prod meat_prod_cat cam_milk_prod shoat_milk_prod                ;; Monthly milk and meat production by cattle camel and shoats
opportunistic_slaughter                                              ;; Monthly probability that a steer will be slaughtered
milk_cal_cow milk_cal_cam milk_cal_gt milk_cal_sh                    ;; Calories from cattle, camel, goat and sheep
meat_cal non-maize_cal maize_cal sug_cal                             ;; calories from meat, non-maize sources, maize and sugar
income_catcam income_shoat                                           ;; Sources of income
exp_food exp_gen exp_vet                                             ;; Sources of expenses
cattle-total camel-total sheep-total goat-total                      ;; Population sizes, of cattle, camel , sheep and goats
drop-outs  hungry                                                    ;; Total number of households in each month, that have lost all assets (livestock)
hungry_turk hungry_bar hungry_wp hungry_sam  hungry_isi  hungry_lai hungry_mar hungry_man  hungry_waj hungry_gar hungry_tr  hungry_lam hungry_kaj hungry_nar
R month m_days                                                       ;; Total number of months to simulate; variable converting ticks to months
cat-dr cam-dr sh-dr gt-dr]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

breed [hholds hhold]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

patches-own [
Kenya zone  cov  den  p_prop protect   ;; patches in Kenya, livelihood zone id, landcover category patch human density
tribe mark  nomad                      ;; County id stand in for tribe id , market access, proportion nomadic in the patch
cattle sheep goat camel farm           ;; Mean number of cattle, sheep, goat and camel within livelihood zones; Is patch a farming area or not.
HSI_herb HSI_browse stock_den cam_den  ;; Habitat suitability for livestock, habitat suitability of a patch based on browse availability, stocking density based on HSI,
CAT-T cam-T                            ;; Counter for total number of cattle and camel on patch
forage_cat forage_browse               ;; Total available forage for cattle and sheep and total available browse for goats and camels
cat-per-pools sh-per-pools            ;; The fraction of each biomass pool available to each species weighted by TLU and biomass preferences
gt-per-pools cam-per-pools             ;;  These four lists are calculated each month based on changing compositions of
cons browse_cons                       ;; Counter for forage consumed by cattle and sheep (cons) and goat and camels (browse_cons)
percap_forage percap_browse            ;; Per capita browse available to each livestock species ; cattle and sheep (percap_forage) camel and goats (percap_browse)
cattle-forage sheep-forage
goat-forage camel-forage
percap_cattle percap_shp               ;; Forage available per head of cattle and sheep on each patch
percap_cam percap_gt                   ;; Forage available per head of camel and goats on each patch
cons_cat cons_sh cons_cam cons_gt      ;; Forage consumed each month on each patch by each species
green_herb dead_herb                   ;; Green and dead herb biomass from Lrange
green_shrub dead_shrub shrub_brnch     ;; Green, dead and branch biomass for shrubs from LRange
green_tree dead_tree tree_brnch        ;; Green, shrub and branch biomass for trees from LRange
greenH deadH greenS deadS brnchS       ;; Holding variables for different biomass pools from L-Range
greenT deadT brnchT                    ;; These are used for tracking changes in biomass and calculating fraction forage grazed.
liv_prop camels                        ;; The fraction of total herbivore biomass on a patch that is made up of livestock (from Ogutu et al ., 2018)
hunger                                 ;; Proportion of households on patch that are food deficient



]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

hholds-own [

nonsed occ agrop                                                         ;; nomadic status, occupation, agropastoralist
hm_patch my-tribe                                                        ;; Patch where houseolds are located at the start of ths simulaton and where they should return in the monsoon season
past_type move-stat grazing_land                                         ;;Type of pastoralist (spliiter or non-splitter); Pasture where splitter herds graze
move-cost                                                                ;; Cost associated with movement
;cat gt shp cam                                                          ;; matrix holding cattle,shoat and camel age-sex classes

cam_aM cam_aF cam-tot cam_aM_wt cam_aF_wt                                ;; camel holding variables : number of maes, females, total, wts of males and females
cam_aF_ag cam_aM_ag cam_fem_lact                                         ;; Ages of males and females, id of lactating females
cam_calves cam_calves_ag cam_tot_wt                                      ;; Total calves, calf age and total camel wt
dead-camF dead-camM camel-owner                                          ;; Counter for dead camels; Identifier if household traditionally holds camels


ca_calves ca_calves_ag ca_aF ca_aM cat-tot                               ;; Cattle holdings variables (# calves,post weaning individuals (ca_af, ca_am), total cattle
ca_aF_wt ca_aM_wt ca_tot_wt  fem_lact                                    ;; Cattle wt  tracker for each age-sex class except calves. id of lactating ind
ca_aF_ag ca_aM_ag dead-caF dead-caM                                      ;; Cattle age tracker for each age-sex class; Counter for dead cattle


sh_r sh_e sh-tot sh_r_wt sh_e_wt                                         ;; Sheep holding variables: Number of rams, ewes, total sheep, weights of classes
sh_r_ag sh_e_ag sh_fem_lact                                              ;; Ram and Ewe age, id of lactating ewes
sh_lambs sh_lambs_ag sh_tot_wt dead-she dead-shr                         ;; Total number of lambs, ages and total wt of sheep; counter for dead sheep

gt_b gt_d gt-tot gt_b_wt gt_d_wt                                         ;; Goat holding variables: Number of bucks, kids, total goats, wts of bucks and does
gt_b_ag gt_d_ag gt_fem_lact                                              ;; Ages of bucks and does, id of lactating does
gt_kids gt_kids_ag gt_tot_wt                                             ;; Total number of kids, age of kids, total wt of goats; counter for dead goats
dead-gtb dead-gtd

p_under5 p_6to12 m_13to17 m_older17 f_13to17 f_older17  hh_mem  AE       ;; Household composition (# of individuals in each age-sex class);List of hhold members; Total adult equivalents
hh_tot h_quant
cow-milk cow-meat cal_meat cal_milk tot_calreq_month                     ;; Cow milk and meat production, calories from meat and milk
cal_maize maize food_sufficiency sufficiency-source hunger-stat          ;; Calories in hhold from maize, Maize available at home Food sufficiency category ("Deficient" "Sufficient")
camel-milk sh-milk gt-milk    cal-source                                 ;; Milk from camel, sheep and goat
cash_in_hand maize_purchased                                                             ;; Disposable income with hhold
labour business ag_land  base_income                                     ;; Indicator of whether household engages in labour; business; land owned in ha by pastoral hholds; base monthly income
cal_needs  dead-meat   store_cal  liv_cal                                       ;; Total calorie needs of household; total meat from dead animals; Indicator of purchased calories
dead-meat-ca dead-meat-cam dead-meat-gt dead-meat-sh                     ;; Dead meat from each livestock species
economic_state  assets                                                   ;; Household debt status and Indicator of availability of livestock assets (0 / assetless)
family                                                                   ;; List of households that constitute a social network for a home
TLU-owned  TLU-cap                                                       ;; Livestock owned in TLU
temp_given temp_recieved temp_gift_given temp_gift_recieved              ;; Is milk / gifts given and received between families in a month
gift_given gift_recieved sell                                            ;; Indicator of whether livestock was gifted or sold
milk_recieved milk_given milk_sold                                       ;; Indicator of whether gfit was received or given , milk sold
temp_past_status                                                         ;; Temporary indicator to determine if household has made a movement decision
hh-cam-tot hh-cat-tot hh-cat-lam hh-cam-lam                              ;; A running tally of household camel and cattle holdings
risk  raid-loss raid-tribe                                                          ;; Indicator of whether household is exposed to risk from other ethnic groups
sales_ca purchases_ca sales_cam purchases_cam sales_sht purchases_sht    ;; An indicator of sale and purchase of each livestock species
sales_ca_m purchases_ca_m sales_cam_m purchases_cam_m sales_sht_m        ;; A monthly counter of sales and purchases by households
purchases_sht_m sale_income
reborn                                                                   ;; A household that is assetless is provided some livestock and reenters the simulation
ca_s_tot ca_p_tot cam_s_tot cam_p_tot sht_s_tot sht_p_tot                ;; Total sales and purchases of livestock by each hhold over the course of the simulation
selection
cat_m  cam_m sh_m gt_m
liv_sales_income milk_inc
cal_ava maize_cons
cal_needs1 cal_needs2 cal_needs3
]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to setup
 clear-all
 ;profiler:start
 load-layers
 load-parms
 load-households
 ;spin-hholds
 set R 12 * years  ; Years is set using a sliding scale in the interface
 reset-ticks

end


to set-spin
 spin-hholds

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to go
  while [not file-exists? read-from-string bio_out] [wait 1]
  wait 5
  if ticks = R [
    stop
  ]

  reset-hholds     ;; Households that are assetless at the end of the previous month are collected and provided some livestock to reenter the simulation.
  load-forage      ;; Bring input from LRange, calculate habitat suitability
  find-pasture     ;; Make decisions to move depending on stockign density
  ;find-pasture-sedentary-scenario
  deplete-patch    ;; animals forage and deplete biomass on patch.
  grow-herd        ;; Based on froage consumed, weight gain is calculated and body condition scores determiend which determine  monthly survival probabilities
  produce          ;; Livestock reprodcue and produce milk and meat in appropriate months
  calorie-counter  ;; Determine if calorie needs are being met and classify households as Deficient or sufficient
  cash-flow        ;; Tallying of income, expenses, and sales of livestock
  exchange-stock   ;; Goats are exchanged for cattle if herb availability is high.
  gifting          ;; Social interactions maong households pertaining to gifting of livestock and milk.
  wrap-up          ;; Generate summaries and output files.
  ;print-output     ;; write output to csv
  tick
  ;  ]

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  to load-layers

  ; Note that setting the coordinate system here is optional, as
  ; long as all of the datasets use the same coordinate system.
  ;gis:load-coordinate-system "esa_lc.prj"



  ; Load all spatial datasets
  ;; Load the ESA_CCI land cover dataset for eastern Africa with 10 land cover classes
  set land-cover gis:load-dataset "esa_lc.asc"
  ;; import the gridded population of the world layer..densities will determine distribution of households; This is the population density for the year 2000
  set pop-density gis:load-dataset "pop00.asc"
  ;;Load livelihood zones shape files
  set zones-dataset gis:load-dataset "Lzones_pro.shp" ;; FEWS livelihood zones shapefile with associated zone-spcific attribute table
  ;; Load the market access dataset. Here market access
  set market gis:load-dataset "market_aoi.asc"
  ;; Load the Kenya counties dataset- County boundaries used to define rules of conlflict and cooperation
  set county gis:load-dataset "KE_Admin1_dat.shp"

  ;; Load the protected areas dataset
  set pa gis:load-dataset "eastAF_protected_pro.shp"


  ;; Set the world envelope to the union of all of our dataset's (except pa) envelopes

  resize-world 0 gis:width-of land-cover - 1 0 gis:height-of land-cover - 1 ;; This ensure that the number of patches match those on the input raster layers

  gis:set-world-envelope-ds (gis:envelope-union-of (gis:envelope-of land-cover)
                              (gis:envelope-of pop-density)
                               (gis:envelope-of zones-dataset)
                                (gis:envelope-of county)
                                 (gis:envelope-of market))

;; Determine the patch size from the land cover  .asc files

file-open "esa_lc.asc"
repeat 4 [let skip file-read-line]  ; ignore the first four lines
let ignore file-read-characters 8   ; ignore character string preceding the grain value
set grain file-read  ;;;
file-close
 ;; Display datasets

; Display land-cover datasets
  gis:apply-raster land-cover cov
  let min-cov  1 ;;gis:minimum-of land-cover
  let max-cov 10;;gis:maximum-of land-cover
  ask patches[if(cov > -9999)[
      set pcolor scale-color brown cov min-cov max-cov]]
;0 No data
;1 Trees cover areas
;2 Shrubs cover areas
;3 Grassland
;4 Cropland
;5 Vegetation aquatic or regularly flooded
;6 Lichen Mosses / Sparse vegetation
;7 Bare areas
;8 Built up areas
;9 Snow and/or Ice
;10 Open water

;;; Load and plot pop density dataset

 gis:apply-raster pop-density den
  ; To display population density
  ;let min-den gis:minimum-of pop-density
  ;let max-den gis:maximum-of pop-density
  ;ask patches[
  ;  if (den > -9999)
  ;    [set pcolor scale-color brown den min-den max-den]
  ;]


  ;; Assign attributes to patches depending on the zone they lie in
   ;let i 1
   foreach gis:feature-list-of zones-dataset [feature ->
    ask patches gis:intersecting feature [
      set cattle gis:property-value feature "cattle"      ; Mean number of cattle per household
      set sheep gis:property-value feature "sheep"        ; Mean number of sheep per household
      set goat gis:property-value feature "goats"         ; Mean number of goats per household
      set camel gis:property-value feature "camel"        ; Mean number of camel per household
      set zone gis:property-value feature "LZCODE"        ; zone id
      set farm gis:property-value feature "Crop_sales"    ; Crop sales -  Binary variable divides zones into farming and pastoral areas
      set nomad gis:property-value feature "nomads" ]      ; Proportion of nomads in the llhood zone
     ;set i i + 1
 ]

;; Assign county identity to each patch
;; Display county dataset
  gis:set-drawing-color yellow
  gis:draw county 1
   foreach gis:feature-list-of county [feature ->
    ask patches gis:intersecting feature [
      set tribe gis:property-value feature "ADMIN1"      ; The county name is associated with each patch as a tribe identity
      set liv_prop  (gis:property-value feature "liv_prop") ; Proportion of cattle in herbivore population in county
      ;set camels (gis:property-value feature "camel")   ; Proportion camel
      set p_prop (gis:property-value feature "Past_p")  ; Proportion of pastoral people in county
    ]

 ]


;; Plot protected area dataset
  ask patches [set protect 0]
  gis:set-drawing-color green
  gis:fill pa 1
 foreach gis:feature-list-of pa [feature ->
    ask patches gis:intersecting feature [
      set protect gis:property-value feature "PA"      ; The protection status associated with a patch is set
        ]
      ]


  ;; Assign livestock proportions to patches without data. Set this at 0.8

  ask patches with [liv_prop = 0] [set liv_prop 0.8]

;; Assign Kenya identity to each patch; This is so that we can restrict model to Kenya
  ask patches gis:intersecting zones-dataset [set Kenya 1] ; demarcate what patches are within Kenya

; Apply market datasets
 gis:apply-raster market mark  ; Read in and apply the market access layer



end

to-report assign-wt [current-age compare-age compare-wt max-age max-wt]
  let ideal-wt []
  foreach current-age [x ->
    ifelse x < max-age
     [let pos position x compare-age
      let id-wt item pos compare-wt
      set ideal-wt lput id-wt ideal-wt]
     [set ideal-wt lput max-wt ideal-wt]
  ]

  report ideal-wt

end




;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Load households based on option set using the chooser (Farmers, Pastoralists, All)

to load-households
                                   ;; Since agents are households and not indivduals, the number of households sprouted is set at about a fifth of the density
ifelse llhood = "all" [            ;; If both farmers and pastoral groups are being simualted
  ask patches [
    if ((cov  = 2) or (cov = 3 ) or (cov = 4))  and (den > -9999) and  kenya = 1 and protect = 0 [
      sprout-hholds ceiling (den * 0.2  * sam_p) [
       set shape "house"
       set color red
       set hm_patch patch-here
          ifelse [cov] of patch-here = 4 and [farm] of patch-here = 1 [set occ "farmer"  set color green] [set occ "pastoralist"]
          set my-tribe [tribe] of patch-here
 ]
  ]
   ]
    ]

  [if llhood = "farmer" [ask patches [  ; only farmers are simulated
    if (cov = 4)  and (den > -9999) and kenya = 1 and farm = 1 and protect = 0 [
      sprout-hholds ceiling (den * 0.2 * sam_p) [
       set shape "house"
       set color red
       set hm_patch patch-here
       set occ "farmer"
        set my-tribe [tribe] of patch-here]
 ]
  ]
    ]

  if llhood = "pastoralist" [ask patches with   ; only pastoralists are simulated
      [((cov = 2) or (cov = 3) or (cov = 4))  and (den > -9999) and kenya = 1 and farm = 0 and p_prop > 0.1 and protect = 0] [

       sprout-hholds ceiling (den  * 0.15 * p_prop * sam_p * pop_fact)  [  ;; Kratli and Swift 2014, Counting pastoralists and hhld size is a little over 5 hence multiply by 0.1; p_prop is pastoral population proportion
       set shape "house"
       set color red
       set hm_patch patch-here
       set occ  "pastoralist"
       set my-tribe [tribe] of patch-here]
 ]
  ]
    ]


; Assign agropastoral status to pastoral households

  ask hholds with [[cov] of patch-here = 4]    ; Agropastoral households are pastoral households on ag land . land holding range from 0.25 Ha to a little under 2 Ha
                  [set agrop 1
                   set ag_land precision ((random-float 1.75) + 0.25) 2]


; Assign non-sedentary status to households that are not agropastoral
  ask hholds with [agrop = 0] [let temp [nomad] of patch-here
    if random-float 1 < temp / 100 [set nonsed 1]]

   ask hholds[
   ;; assign members based on age-sex classification to each household : We will use the age-sex classification from GridPop to inform this if necessary.
   ;; Hholds may thus have a maximum of 10 members and a minimum of 2

   set  p_under5   random 3                ;; members under 5 years of age
   set  p_6to12    random 3                ;; members between 6 and 12 years of age
   set  m_13to17   random 3                ;; male members between 13 and 17 years of age
   set  f_13to17   random 3                ;; female members between 13 and 17 years of age
   set  m_older17  (random 3) + 1          ;; male members older than 17
   set  f_older17  (random 3) + 1          ;; female members older than 17  Ensure that households have at least 1 older male and female.

   set hh_mem (list p_under5 p_6to12 m_13to17 f_13to17 m_older17  f_older17)  ;< 5 , 6-12, 13-17 (m) 13-17 (f) >17 (m) >17 (f)
   set hh_tot sum hh_mem
  ]
;##########################################################################################################################################################################

  ;; Households are assigned to three categories based on size. This determines livestock holdings and sources of income

  ask hholds [

    if hh_tot < 8 [set h_quant 1]
    if hh_tot > 7 and hh_tot < 11 [set h_quant 3]
    if hh_tot > 10 [ set h_quant 6]



    ;; give households a cattle herd
    let ca_temp abs (random-normal ([cattle] of patch-here * h_quant ) 5) ; Mean as per FEWS

    ; Split cattle into two sex classes (includes all post weaning individuals)
    set ca_aF ceiling (ca_temp * 0.57)
    set ca_aM ceiling (ca_temp * 0.43)


    ;set cat matrix:from-column-list (list(list ca_aF  ca_aM)) ;
    set cat-tot sum (list ca_aF ca_aM); Here we do not include calves in the total.

    ;; Give the herd a starting age. Here we assign a starting age for each sex class ranging. Cohort includes individuals of all ages post weaning

    set ca_aF_ag  n-values ca_aF [random (96 - 9 + 1) + 9]  ;Max age 12 years, Min age 9 months (weaning age)
    set ca_aM_ag  n-values ca_aM [random (96 - 9 + 1) + 9]


    ;; Give the herd a starting weight.
    ;;Removing sum before n-values to make a list of weights instead of total weight of cohort
    let temp_caFwt assign-wt ca_aF_ag cat_age cat_wt_age 16 200
    set ca_aF_wt []
    foreach temp_caFwt [x -> set ca_aF_wt lput (x + random-normal 0 2) ca_aF_wt]

    let temp_caMwt assign-wt ca_aM_ag cat_age cat_wt_age 18 250
    set ca_aM_wt []
    foreach temp_caMwt [x -> set ca_aM_wt lput (x + random-normal 0 2) ca_aM_wt]

    set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))

    ;; Determine breeding females and create calf cohort
    set ca_calves 0
    set ca_calves_ag []
    set fem_lact n-values ca_af [0]


    set hh-cat-tot (list cat-tot)  ; Total adult cattle owned
    set hh-cat-lam []   ; A tracker for monthly cattle population growth rate

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ;; give households a goat herd
    let gt_temp abs (random-normal ([goat] of patch-here * h_quant) 5) ; Mean as per FEWS

    ; Assign individuals to sex cohorts
    set gt_b ceiling (gt_temp * 0.26)
    set gt_d ceiling (gt_temp * 0.74)


  ;set gt matrix:from-column-list (list(list gt_b  gt_d))
  set gt-tot sum (list gt_b  gt_d ) ; Total adult goats owned


    ;; Give each animal a starting age

   set gt_b_ag n-values  gt_b [random (60 - 8 + 1) + 8]
   set gt_d_ag n-values gt_d [random (60 - 8 + 1) + 8]


   ;; Give a starting weight to each age sex class

    let temp_gtDwt assign-wt gt_d_ag gt_age gt_wt_age 16 32
    set gt_d_wt []
    foreach temp_gtDwt [x -> set gt_d_wt lput (x + random-normal 0 2) gt_d_wt]

    let temp_gtBwt assign-wt gt_b_ag gt_age gt_wt_age 17 34
    set gt_b_wt []
    foreach temp_gtBwt [x -> set gt_b_wt lput (x + random-normal 0 2) gt_b_wt]

    set gt_tot_wt sum (map [x -> sum x] (list gt_d_wt gt_b_wt))

    ;; Determine lactating individuals and create kids cohort
    set gt_kids 0
    set gt_kids_ag []
    set gt_fem_lact n-values gt_d [0]

    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ; give households a sheep herd

    let shp_temp abs (random-normal ([sheep] of patch-here * h_quant) 5); Mean as per FEWS

    set  sh_r ceiling (shp_temp * 0.12)
    set  sh_e ceiling (shp_temp * 0.88)

    ;set shp matrix:from-column-list (list (list sh_r  sh_e))
    set sh-tot sum (list sh_r  sh_e)   ; Total adult sheep owned

    ;; Give each animal a starting age  (Konig et al 2017)

   set sh_r_ag n-values sh_r [random (60 - 8 + 1) + 8]      ;; Max age of adults is 5 years.
   set sh_e_ag n-values sh_e [random (60 - 8 + 1) + 8]

    ;; Give a starting weight to each age sex class

    let temp_shEwt assign-wt sh_e_ag sh_age sh_wt_age 14 32
    set sh_e_wt []
    foreach temp_shEwt [x -> set sh_e_wt lput (x + random-normal 0 2) sh_e_wt]

    let temp_shRwt assign-wt sh_r_ag sh_age sh_wt_age 14 34
    set sh_r_wt []
    foreach temp_shRwt [x -> set sh_r_wt lput (x + random-normal 0 2) sh_r_wt]


    set sh_tot_wt sum (map [x -> sum x] (list sh_r_wt sh_e_wt))

     ;; Determine breeding females and create calf cohort
    set sh_lambs 0
    set sh_lambs_ag []
    set sh_fem_lact n-values sh_e [0]

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  ;; Give households camel herds; Not all areas in Kenya have camels. So only patches where camels have been recorded get hholds with camels
    ifelse [camel] of patch-here != 0 [set camel-owner 1] [set camel-owner 0] ;; Designate if the household traditionally keeps camels

    let cam_temp abs (random-normal ([camel] of patch-here * h_quant) 5); Mean as per FEWS * the quartile the household falls in.
    if [camel] of patch-here = 0 [set cam_temp 0]

    set cam_aM ceiling (0.33 * cam_temp)
    set cam_aF ceiling (0.67 * cam_temp)

    ;set cam matrix:from-column-list (list (list cam_aM  cam_aF))
    set cam-tot sum (list cam_aM  cam_aF)

    ;; Give each animal a starting age  (Konig et al 2017)

    set cam_aM_ag n-values cam_aM [random (300 - 8 + 1) + 8]         ;; Max age of adults set to 25 years
    set cam_aF_ag n-values cam_aF [random (300 - 8 + 1) + 8]         ;; Weaning age is 7 months

      ;; Give a starting weight to each age sex class

    let temp_camFwt assign-wt cam_af_ag cam_age cam_wt_age 17 350
    set cam_af_wt []
    foreach temp_camFwt [x -> set cam_af_wt lput (x + random-normal 0 2) cam_af_wt]

    let temp_camMwt assign-wt cam_am_ag cam_age cam_wt_age 19 400
    set cam_am_wt []
    foreach temp_camMwt [x -> set cam_am_wt lput (x + random-normal 0 2) cam_am_wt]


    set cam_tot_wt sum (map [x -> sum x] (list cam_aF_wt cam_aM_wt))


        ;; Determine breeding females and create calf cohort
    set cam_calves 0
    set cam_calves_ag []
    set cam_fem_lact n-values cam_af [0]


    set hh-cam-tot (list cam-tot)

    set hh-cam-lam []      ;; This is where the monthly camel population growth rate is tracked


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   ;; For each household set up total number of livestock as TLU
   set TLU-owned (list ((cam-tot * 1.25) + cat-tot  + gt-tot * 0.1 + sh-tot * 0.1)) ;; Megersa et al 2014
   let adult_eq [0.52 0.85 0.96 0.96 1.0 0.86];; from DECUMA
   set AE sum (map [[a b] -> a * b] hh_mem adult_eq) ;; Total adult equivalents in each household
   set TLU-cap (list (item 0 TLU-owned / AE));; The TLUs owned per adult equivalent
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    set move-cost []   ;; Set up the list that tracks distances moved in each step

    ;; Give households a starting quanitity of maize purchased from markets / grown at home
    set maize 0; (floor abs random-normal 100 5) ;; Here each household has upto 80 kgs of maize assigned randomly for the month; Left over from previous months

   ;; Give households sources of income
    ;ifelse (item 0 TLU-cap) <= 5  ; Poverty line is 2$/day. These households earn approximately 4000ksh/month and earn the rest via cattle sales
    ;    [set base_income abs(random-normal 4000 100)] [set base_income 0]

    ifelse h_quant = 1 [ set base_income abs(random-normal 3000 100)] [set base_income 0]

  ; ifelse (item 0 TLU-cap) > 5  and (item 0 TLU-cap) <= 8
   ;     [set labour abs(random-normal 6000 500)] [set labour 0]

     ifelse h_quant = 3 [ set labour abs(random-normal 5000 500)] [set labour 0]

    ;ifelse (item 0 TLU-cap) > 8
    ;[set business abs(random-normal 8000 500)] [set business 0] ;;

    ifelse h_quant = 6 [ set business abs(random-normal 8000 500)] [set business 0]

    set cash_in_hand 0; (floor abs random-normal 10000 500)  ;; money left over from last month



   ;; Assign a few households (at a minimum 1 and a maximum of 10) as family from whom gifts may be received or to whom gifts may be given
    let temp-fam hholds with [my-tribe = [my-tribe] of myself]
    let fam count temp-fam
    ifelse fam < 10
    [create-links-with n-of (random  fam) other temp-fam  [hide-link]]
    [create-links-with n-of (random  (10)) other temp-fam  [hide-link]]

;;  Set the calorie source tracker
    set cal-source []

 ;; Set the debt tracker
     set economic_state []
    ;;Set the sales and purchases tracker. For each houselhold, each month the number of cattle, camel, sheep and goat bought and sold is tracked.

    set sales_ca_m []
    set sales_cam_m []
    set sales_sht_m []
    set purchases_ca_m []
    set purchases_cam_m []
    set purchases_sht_m []
    set hunger-stat []
    set milk_given []
    set milk_recieved []
    set gift_given []
    set gift_recieved []
    set cat_m []
    set cam_m []
    set gt_m []
    set sh_m []
    set liv_sales_income []
    set raid-tribe []
    set raid-loss []
    set grazing_land patch-here
    if nonsed = 0 [set move-stat "sedentary" set temp_past_status 1]
    if nonsed = 1 [set move-stat "non-sedentary" set temp_past_status 1]
  ]

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to load-parms
  set m_days [31 28 31 30 31 30 31 31 30 31 30 31]

  ;; Adult equivalent conversions and Calorie requirements per AE
 set hh_ae [0.52 0.85 0.96 0.96 1.0 0.86] ;; < 5 , 6-12, 13-17 (m) 13-17 (f) >17 (m) >17 (f)
 set mem_calreq [1720 1720 1943 1943 2024 1943]

  ;Milk calorie for each sp

 set milk_cal_cow 789 ; Milk calorie count (cal/kg)
 set milk_cal_cam 700  ; Camel milk calorie (cal/kg) From Morton 1984
 set milk_cal_gt  530 ; Calories from goat milk
 set milk_cal_sh  530 ; Calories from sheep milk

  ; Slaughter probability and meat calories
 set opportunistic_slaughter 0.05
 set meat_cal 1720; Meat calorie count (kcal/kg)
 set maize_cal 3700 ; Maize calorie count (kcal/kg)


  ;; Household wealth and sources in Kenyan Shillings: These values are placeholders from Decuma

 set income_catcam  [5889 5818 6798 6679 6514 7721 6924 6403 6254 6743 6790 6939] ;; Monthly price of large livestock
 set income_shoat [1212 1179 1198 1160 1213 1217 1167 1187 1149 1232 1326 1383] ; Monthly price of small stock


 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  set TLU [1 0.1 0.1 1]

  set cat_age [8 9 10 11 12 13 14 15 16 17 18] ;;post-weaning ages for cattle and camel
  set cat_wt_age [100	107	115	124	135	147	161	177	195	215	238];; weight at age for cattle

  set cam_age [8 9 10 11 12 13 14 15 16 17 18 19]
  set cam_wt_age [150	162	175	190	206	224	244	266	291	319	350	385]

  set sh_age [3 4 5 6 7 8 9 10 11 12 13 14]
  set sh_wt_age [10	10.89	11.9	13.05	14.36	15.86	17.58	19.56	21.84	24.48	27.54	31.1]

  set gt_age [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17]
  set gt_wt_age [10 10 11 12 13 14 15 16 17 19 21 23 26 28 32]


  set ca_calf_dr 0.029      ; Monthly death rate for calves  ;;All 4 values from Having herds
  set cam_calf_dr 0.029  ; Monthly death rate for camel calves
  set gt_kids_dr 0.018   ; Monthly death rate for kids
  set sh_lambs_dr 0.029   ; Monthly death rate for lambs


  set milk_prod [24 24 24 45 46.5 24 24 24 24 24 42 42] ; milk produced kg/cow/month Decuma
  set cam_milk_prod [15 15 15 51 51 51 45 45 45 36 36 36]; McCabe 2004
  set shoat_milk_prod [0 0 0 5 5 0 0 0 0 0 4 4]; McCabe 2004


 ;; Set the breeeding and milking months for cattle, camel and shoats between Jan and Dec

  set cat-breed [0 0 0 1 0 0 0 0 0 0 1 0]
  set shoat-breed [0 0 0 1 0 0 0 0 0 0 1 0]
  set cam-breed [0 0 0 1 0 0 0 0 0 0 1 0]

  set cat-milk [1 1 1 1 1 1 1 1 1 1 1 1]
  set shoat-milk [0 0 0 1 1 0 0 0 0 0 1 1]
  set cam-milk [1 1 1 1 1 1 1 1 1 1 1 1];   From Morton 1984

  set cat-rep-rate [0 0 0 0.5 0 0 0 0 0 0 0.2 0]
  set sht-rep-rate [0 0 0 0.7 0 0 0 0 0 0 0.3 0]
  set cam-rep-rate [0 0 0 0.4 0 0 0 0 0 0 0.1 0]


  set m_harvest [0 0 0 0 0 0 1 0 0 0 0 0]  ; Month when maize is harvested by agropastoral hholds (July)

  set cat_pool [0.45 0.45 0.05 0.05 0 0 0 0] ; relative preference of cattle for gherb dherb gshrub dshrub bshrub gtree dtree btree
  set sh_pool [0.45 0.43 0.05 0.05 0 0.07 0.07 0] ; relative preference of sheep for gherb dherb gshrub dshrub bshrub gtree dtree btree
  set gt_pool [0.08 0.10 0.40 0.40 0.28 0.45 0.45 0.38] ; relative preference of goat for gherb dherb gshrub dshrub bshrub gtree dtree btree
  set cam_pool [0.02 0.02 0.50 0.50 0.72 0.48 0.48 0.62] ; relative preference of camel for gherb dherb gshrub dshrub bshrub gtree dtree btree

  ;set cat_energy 7
  ;set cam_energy 5
  ;set sh_energy 7
  ;set gt_energy 8
  ;; Above each pool adds up to 1.


;;;;;;;;;;;;;;;;;;;Update livestock totals for Kenya;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  ; The total number of cattle, vamel, sheep and goat in Kenya
  set cattle-total (list sum [cat-tot] of turtles)
  set camel-total (list sum [cam-tot] of turtles)
  set sheep-total (list sum [sh-tot] of turtles)
  set goat-total (list sum [gt-tot] of turtles)

  set drop-outs []
  ;set hungry []

end

to spin-hholds
  create-turtles 10657

  file-open  "SPIRALL-NewDiets world.csv"
  let headings csv:from-row file-read-line
  let i 0
  while [ not file-at-end? ] [
    let data csv:from-row file-read-line
    print data
ask turtle i [
;set	who	((item	0	data))
set	color		red
;set	heading	(item	2	data)
set	xcor (item	0	data)
set	ycor (item	1	data)
set	shape	"house"
set	label	(read-from-string	(item	3	data))
set	label-color	black
set	breed	hholds
set	size	1
set	pen-size	1
set	pen-mode	"up"
set	nonsed	(item	4	data)
set	occ	(read-from-string	(item	5	data))
set	agrop		(item	6	data)
set	hm_patch read-from-string (item 7 data)
set	my-tribe	(read-from-string	(item	8	data))
set past_type read-from-string (item 9 data)
set move-stat read-from-string (item 10 data)
set	grazing_land	read-from-string (item	11	data)
set	cam_am	 (item	12	data)
set	cam_af		(item	13	data)
set	cam-tot	(item	14	data)
set	cam_am_wt read-from-string	(item	15	data)
set	cam_af_wt	read-from-string (item	16	data)
set	cam_af_ag	read-from-string (item	17	data)
set	cam_am_ag	read-from-string (item	18	data)
set	cam_fem_lact read-from-string	(item	19	data)
set	cam_calves	(item	20	data)
set	cam_calves_ag	read-from-string (item	21	data)
set	cam_tot_wt	(item	22	data)
set	camel-owner	(item	23	data)
set	ca_calves	(item	24	data)
set	ca_calves_ag	read-from-string (item	25	data)
set	ca_af	(item	26	data)
set	ca_am	(item	27	data)
set	cat-tot	(item	28	data)
set	ca_af_wt	read-from-string (item	29	data)
set	ca_am_wt	read-from-string (item	30	data)
set	ca_tot_wt	 (item	31	data)
set	fem_lact	read-from-string (item	32	data)
set	ca_af_ag	read-from-string (item	33	data)
set	ca_am_ag	read-from-string (item	34	data)
set	sh_r	(item	35	data)
set	sh_e	(item	36	data)
set	sh-tot	(item	37	data)
set	sh_r_wt	read-from-string (item	38	data)
set	sh_e_wt	read-from-string (item	39	data)
set	sh_r_ag	read-from-string (item	40	data)
set	sh_e_ag	read-from-string (item	41	data)
set	sh_fem_lact	read-from-string (item	42	data)
set	sh_lambs	(item	43	data)
set	sh_lambs_ag	read-from-string (item	44	data)
set	sh_tot_wt  (item	45	data)
set	gt_b (item	46	data)
set	gt_d	(item	47	data)
set	gt-tot	(item	48	data)
set	gt_b_wt	read-from-string (item	49	data)
set	gt_d_wt	read-from-string (item	50	data)
set	gt_b_ag	read-from-string (item	51	data)
set	gt_d_ag	read-from-string (item	52	data)
set	gt_fem_lact	read-from-string (item	53	data)
set	gt_kids	(item	54	data)
set	gt_kids_ag	read-from-string (item	55	data)
set	gt_tot_wt	(item	56	data)
set	p_under5	(item	57	data)
set	p_6to12	(item	58	data)
set	m_13to17	(item	59	data)
set	m_older17	(item	60	data)
set	f_13to17	(item	61	data)
set	f_older17	(item	62	data)
set	hh_mem	read-from-string (item	63	data)
set	ae	(item	64	data)
set	hh_tot (item	65	data)
set	h_quant	(item	66	data)
set	maize	(item	67	data)
set	cash_in_hand	(item	68	data)
set	labour	(item	69	data)
set	business	(item	70	data)
set	ag_land	(item	71	data)
set	base_income	(item	72	data)
set	assets	(item 73	data)
set	family	(item	74	data)
    set move-cost []
    set cal-source []
    set economic_state []
    set sales_ca_m []
    set sales_cam_m []
    set sales_sht_m []
    set purchases_ca_m []
    set purchases_cam_m []
    set purchases_sht_m []
    set hunger-stat []
    set milk_given []
    set milk_recieved []
    set gift_given []
    set gift_recieved []
    set hh-cat-tot (list cat-tot)  ; Total adul cattle owned
    set hh-cat-lam []   ; A tracker for monthly cattle population growth rate
    set hh-cam-tot (list cam-tot)
    set hh-cam-lam []
    set TLU-owned []
    set TLU-cap []
    set cat_m (list cat-tot)
    set cam_m (list cam-tot)
    set sh_m (list sh-tot)
    set gt_m (list gt-tot )
    set liv_sales_income []
    set raid-tribe []
    set raid-loss []

        ]
set i i + 1
    ]

  file-close-all

  ask hholds [
    ;move-to  hm_patch             ;; Use this and next line for sedentary scenario
    ;set grazing_land hm_patch
    let temp-fam hholds with [my-tribe = [my-tribe] of myself]
    let fam count temp-fam
    ifelse fam < 10
    [create-links-with n-of (random  fam) other temp-fam  [hide-link]]
    [create-links-with n-of (random  (10)) other temp-fam  [hide-link]]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   ;; For each household set up total number of livestock as TLU
   set TLU-owned (list ((cam-tot * 1.25) + cat-tot  + gt-tot * 0.1 + sh-tot * 0.1)) ;; Megersa et al 2014
   let adult_eq [0.52 0.85 0.96 0.96 1.0 0.86]
   set AE sum (map [[a b] -> a * b] hh_mem adult_eq)
   set TLU-cap (list (item 0 TLU-owned / AE))

      ]


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to reset-hholds

;; This step ensures that if there are pastoralists who end up without any livestock in the previous step, they have atleast a small herd of a combinaiton of cattle and shoats to start off with to stay in the system

  ask hholds with [assets = "assetless"]  ; Households that lost their entire herd at the end of the previous month
               ;; give households a cattle herd
  [
    set reborn  1

   let ca_temp random-poisson 2 ;

    ; Split cattle into two sex classes (includes all psot weaning individuals)
    set ca_aF ceiling (ca_temp * 0.57)
    set ca_aM ceiling (ca_temp * 0.43)


    ;set cat matrix:from-column-list (list(list ca_aF  ca_aM)) ;
    set cat-tot sum (list ca_aF ca_aM); Here we do not include calves in the total.

    ;; Give the herd a starting age. Here we assign a starting age for each sex class ranging. Cohort includes individuals of all ages post weaning

    set ca_aF_ag  n-values ca_aF [random (144 - 9 + 1) + 9]  ;Max age 13 years, Min age 9 months (weaning age)
    set ca_aM_ag  n-values ca_aM [random (144 - 9 + 1) + 9]


    ;; Give the herd a starting weight.
    ;;Removing sum before n-values to make a list of weights instead of total weight of cohort
    let temp_caFwt assign-wt ca_aF_ag cat_age cat_wt_age 16 200
    set ca_aF_wt []
    foreach temp_caFwt [x -> set ca_aF_wt lput (x + random-normal 0 2) ca_aF_wt]

    let temp_caMwt assign-wt ca_aM_ag cat_age cat_wt_age 18 250
    set ca_aM_wt []
    foreach temp_caMwt [x -> set ca_aM_wt lput (x + random-normal 0 2) ca_aM_wt]
    set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))

    ;; Determine breeding females and create calf cohort
    set ca_calves 0
    set ca_calves_ag []
    set fem_lact n-values ca_af [0]


   ; set hh-cat-tot n-values (ticks + 1)  [0]
    ;set hh-cat-lam n-values (ticks + 1)  [1]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ;; give households a goat herd
    let gt_temp random-poisson 2 ; Poisson mean as per FEWS

    ; Assign individuals to sex cohorts
    set gt_b ceiling (gt_temp * 0.26)
    set gt_d ceiling (gt_temp * 0.74)


  ;set gt matrix:from-column-list (list(list gt_b  gt_d))
  set gt-tot sum (list gt_b  gt_d )


    ;; Give each animal a starting age

   set gt_b_ag n-values  gt_b [random (60 - 8 + 1) + 8]
   set gt_d_ag n-values gt_d [random (60 - 8 + 1) + 8]


   ;; Give a starting weight to each age sex class

    let temp_gtDwt assign-wt gt_d_ag gt_age gt_wt_age 16 32
    set gt_d_wt []
    foreach temp_gtDwt [x -> set gt_d_wt lput (x + random-normal 0 2) gt_d_wt]

    let temp_gtBwt assign-wt gt_b_ag gt_age gt_wt_age 17 34
    set gt_b_wt []
    foreach temp_gtBwt [x -> set gt_b_wt lput (x + random-normal 0 2) gt_b_wt]

    set gt_tot_wt sum (map [x -> sum x] (list gt_d_wt gt_b_wt))

    ;; Determine lactating individuals and create kids cohort
    set gt_kids 0
    set gt_kids_ag []
    set gt_fem_lact n-values gt_d [0]

    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ; give households a sheep herd

    let shp_temp random-poisson 2 ; Poisson mean as per FEWS

    set  sh_r ceiling (shp_temp * 0.12)
    set  sh_e ceiling (shp_temp * 0.88)

    ;set shp matrix:from-column-list (list (list sh_r  sh_e))
    set sh-tot sum (list sh_r  sh_e)

    ;; Give each animal a starting age  (Konig et al 2017)

   set sh_r_ag n-values sh_r [random (60 - 8 + 1) + 8]      ;; Max age of adults is 5 years.
   set sh_e_ag n-values sh_e [random (60 - 8 + 1) + 8]

    ;; Give a starting weight to each age sex class

   let temp_shEwt assign-wt sh_e_ag sh_age sh_wt_age 14 32
    set sh_e_wt []
    foreach temp_shEwt [x -> set sh_e_wt lput (x + random-normal 0 2) sh_e_wt]

    let temp_shRwt assign-wt sh_r_ag sh_age sh_wt_age 14 34
    set sh_r_wt []
    foreach temp_shRwt [x -> set sh_r_wt lput (x + random-normal 0 2) sh_r_wt]

    set sh_tot_wt sum (map [x -> sum x] (list sh_r_wt sh_e_wt))

     ;; Determine breeding females and create calf cohort
    set sh_lambs 0
    set sh_lambs_ag []
    set sh_fem_lact n-values sh_e [0]

  ]

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;



to load-forage
  ; This is where the agent based model will integrate with lrange
  ;; The biomass values are updated for each patch


 let p_sort sort patches
 let pools ["GREEN_HERB" "DEAD_HERB"  "GREEN_SHRUB" "DEAD_SHRUB" "SHRUB_BRNCH" "GREEN_TREE" "DEAD_TREE" "TREE_BRNCH"]


  file-open (read-from-string bio_out)
  let temp []
   while [not file-at-end?] [
   let skip file-read-line
   repeat (count patches) [set temp lput file-read temp]
        ]
  file-close

  ;;Update  biomass
  let totp count patches
  (foreach p_sort sublist temp 0 totp [[p t] ->
    ask p [set green_herb t]])
  (foreach p_sort sublist temp totp (totp * 2) [[p t] ->
    ask p [set dead_herb t]])
  (foreach p_sort sublist temp (totp * 2) (totp * 3) [[p t] ->
    ask p [set green_shrub t]])
  (foreach p_sort sublist temp (totp * 3) (totp * 4) [[p t] ->
    ask p [set dead_shrub t]])
  (foreach p_sort sublist temp (totp * 4) (totp * 5) [[p t] ->
    ask p [set shrub_brnch t]])
  (foreach p_sort sublist temp (totp * 5) (totp * 6) [[p t] ->
    ask p [set green_tree t]])
 (foreach p_sort sublist temp (totp * 6) (totp * 7) [[p t] ->
    ask p [set dead_tree t]])
  (foreach p_sort sublist temp (totp * 7) (totp * 8) [[p t] ->
    ask p [set tree_brnch t]])


  ;; Reset the forage and other metrics to 0

  ask patches [
    set hsi_herb 0
    set hsi_browse 0
    set forage_cat 0
    set forage_browse 0
    set stock_den 0
    set cam_den 0]





  ask patches with [green_herb >= 1] [                   ;; here we calculate habitat suitability values based on the max and min observed biomass values for Kenya Boutton et al., 1988
                                                         ;; Biomass Dynamics of grassland vegetation in Kenya.

    ;let mag (green_herb + 0.25 * dead_herb ) * (1 - unavailable); total monthly available biomass for grazers
    ;let mab (green_shrub + 0.25 * dead_shrub + 0.5 * (green_tree + 0.25 * dead_tree)) * (1 - unavailable); total monthly available biomass for browsers
    ;; We assume that dead plant matter contributes 25 % to the diets of herbivores (McNaughton 1985) and about 50 % of green tree matter is available to herbivores (check for reference)
    ;; Of this total amount, in reality a large fraction is unavailable due to natural and anthropogenic constraints. We assume that an assessment of suitability is made based on the total availability

    ;ifelse mag = 0 [set HSI_herb 0]
     ; [set HSI_herb exp(-5 + 0.1 * mag) / (1 + exp(-5 + 0.1 * mag))]


   ; ifelse mab = 0 [set HSI_browse 0]
         ; [set HSI_browse exp(-5 + 0.1 * mab) / (1 + exp(-5 + 0.1 * mab))]

  ;; We determine forage availability for each livestock species by assuming that abt 20 % of herbivore diet is composed of dead matter. Mingo and Oesterheld 2009 McNaughton 1985
  ;; Forage available on a patch is based on the fraction of the population represented (sam_p)
    set greenH green_herb
    set deadH dead_herb
    set greenS green_shrub
    set deadS dead_shrub
    set brnchS shrub_brnch
    set greenT green_tree
    set deadT dead_tree
    set brnchT tree_brnch
  ]

end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;This sub-routine allows herders to compare the suitability of the patch they are on patches within multiple radii and make movement decisions
;;We work under the assumption that movements out of the patch are driven only by considerationf of forage availability for cattle
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to find-pasture

    set month ticks - (12 * floor (ticks / 12))
    if member? ticks n-values years [x -> x * 12] [ set month 0]

  ask patches [

   let mag (green_herb +  dead_herb ) * (grain ^ 2) * (0.001) * (0.01) * sam_p * (1 - unavailable); total monthly available biomass for grazers
   let mab (green_shrub +  dead_shrub + (green_tree +  dead_tree)) * (grain ^ 2) * (0.001) * (0.01) * sam_p * (1 - unavailable); total monthly available biomass for browsers

   set stock_den (mag / 225 )
   set cam_den (mab /  360 )
   ;set stock_den  floor (max_cat * (1 - exp (-30 * 0.05 * HSI_herb / 0.5))) * sam_p ; ;; Monthly patch specific stocking density based on habitat suitability for grazers
   ;set cam_den floor (max_cam * (1 - exp (-30 * 0.05 * HSI_browse / 0.5))) * sam_p ; Monthly patch specific stocking density based on habitat suitability for browsers

    ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; PA access scenario

  if PA_access = "No access" [set PA_patch "protect = 0"]
  if PA_access = "Access allowed" [set PA_patch "protect >= 0"]




;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;When ticks are greater than 0
;; Once sedentary hholds have decided where to place cattle on the lands, in subsequent months assessment are made relative to this new grazing land (Note grazing land may also be the home patch)
;; Hholds assess if graing lands on which cattle are located at the end of previous iteration have reached stockign density. If yes, they are moved to another patch. Those hholds who find their cattle
;; on their home patch are called non-splitters, others are splitters. note again, sedentary hholds keep all other stock on home patch without assessing suitability.  There is a tendency to move
  ;; to patches closer to home in the long rain months

;if ticks > 0 [

  ask patches [set CAT-T 0
               set cam-t 0]

  ask hholds with [move-stat = "sedentary"][
    let current_loc grazing_land
    let name [who] of self
    let home_patch hm_patch

    if (month = 3 or month = 4 or month = 5)[
         ask patch-here [set cam-T cam-T + [cam-tot] of hhold name  ; Camels stay on patch of sedentary households
                         set CAT-T CAT-T + [cat-tot] of hhold name]
               set grazing_land patch-here
               ifelse grazing_land = home_patch [set past_type "non-splitter"] [set past_type "splitter"]
               set move-stat "sedentary"
               set move-cost lput (distance current_loc) move-cost
               ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
               set selection 1]]


     ask hholds with [move-stat = "sedentary"] [

       let name [who] of self
       let home_patch hm_patch


      ask patch-here [ set cam-T cam-T + [cam-tot] of hhold name ]  ; Camels stay on patch of sedentary households

       ifelse [CAT-T] of grazing_land + cat-tot < [stock_den] of grazing_land  ; Check grazing lands to see if they can support cattle;

              [;set grazing_land grazing_land; grazing_land
               ask grazing_land [set CAT-T CAT-T + [cat-tot] of hhold name]
               ifelse grazing_land = home_patch [set past_type "non-splitter"] [set past_type "splitter"]
               set move-stat "sedentary"
               set move-cost lput 0 move-cost
               ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
               set selection 1]

    ;; Look for a suitable patch within county boundary

      [let available ([patches in-radius (orbit_normal /(grain  / 1000))] of home_patch) ;; Look for patches within county boundary
                                 with [tribe = [my-tribe] of turtle name  and (CAT-T + [cat-tot] of turtle name  < stock_den)
                                          and (cov = 3 or cov = 2 or cov = 4) and farm = 0 and (runresult (PA_patch))]

          if my-tribe = "Turkana" [

          set available available with [tribe != "Marsabit"]]

                  ifelse any? available
                   [let temp_range 0
                    set temp_range (ifelse-value (month = 3 or month = 4 or month = 5) [min-one-of available [distance home_patch]]
                                                                                       [ one-of available])
                     set grazing_land temp_range
                     ask grazing_land [set CAT-T CAT-T  + [cat-tot] of hhold name]
                     ifelse grazing_land = home_patch [set past_type "non-splitter"] [set past_type "splitter"]
                     set move-stat "sedentary"
                     set move-cost lput (distance grazing_land) move-cost
                     ifelse my-tribe != [tribe] of grazing_land [set risk 1] [set risk 0]
                     set selection 2]

       ;; Look for a suitable patch for cattle beyond county boundary

             [let available-d ([patches in-radius (orbit_normal /(grain  / 1000))] of home_patch) ; Look for patches outside county boundary
                                 with [(CAT-T + [cat-tot] of turtle name  < stock_den) and (cov = 3 or cov = 2 or cov = 4) and farm = 0 and (runresult (PA_patch))]

          if my-tribe = "Turkana" [

          set available-d available-d with [tribe != "Marsabit"]]

                   ifelse any? available-d
                     [let temp_range 0
                     set temp_range (ifelse-value (month = 3 or month = 4 or month = 5) [min-one-of available-d [distance home_patch]]
                                                                                       [ one-of available-d])
                     set grazing_land temp_range
                     ask grazing_land [set CAT-T CAT-T + [cat-tot] of hhold name ]
                     ifelse grazing_land = home_patch [set past_type "non-splitter"] [set past_type "splitter"]
                     set move-stat "sedentary"
                     set move-cost lput (distance grazing_land) move-cost
            ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
                     set selection 3]

            ;;If no suitable patches are available within or beyond the county keep cattle on current patch
              [;set grazing_land grazing_land; grazing_land
               ask grazing_land [set CAT-T CAT-T + [cat-tot] of hhold name ]
               ifelse grazing_land = home_patch [set past_type "non-splitter"] [set past_type "splitter"]
               set move-stat "sedentary"
               set move-cost lput 0 move-cost
               ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
               set selection 4]

              ]
            ]
         ]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   ;;;;;; Move non-sedetary househlds.
;; Non -sedentary hholds assess the suitability of patches for both camel and cattle. They move the entire hhold when patches have reached stockign density for either cattle or camel
  ;; Movement is first to another patch within the county, then beyond the county and if nothing is found, then to any patch with HSI> 0. Tendency to move to a patch close to home in the
  ;; long rain months
  ask hholds with [move-stat = "non-sedentary"][

  set temp_past_status 0
  let name [who] of self
  let home_patch hm_patch
  let current_loc patch-here
  set grazing_land 0

    ;; During long rain months in Kenya (March-April-May) households head back to their home patch "Awi"
      ifelse (month = 3 or month = 4 or month = 5)

                      [move-to home_patch
                      ask patch-here  [set CAT-T CAT-T + [cat-tot] of hhold name
                                       set cam-T (cam-T + [cam-tot] of hhold name )]
                      set move-cost lput (distance current_loc) move-cost
                      set past_type "non-splitter"
                      set move-stat "non-sedentary"
                      set temp_past_status 1
                      set nonsed  1
                      set grazing_land home_patch
                      set selection 1
                      set risk 0]

 ;; In other months households examine whether the patch they are located on can support cattle and camel herds
      [ifelse ([CAT-T] of patch-here + cat-tot < [stock_den] of patch-here and
              [cam-T] of patch-here +  cam-tot < [cam_den] of patch-here)

      ;; If it can, stay on patch
       [ask patch-here [set CAT-T  CAT-T + [cat-tot] of hhold name
                        set cam-T cam-T + [cam-tot] of hhold name]
          set move-cost lput 0 move-cost
          set past_type "non-splitter"
          set move-stat "non-sedentary"
          set temp_past_status 1
          set nonsed  1
          set grazing_land patch-here
          ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
          set selection 1]

      ;; If not look for another patch within the movement orbit around the home patch and within the county
        [let available ([patches in-radius ((orbit_normal) /(grain  / 1000))] of home_patch) ; Look for patches within county boundary
                                 with [tribe = [my-tribe] of turtle name  and (CAT-T + [cat-tot] of turtle name  < stock_den) and (cov = 3 or cov = 2 or cov = 4)
                                         and (cam-T + [cam-tot] of turtle name ) < cam_den and farm = 0 and (runresult (PA_patch))]

        if my-tribe = "Turkana" [

          set available available with [tribe != "Marsabit"]]


              ifelse any? available
                    [ let new-p 0

                      set new-p one-of available
                      move-to new-p
                      ask new-p [set CAT-T CAT-T + [cat-tot] of hhold name
                                               set cam-T (cam-T + [cam-tot] of hhold name )]
                      set move-cost lput (distance current_loc) move-cost
                      set past_type "non-splitter"
                      set move-stat "non-sedentary"
                      set temp_past_status 1
                      set nonsed  1
                      set grazing_land new-p
                      ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
                      set selection 2]

                        [set temp_past_status 0]]]
  ]

;; Move households that have still not found a suitable pasture. Look for patches within movement radius and otside of the county

  ask hholds with [move-stat = "non-sedentary" and temp_past_status = 0][
                 let name [who] of self
                 let home_patch hm_patch
                 let current_loc patch-here

                 let available-d ([patches in-radius (orbit_normal /(grain  / 1000))] of home_patch) ; Look for pactches outside the county
                                          with [(CAT-T + [cat-tot] of turtle name  < stock_den) and (cov = 3 or cov = 2 or cov = 4) and
                                                (cam-T + [cam-tot] of turtle name) < cam_den and farm = 0 and (runresult (PA_patch))]

          if my-tribe = "Turkana" [

          set available-d available-d with [tribe != "Marsabit"]]


        ifelse any? available-d

                    [let new-pn 0

                    set new-pn one-of available-d
                               move-to new-pn
                               ask new-pn [set CAT-T CAT-T + [cat-tot] of hhold name
                                                         set cam-T (cam-T + [cam-tot] of hhold name)]
                               set move-cost lput (distance current_loc) move-cost
                               set past_type "non-splitter"
                               set move-stat "non-sedentary"
                               set temp_past_status 1
                               set nonsed 1
                               set grazing_land new-pn
                               if my-tribe != [tribe] of patch-here and [protect] of grazing_land = 0 [set risk 1]
                               set selection 3]

         ;; Remain on current patch

                 [ask patch-here [set CAT-T  CAT-T + [cat-tot] of hhold name
                        set cam-T cam-T + [cam-tot] of hhold name]
                        set move-cost lput 0 move-cost
                        set past_type "non-splitter"
                        set move-stat "non-sedentary"
                        set temp_past_status 1
                        set nonsed  1
                        set grazing_land patch-here
                      ifelse my-tribe != [tribe] of grazing_land and [protect] of grazing_land = 0 [set risk 1] [set risk 0]
                        set selection 4]
   ]


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
to find-pasture-sedentary-scenario

  ask patches [

   let mag (green_herb +  dead_herb ) * (grain ^ 2) * (0.001) * (0.01) * sam_p * (1 - unavailable); total monthly available biomass for grazers
   let mab (green_shrub +  dead_shrub + (green_tree +  dead_tree)) * (grain ^ 2) * (0.001) * (0.01) * sam_p * (1 - unavailable); total monthly available biomass for browsers

   set stock_den (mag / 225 )
   set cam_den (mab /  360 )
   ;set stock_den  floor (max_cat * (1 - exp (-30 * 0.05 * HSI_herb / 0.5))) * sam_p ; ;; Monthly patch specific stocking density based on habitat suitability for grazers
   ;set cam_den floor (max_cam * (1 - exp (-30 * 0.05 * HSI_browse / 0.5))) * sam_p ; Monthly patch specific stocking density based on habitat suitability for browsers

    ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; Procedure to explore full sedentarization
;; Here all housholds stay on their respective home patches

  ask patches [set CAT-T sum [cat-tot] of turtles-here
               set cam-T sum [cam-tot] of turtles-here]

    ask hholds[
               set grazing_land patch-here;
               set past_type "non-splitter"
               set move-stat "sedentary"
               set move-cost lput (distance grazing_land) move-cost
               ifelse my-tribe != [tribe] of grazing_land [set risk 1] [set risk 0]
               set selection 1]


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now we divide up existing biomass among the livestock present on the patch by first accounting for the fact that only a fraction of the population is being sampled
;; This procedure includes two components: 1) The forage acquired by each animal is tallied to determine weight gain. 2) the patch depletion rate is tallied and and ASCII is written out
;; Livestock lose energy from travel to a patch as well as travel within patch. Travel within patch is based on watering frequency and some random assumed distance to water
;; Wt: List with weight of the livestock group (species-sex-age)
;; BMR : Species specific Matabolic rate
;; travel: total distance traveled to get to patch
;; wat_frequency: The number of times each species is taken to water each month
;; percapita: The percapita available forage for the species on the patch
;; energy: Energy content of the forage consumed by the species (MJ)
;; max_wt: Maximum possible wt for each sex class of each species
;; grazing_area: For splitter cattle herds, grazing area is the patch on which herd is currently grazing (may be different from patch on which hhold is located)
;; All other species and non-splitter cattle herds graze on the same patch where the hhold is located

to-report forage [wt BMR travel wat_freq percapita energy max_wt]

  let max_forage map [n -> (n * 0.03 * 30)] wt  ; based on current wt determine maximum forage that can be consumed as 3 % of body weight

  set wt map [n -> n - (precision (((BMR * (n ^ 0.75) * 30 * 239) / 5600 ) +   ;; FAO;; Wt loss from travel and metabolic costs
                        ((travel + (((random 10) + 1) * wat_freq))  * (12 * n / 100) / 5600)) 2)] wt

  let forage_cons []
  let consumed 0
   foreach max_forage [n -> ifelse percapita > n ;; Checks if per capita available forage is greater than maximum forage that can be consumed by individual
           [set forage_cons lput n forage_cons                     ;; If yes then constrain foraging to maximum diet capacity
            set consumed consumed + n]
           [set forage_cons lput  percapita forage_cons  ;; else constrain to percapita available forage
            set consumed consumed + percapita ]
           ]
      let energy_aq map [n -> n * energy * 239] forage_cons   ;; energy here is the energy content in MJ of 1 kg DM consumed

      set wt (map  [[n a] -> precision (n + (a / 5600)) 2] wt energy_aq) ;; weight gained by assuming 5600 kcal is needed for 1 kg wt gain.

      let temp1 []
      foreach wt [n -> ifelse n > max_wt [set temp1 lput max_wt temp1] [set temp1 lput n temp1]]  ;; Constrain max weight to max possbile wt
      let temp2 []
      foreach temp1 [n -> ifelse n < 0 [set temp2 lput 0 temp2] [set temp2 lput n temp2]]  ;; Remove possible negative values
      set wt temp2

report (list wt consumed forage_cons max_forage)

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Calculate per capita availability of each pool
to deplete-patch
  ask patches with [CAT-T + sum [cam-tot] of turtles-here + sum [sh-tot] of turtles-here + sum [gt-tot] of turtles-here > 0][

;; Account for all the animals on the patch. cows belonging to both hholds on the patch and splitter families
let cows cat-t
let cams sum [cam-tot] of turtles-here
let shs sum [sh-tot] of turtles-here
let goats sum [gt-tot] of turtles-here

;; Standardize total livestock on patch in terms of TLU and relative TLU aundance
let temp-pop (list cows shs goats cams)
let temp-pop-tlu (map [[a b] -> a * b] TLU temp-pop)
let temp-tlu-sum sum temp-pop-tlu
let temp-tlu-std map [a -> a / temp-tlu-sum] temp-pop-tlu

;; Create a combined metric of fraction of each pool allocated representing pool preference and standardized relative abundance
    let cattle-props map [a -> (item 0 temp-tlu-std)  * a] cat_pool
    let sheep-props  map [a -> (item 1 temp-tlu-std)  * a] sh_pool
    let goat-props  map [a -> (item 2 temp-tlu-std) * a]  gt_pool
    let camel-props  map [a -> (item 3 temp-tlu-std) * a] cam_pool

    let temp-tots (map[[a b c d] -> a + b + c + d] cattle-props sheep-props goat-props camel-props)
    let temp-tots2 map [[x] -> ifelse-value (x = 0) [1] [x]] temp-tots ;; This is done to avoid a divide by zero error in the next step

 ; This is the final standardized allocation of each pool to each species on a patch
    set cat-per-pools (map [[a b] -> a / b] cattle-props temp-tots2)
    set sh-per-pools (map [[a b] -> a / b] sheep-props temp-tots2)
    set gt-per-pools (map [[a b] -> a / b] goat-props temp-tots2)
    set cam-per-pools (map [[a b] -> a / b] camel-props temp-tots2)

 ;; Calculate the total forage available for each species by multiplying the fractions with biomass for each pool

    set cattle-forage (sum (map [[a b] -> a * b] cat-per-pools (list greenH deadH greenS deadS brnchS greenT deadT brnchT))) * (grain ^ 2) * 0.001 * 0.01 * sam_p * (1 - unavailable)
    set sheep-forage (sum (map [[a b] -> a * b] sh-per-pools (list greenH deadH greenS deadS brnchS greenT deadT brnchT))) * (grain ^ 2) * 0.001 * 0.01 * sam_p * (1 - unavailable)
    set goat-forage (sum (map [[a b] -> a * b] gt-per-pools (list greenH deadH greenS deadS brnchS greenT deadT brnchT))) * (grain ^ 2) * 0.001 * 0.01 * sam_p * (1 - unavailable)
    set camel-forage (sum (map [[a b] -> a * b] cam-per-pools (list greenH deadH greenS deadS brnchS greenT deadT brnchT))) * (grain ^ 2) * 0.001 * 0.01 * sam_p * (1 - unavailable)

    ifelse cows > 0 [set percap_cattle cattle-forage / cows] [set percap_cattle cattle-forage]
    ifelse shs > 0 [set percap_shp sheep-forage / shs] [set percap_shp sheep-forage]
    ifelse goats > 0 [set percap_gt goat-forage / goats] [set percap_gt goat-forage]
    ifelse cams > 0 [set percap_cam camel-forage / cams] [set percap_cam camel-forage]
    ]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set the coutners tracking froaged consumed each month to 0

  ask patches[set cons_cat 0
              set cons_sh 0
              set cons_gt 0
              set cons_cam 0]


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 ask hholds with [past_type = "non-splitter"] [

    let move-dist 0  ;; Cattle of sedentary and non-spitter households incur movement costs from accessing water within patch, whereas non-sedentary household cattle
                     ;; incur movement cost both from moving to other patches and accesing water within patch
    ifelse past_type = "non-sedentary" [set move-dist (item (ticks ) move-cost) * grain / 1000] [set move-dist 0]


 if ca_aF > 0 [
     let percap_patch [percap_cattle] of patch-here
     let new_wt forage  ca_aF_wt 0.48 move-dist 15 floor percap_patch cat_energy 200
     set ca_aF_wt item 0 new_wt
     ask patch-here [set cons_cat cons_cat + item 1 new_wt]
        ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

    if ca_aM > 0 [

     let percap_patch [percap_cattle] of patch-here
     let new_wt forage  ca_aM_wt 0.48 move-dist 15 floor percap_patch cat_energy 250
     set ca_aM_wt item 0 new_wt
     ask patch-here [set cons_cat cons_cat + item 1 new_wt]
   ]


    set ca_tot_wt sum (map [x -> sum x](list ca_aF_wt ca_aM_wt))  ; Update total cattle wt

 ]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Next we deplete patches where splitter herds are located
 ask hholds with [past_type = "splitter"] [ ; Cattle of splitter households incur movement costs from moving to grazing lands
                                                            ; and from accessign water.

    ; Cattle of splitter households
    let percap_patch [percap_cattle] of grazing_land
    let move-dist 0
    set move-dist (item (ticks) move-cost) * grain / 1000

    if ca_aF > 0 [


     let new_wt2 forage  ca_aF_wt 0.48 move-dist 15 floor percap_patch cat_energy 200
     set ca_aF_wt item 0 new_wt2
     ask grazing_land [set cons_cat cons_cat + item 1 new_wt2]
]




 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

    if ca_aM > 0 [

     let new_wt3 forage  ca_aM_wt 0.48 move-dist 15 floor percap_patch cat_energy 250
     set ca_aM_wt item 0 new_wt3
     ask grazing_land [set cons_cat cons_cat + item 1 new_wt3]
     ]


      set ca_tot_wt sum (map [x -> sum x](list ca_aF_wt ca_aM_wt))

]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Update sheep foraging and wt gain

  ask hholds with [sh-tot > 0 ] [
    let move-dist 0
    ifelse past_type = "non-sedentary" [set move-dist (item (ticks) move-cost) * grain / 1000] [set move-dist 0]

    if sh_e > 0 [
     let percap_patch [percap_shp] of patch-here
     let new_wt forage  sh_e_wt 0.25 move-dist 10 floor percap_patch sh_energy 32
     set sh_e_wt item 0 new_wt
     ask patch-here [set cons_sh cons_sh + item 1 new_wt]

     ]

  ;;;;;;;;;;;;;;;;;;;

    if sh_r > 0 [

     let percap_patch [percap_shp] of patch-here
     let new_wt forage  sh_r_wt 0.25 move-dist 10 floor percap_patch sh_energy 34
     set sh_r_wt item 0 new_wt
     ask patch-here [set cons_sh cons_sh + item 1 new_wt]
    ]


     set sh_tot_wt sum (map [x -> sum x] (list sh_e_wt sh_r_wt))  ;update total sheep wt

  ]

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


 ;; Update foraging and wt gain of goats and camels

 ask hholds with [cam-tot > 0] [

     let move-dist 0
     ifelse past_type = "non-sedentary" [set move-dist (item (ticks) move-cost) * grain / 1000] [set move-dist 0]

     if cam_aF > 0 [

     let percap_patch [percap_cam] of patch-here
     let new_wt forage  cam_aF_wt 0.314 move-dist 10 percap_patch cam_energy 350
     set cam_aF_wt item 0 new_wt
      ask patch-here [set cons_cam cons_cam + item 1 new_wt]
     ]

;;;;;;;;;

     if cam_aM > 0 [

     let percap_patch [percap_cam] of patch-here
     let new_wt forage  cam_aM_wt 0.314 move-dist 10 percap_patch cam_energy 400
     set cam_aM_wt item 0 new_wt
     ask patch-here [set cons_cam cons_cam + item 1 new_wt]
       ]

    set cam_tot_wt sum (map [x -> sum x](list cam_aF_wt cam_aM_wt))  ; Update total cattle wt


  ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  ask hholds with [gt-tot > 0] [

    let move-dist 0
    ifelse past_type = "non-sedentary" [set move-dist (item (ticks) move-cost) * grain / 1000] [set move-dist 0]

    if gt_b > 0 [

    let percap_patch [percap_gt] of patch-here
     let new_wt forage  gt_b_wt 0.3 move-dist 10 percap_patch gt_energy 34
     set gt_b_wt item 0 new_wt
     ask patch-here [set cons_gt cons_gt + item 1 new_wt]

    ]
;;;;;;;;;;;;;;;;;;;;;
     if gt_d > 0 [

     let percap_patch [percap_gt] of patch-here
     let new_wt forage  gt_d_wt 0.3 move-dist 10 percap_patch gt_energy 32
     set gt_d_wt item 0 new_wt
     ask patch-here [set cons_gt cons_gt + item 1 new_wt]

     ]

    set gt_tot_wt sum (map [x -> sum x](list gt_b_wt gt_d_wt))  ; Update total cattle wt


  ]

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

    ;; Deplete patches
    ;; the fraction of each pool grazed is calculated as follows: (total consumed / total forage) * (fraction of each pool considered) * (fraction deemed unavailable)
   ;;  not all of the  available dead herb and shrub and tree can be cosumed whereas all of the green herb, shrub, and tree is that is available can also be consumed
   ;; For sites where livestock grazing is not simulated (eg. areas outside Kenya, non-pastoral areas in Kenya), we set the fraction grazed to a fixed value

   ask patches with [cons_cat + cons_sh + cons_gt + cons_cam > 0][

    set green_herb (((cons_cat / (cattle-forage + 1)) * (item 0 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 0 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 0 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 0 cam-per-pools))) * ( 1 - unavailable)
    set dead_herb (((cons_cat / (cattle-forage + 1)) * (item 1 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 1 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 1 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 1 cam-per-pools))) * ( 1 - unavailable)
    set green_shrub ( ((cons_cat / (cattle-forage + 1)) * (item 2 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 2 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 2 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 2 cam-per-pools))) * ( 1 - unavailable)
    set dead_shrub (((cons_cat / (cattle-forage + 1)) * (item 3 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 3 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 3 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 3 cam-per-pools))) * ( 1 - unavailable)
    set shrub_brnch (((cons_cat / (cattle-forage + 1)) * (item 4 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 4 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 4 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 4 cam-per-pools))) * ( 1 - unavailable)
    set green_tree (((cons_cat / (cattle-forage + 1)) * (item 5 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 5 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 5 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 5 cam-per-pools))) * ( 1 - unavailable)
    set dead_tree (((cons_cat / (cattle-forage + 1)) * (item 6 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 6 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 6 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 6 cam-per-pools))) * ( 1 - unavailable)
    set tree_brnch (((cons_cat / (cattle-forage + 1)) * (item 7 cat-per-pools)) + ((cons_sh / (sheep-forage + 1)) * (item 7 sh-per-pools)) +((cons_gt / (goat-forage + 1)) * (item 7 gt-per-pools)) + ((cons_cam / (camel-forage + 1)) * (item 7 cam-per-pools))) * ( 1 - unavailable)

  ]


  ask patches with [((cons_cat + cons_sh + cons_gt + cons_cam) = 0) and green_herb > -9999]   ;; Sites where livestock did not graze.
    [
      set green_herb 0.001 * grazing
      set dead_herb 0.001 * grazing
      set green_shrub 0.001 * grazing
      set dead_shrub 0.001 * grazing
      set shrub_brnch 0.0001 * grazing
      set green_tree 0.01 * grazing
      set dead_tree 0.001 * grazing
      set tree_brnch 0.0001 * grazing
  ]




end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; In this procedure animals survive or die depending on body condition and they transition to appropriate age cohorts. Two seperate reproters
;; are created (grow-f and grow-m), one for each sex.
;;age: List of ages of inidviduals in each species-sex-age group
;;wt:List of body weights of inidviduals in each species-sex-age group
;; num: Total number of individuals in each species-age-sex group
;; u v w x : Parameters for species and sex specific Brody curves
;;lact-ind: List indicating which females are lactating
;; max-age: Maximum age to which a species lives
;;Meat-from-dead: Total body weight of animals that failed to survive. In the 'produce' procedure, this is used to tally total meat available from dead animals
;; These procedures, body
to-report grow-f [age wt num max-age-wt compare-age compare-wt max-wt lact-ind max-age meat-from-dead dead-an]

  let exp_wt []
  foreach age [x ->
    ifelse x < max-age-wt
     [let pos position x compare-age
      let id-wt item pos compare-wt
      set exp_wt lput id-wt exp_wt]
     [set exp_wt lput max-wt exp_wt]
  ]
   ;let exp_wt map [n -> u * (1 - exp(- v * w * n / x))] age  ;;


  let BC (map [ [a b] -> a / b] wt exp_wt)
  let DR map [i -> 1 -(precision ((exp (-4 + 9 * i )) / (1 + exp (-4 + 9 * i))) 3)] BC    ;;
  set age map [n -> n + 1] age
  let temp n-values num [random-float 1]
  let dead (map [[a b c] -> (ifelse-value a < b [0]
                                          c > max-age [0]
                                              [1])] temp DR age)
  set meat-from-dead []
  (foreach dead wt [[a b] -> set meat-from-dead lput ((1 - a) * b) meat-from-dead])
   set wt (map [ [a b] -> a * b ] dead wt)
   set wt remove 0 wt
   set age (map [[a b] ->  a * b ] dead age)
   set age remove 0 age
   set num length wt
   set lact-ind map [a -> a + 1] lact-ind ;; 0 becomes 1 and 1 becomes 2
   set lact-ind (map [[a b] -> a * b ] dead lact-ind) ;;
   set lact-ind remove 0 lact-ind
   set lact-ind map[a -> a - 1] lact-ind
   set meat-from-dead sum meat-from-dead
   set dead-an (length dead - sum dead)

  report (list age wt num lact-ind meat-from-dead dead-an)

end

to-report grow-m [age wt num max-age-wt compare-age compare-wt max-wt max-age meat-from-dead dead-an]

  let exp_wt []
  foreach age [x ->
    ifelse x < max-age-wt
     [let pos position x compare-age
      let id-wt item pos compare-wt
      set exp_wt lput id-wt exp_wt]
     [set exp_wt lput max-wt exp_wt]
  ]

  ;let exp_wt map [n -> u * (1 - exp(- v * w * n / x))] age  ;; These brody parms need to be flexible to accommodate multiple species
  let BC (map [ [a b] -> a / b] wt exp_wt)  ; Calculate body condition
  let DR map [i -> precision (1 - (exp (-4 + 9 * i )) / (1 + exp (-4 + 9 * i))) 3] BC ;;Caculate monthly death rate based on body condition. Max monthly survival set to 0.99 from 0.995
  set age map [n -> n + 1] age
  let temp n-values num [random-float 1]
  let dead (map [[a b c] -> (ifelse-value  a < b [0]  ; Animals may die due to poor body condition or age
                                           c > max-age [0]
                                                [1])] temp DR age)
  set meat-from-dead[]
  (foreach dead wt [[a b] -> set meat-from-dead lput ((1 - a) * b) meat-from-dead])
   set wt (map [ [a b] -> a * b ] dead wt)
   set wt remove 0 wt
   set age (map [[a b] ->  a * b ] dead age)
   set age remove 0 age
   set num length wt
   set meat-from-dead sum meat-from-dead
   set dead-an (length dead - sum dead)
   report (list age wt num meat-from-dead dead-an)

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Individuals are transitioned to appropriate age cohorts
;; calf: number of pre-weaned individuals of each species in a household
;; weaned-f and weaned-m : List of ages of adult female and male individuals of a species in a household (e.g. ca_aF_ag for adult cows)
;; wean-age: Age at which young ones are weaned and become adults (start consuming forage)
;;lact-ind: List of lactating individuals of each species in a hhold
;; calf_dr: The montly death rate fro pre-weaning individuals of each species
;;calf-wt-mean, calf-wt-sd: The mean weight and standard deviation of individuals at weaning age for each species

to-report transition-age [calf weaned-f weaned-m  weaned-f-wt weaned-m-wt wean-age lact-ind calf_dr calf-wt-mean calf-wt-sd]
if length calf != 0 [
set calf map [a -> a + 1] calf
let i 0
foreach calf [a  ->                        ;; Remove individuals from cohort who do not survive
    ifelse random-float 1 < calf_dr
      [set calf remove-item i calf]
      [set i i + 1]
    ]
 let j 0
 foreach calf [a ->                        ;; Check if surviving individuals are above weaning age
    ifelse a > wean-age [
      ifelse random-float 1 > 0.5      ;; If so, randomly sort them into male and female post weaning (adult) cohorts.
      [set weaned-m lput a weaned-m
       set weaned-m-wt lput (calf-wt-mean + random-normal 0 calf-wt-sd)  weaned-m-wt
       set calf remove-item j calf]
      [set weaned-f lput a weaned-f
       set weaned-f-wt lput (calf-wt-mean + random-normal 0 calf-wt-sd) weaned-f-wt
       set calf remove-item j calf
       set lact-ind lput 0 lact-ind]
      ]
      [set j j + 1]
    ]
  ]

  report (list weaned-f weaned-f-wt weaned-m weaned-m-wt calf lact-ind )
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


to grow-herd          ;; Here we create a variable that measures the difference between the ideal and realized body weights of herds.
                      ;; We start by drawing weights based on age from a Brody Curve specified for males and females.
                      ;; The weights of each individual is then compared to their ideal weight and a ratio is obtained

  let cat_pop1 sum [cat-tot] of hholds
  let cam_pop1 sum [cam-tot] of hholds
  let gt_pop1 sum [gt-tot] of hholds
  let sh_pop1 sum [sh-tot] of hholds


  ask hholds [set dead-meat 0]
  ;; Grow cattle herd

  ask hholds with [cat-tot > 0 ] [
    let temp_aF  grow-f ca_aF_ag ca_aF_wt ca_aF 16 cat_age cat_wt_age 200 fem_lact 144 dead-meat dead-caF
    set ca_aF_ag item 0 temp_aF
    set ca_aF_wt item 1 temp_aF
    set ca_aF item 2 temp_aF
    set fem_lact item 3 temp_aF
    set dead-meat-ca item 4 temp_aF
    set dead-caF item 5 temp_aF

    let temp_aM  grow-m ca_aM_ag ca_aM_wt ca_aM 18 cat_age cat_wt_age 250 144 dead-meat dead-caM
    set ca_aM_ag item 0 temp_aM
    set ca_aM_wt item 1 temp_aM
    set ca_aM item 2 temp_aM
    set dead-meat-ca  item 3 temp_aM
    set dead-caM item 4 temp_aM

  ; If the ages of individuals are over the maximum for the cohort thery are in , we transition these individuals to the next cofort. If
; it is a birthing month individuals are born to a portion of the females and these calves are added to the calf cohort. Birth rates are functions of the BC of the females

   ;Transition pre-weaning individuals to post-weaning cohort

   let temp_trans transition-age ca_calves_ag ca_aF_ag ca_aM_ag ca_aF_wt ca_aM_wt 8 fem_lact ca_calf_dr 100 2
    set ca_aF_ag item 0 temp_trans
    set ca_aF_wt item 1 temp_trans
    set ca_aM_ag item 2 temp_trans
    set ca_aM_wt item 3 temp_trans
    set ca_calves_ag item 4 temp_trans
    set fem_lact item 5 temp_trans
    ; Update totals: The total number of animals in each cohort is updated to reflect the transitions
     set ca_calves length ca_calves_ag
     set ca_aF length ca_aF_wt
     set ca_aM length ca_aM_wt
     set cat-tot sum (list ca_aF ca_aM)
     ;set cat matrix:from-column-list (list(list ca_aF  ca_aM))
    set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))]

  ;;; Stochastic loss of herds to conflict; Pastoralists who are on lands outside their county may experience loss of cattle herds to conflict with a 5 % monthly probability

ask hholds[
         let raid-loss-temp 0
         let raid-tribe-temp 0
 if risk = 1 and cat-tot > 0 [

         if random-float 1 < 0.05 [     ;; Any month, there is a 5 % chance of a raid
         set cat-tot 0
         set ca_aF 0
         set ca_aM 0
         set ca_aF_wt []
         set ca_aF_ag []
         set fem_lact []
         set ca_aM_ag []
         set ca_aM_wt []
         set ca_calves 0
         set ca_calves_ag []
         set ca_tot_wt 0
         set raid-loss-temp 1
         set raid-tribe-temp [tribe] of grazing_land]]

  set raid-loss lput raid-loss-temp raid-loss
  set raid-tribe lput raid-tribe-temp raid-tribe

  ]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ; Grow camel herd


ask hholds with [cam-tot > 0 ] [

 ; DETERMINE DEATH RATES BASED ON BODY CONDITION AND ADJUST COHORTS
    let temp_cam_aF  grow-f cam_aF_ag cam_aF_wt cam_aF 17 cam_age cam_wt_age 350 cam_fem_lact 288 dead-meat-cam dead-camF
    set cam_aF_ag item 0 temp_cam_aF
    set cam_aF_wt item 1 temp_cam_aF
    set cam_aF item 2 temp_cam_aF
    set cam_fem_lact item 3 temp_cam_aF
    set dead-meat-cam item 4 temp_cam_aF
    set dead-camF item 5 temp_cam_aF

    let temp_cam_aM  grow-m cam_aM_ag cam_aM_wt cam_aM 19 cam_age cam_wt_age 400 288 dead-meat-cam dead-camM
    set cam_aM_ag item 0 temp_cam_aM
    set cam_aM_wt item 1 temp_cam_aM
    set cam_aM item 2 temp_cam_aM
    set dead-meat-cam item 3 temp_cam_aM
    set dead-camM item 4 temp_cam_aM

 ;  Transition to post weaning cohorts all calves older than 7 months

    let temp_trans2 transition-age cam_calves_ag cam_aF_ag cam_aM_ag cam_aF_wt cam_aM_wt 7 cam_fem_lact cam_calf_dr 150 2
    set cam_aF_ag item 0 temp_trans2
    set cam_aF_wt item 1 temp_trans2
    set cam_aM_ag item 2 temp_trans2
    set cam_aM_wt item 3 temp_trans2
    set cam_calves_ag item 4 temp_trans2
    set cam_fem_lact item 5 temp_trans2

    ; Update totals: The total number of animals in each cohort is updated to reflect the transitions
     set cam_calves length cam_calves_ag
     set cam_aF length cam_aF_wt
     set cam_aM length cam_aM_wt
     set cam-tot sum (list cam_aF cam_aM)
     ;set cam matrix:from-column-list (list(list cam_aF  cam_aM))
     set cam_tot_wt sum (map [x -> sum x] (list cam_aF_wt cam_aM_wt))

  ]

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  ; Grow goat herd
  ask hholds with [gt-tot > 0 ] [

  ; DETERMINE DEATH RATES BASED ON BODY CONDITION AND ADJUST COHORTS
    let temp_gt_d  grow-f gt_d_ag gt_d_wt gt_d 16 gt_age gt_wt_age 32 gt_fem_lact 60 dead-meat-gt dead-gtd
    set gt_d_ag item 0 temp_gt_d
    set gt_d_wt item 1 temp_gt_d
    set gt_d item 2 temp_gt_d
    set gt_fem_lact item 3 temp_gt_d
    set dead-meat-gt item 4 temp_gt_d
    set dead-gtd item 5 temp_gt_d

    let temp_gt_b  grow-m gt_b_ag gt_b_wt gt_b 17 gt_age gt_wt_age 34 60 dead-meat-gt dead-gtb
    set gt_b_ag item 0 temp_gt_b
    set gt_b_wt item 1 temp_gt_b
    set gt_b item 2 temp_gt_b
    set dead-meat-gt item 3 temp_gt_b
    set dead-gtb item 4 temp_gt_b


  ;;Transition individuals between pre and post weaning cohorts

    let temp_trans3 transition-age gt_kids_ag gt_d_ag gt_b_ag gt_d_wt gt_b_wt 3 gt_fem_lact gt_kids_dr 10 1
    set gt_d_ag item 0 temp_trans3
    set gt_d_wt item 1 temp_trans3
    set gt_b_ag item 2 temp_trans3
    set gt_b_wt item 3 temp_trans3
    set gt_kids_ag item 4 temp_trans3
    set gt_fem_lact item 5 temp_trans3

 ; Update totals: The total number of animals in each cohort is updated to reflect the transitions
     set gt_kids length gt_kids_ag
     set gt_d length gt_d_wt
     set gt_b length gt_b_wt
     set gt-tot sum (list gt_d gt_b)
     ;set gt matrix:from-column-list (list(list gt_d  gt_b))
     set gt_tot_wt sum (map [x -> sum x] (list gt_d_wt gt_b_wt))

  ]

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


 ; Grow sheep herd
  ask hholds with [sh-tot > 0 ] [

  ; DETERMINE DEATH RATES BASED ON BODY CONDITION AND ADJUST COHORTS
    let temp_sh_e  grow-f sh_e_ag sh_e_wt sh_e 14 sh_age sh_wt_age 32 sh_fem_lact 60 dead-meat-sh dead-she
    set sh_e_ag item 0 temp_sh_e
    set sh_e_wt item 1 temp_sh_e
    set sh_e item 2 temp_sh_e
    set sh_fem_lact item 3 temp_sh_e
    set dead-meat-sh item 4 temp_sh_e
    set dead-she item 5 temp_sh_e

   let temp_sh_r  grow-m sh_r_ag sh_r_wt sh_r 14 sh_age sh_wt_age 34 60 dead-meat-sh dead-shr
    set sh_r_ag item 0 temp_sh_r
    set sh_r_wt item 1 temp_sh_r
    set sh_r item 2 temp_sh_r
    set dead-meat-sh item 3 temp_sh_r
    set dead-shr item 4 temp_sh_r

  ; TRANSITION INDIVIDUALS between pre and post weaning cohorts

    let temp_trans4 transition-age sh_lambs_ag sh_e_ag sh_r_ag sh_e_wt sh_r_wt 3 sh_fem_lact sh_lambs_dr 10 1
    set sh_e_ag item 0 temp_trans4
    set sh_e_wt item 1 temp_trans4
    set sh_r_ag item 2 temp_trans4
    set sh_r_wt item 3 temp_trans4
    set sh_lambs_ag item 4 temp_trans4
    set sh_fem_lact item 5 temp_trans4

; Update totals: The total number of animals in each cohort is updated to reflect the transitions
     set sh_lambs length sh_lambs_ag
     set sh_e length sh_e_wt
     set sh_r length sh_r_wt
     set sh-tot sum (list sh_e sh_r)
     ;set shp matrix:from-column-list (list(list sh_e  sh_r))
     set sh_tot_wt sum (map [x -> sum x] (list cam_aF_wt cam_aM_wt))

  ]

  set cat-dr ((sum [dead-caM + dead-caF] of hholds) / cat_pop1) * 100
  set cam-dr ((sum [dead-camM + dead-camF] of hholds) / cam_pop1) * 100
  set gt-dr ((sum [dead-gtd + dead-gtb] of hholds) / gt_pop1) * 100
  set sh-dr ((sum [dead-shr + dead-she] of hholds) / sh_pop1) * 100

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Animals reproduce and produce milk
;;min_age - max_age; Min and maximuma ge of reporduction for each species
;;rep-calendar: Month when species reproduce
;;lactating-ind Species specific list of lactating individuals in a hhold
;; fem-age, fem-wt List with ages and weights of female cohort of each species
;; calves- total number of pre-weanied individuals of each speceies
;;calf-ag - lsit with ages of pre-weaned individuals of each species
;; milk-calendar- motnhs when each species produces milk
;; sp-milk-prod - maximum mulk production by the species in that month
;; sp-milk - total milk prduced by the species that month in a month
;; j k l m -- Species specific Brody parameters
;; rep-rate -- The fraction of adult females of each species that can reproduce in any given year





to-report reproduce [min_age max_age rep-calendar lactating-ind fem-age fem-wt calves calf-ag milk-calendar sp-milk-prod rep-rate compare-age compare-wt max-age-wt max-wt ]

  set month ticks - (12 * floor (ticks / 12))
    if member? ticks n-values years [x -> x * 12] [ set month 0]



 if item (month)  rep-calendar = 1 [
      set lactating-ind []                                                           ; Reset the lactation tracker
        let expWt []
        foreach fem-age [x ->
        ifelse x < max-age-wt
       [let pos position x compare-age
       let id-wt item pos compare-wt
         set expWt lput id-wt expWt]
        [set expWt lput max-wt expWt]]                                                 ; calculate expected wt for females
      let BC_aF (map [ [a b] -> a / b ] fem-wt expWt)                                ; Caluclate body condition for females

      (foreach BC_aF fem-age
         [ [a b] -> ifelse (a >= 0.8 and b < max_age and b > min_age and random-float 1 < (item month rep-rate))  ; Only females with body condition above 0.8 and age between min and max years can breed (Arbitrary!)
                                                            ; Individuals that meet this requirement produce one calf and enter lactation status.
          [set calves calves + 1                            ; Individuals that do not meet this requirement do not reproduce and do not lactate.
             set calf-ag fput  0 calf-ag
             set lactating-ind lput 1 lactating-ind]
          [  set calves calves
             set calf-ag calf-ag
             set lactating-ind lput 0 lactating-ind]
                    ])

       ]

  let milk-produced 0
  ifelse item month milk-calendar = 1  and lactating-ind != 0                 ; If it is a milking month each household gets milk depending on number of lactating females
    [   let expWt []
        foreach fem-age [x ->
        ifelse x < max-age-wt
       [let pos position x compare-age
       let id-wt item pos compare-wt
         set expWt lput id-wt expWt]
        [set expWt lput max-wt expWt]]                  ; calculate expected wt for females
      let BC_aF (map [ [a b] -> a / b ] fem-wt expWt)                                ; Caluclate body condition for females
      set milk-produced (sum lactating-ind) * item month sp-milk-prod * mean BC_aF ]         ; Milk production is determined by body condition.
     [set milk-produced 0]

   report (list lactating-ind calves calf-ag milk-produced)




end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 to produce   ;; parms based on McCabe 2004

 ask hholds [set cow-milk 0
             set camel-milk 0
             set gt-milk 0
             set sh-milk 0]





  ask turtles with [ca_aF > 0]  [
   let production reproduce 36 120 cat-breed fem_lact ca_aF_ag ca_aF_wt ca_calves ca_calves_ag cat-milk milk_prod cat-rep-rate cat_age cat_wt_age 16 200
   set fem_lact item 0 production
   set ca_calves item 1 production
   set ca_calves_ag item 2 production
   set cow-milk item 3 production ]

 ask turtles with [cam_aF > 0]  [
   let production reproduce 48 240 cam-breed cam_fem_lact cam_aF_ag cam_aF_wt cam_calves cam_calves_ag cam-milk cam_milk_prod cam-rep-rate cam_age cam_wt_age 17 350
   set cam_fem_lact item 0 production
   set cam_calves item 1 production
   set cam_calves_ag item 2 production
   set camel-milk item 3 production ]


 ask turtles with [gt_d > 0]  [
   let production reproduce 18 60 shoat-breed gt_fem_lact gt_d_ag gt_d_wt gt_kids gt_kids_ag shoat-milk shoat_milk_prod sht-rep-rate gt_age gt_wt_age 16 32
   set gt_fem_lact item 0 production
   set gt_kids item 1 production
   set gt_kids_ag item 2 production
   set gt-milk item 3 production ]


 ask turtles with [sh_e > 0]  [
   let production reproduce 18 60 shoat-breed sh_fem_lact sh_e_ag sh_e_wt sh_lambs sh_lambs_ag shoat-milk shoat_milk_prod sht-rep-rate sh_age sh_wt_age 14 32
   set sh_fem_lact item 0 production
   set  sh_lambs item 1 production
   set sh_lambs_ag item 2 production
   set sh-milk item 3 production ]


set month ticks - (12 * floor (ticks / 12))
 if member? ticks n-values years [x -> x * 12] [ set month 0]

  if item month m_harvest = 1
    [ask turtles with [agrop = 1]
      [let maize_produced  ((ag_land * greenH / 1500) * 1000)   ; Maize harvest is set at 1000 kgs per hectare in the best possible scenario. Its depelted as a proportion of
                                                             ;; current green herb biomass relative to a high maximum value (1500 gm / sq m).
                                                              ;; Maize is sold at maize price and input costs are subtratced. input cost = 1200ksh / 90kg
      set cash_in_hand cash_in_hand + (maize_produced * maize_price) - ((maize_produced / 90) * 1200)]]

end





;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Calories requirement and calories from various sources are tallied. First hholds calorie requirements are tallied as the calorie required per adult equivalent for the month

to calorie-counter


  set month ticks - (12 * floor (ticks / 12))
    if member? ticks n-values years [x -> x * 12] [ set month 0]



  ask hholds [

    set food_sufficiency ""             ; reset household food sufficiency values


    set tot_calreq_month sum (map [[a b] -> a * b ] hh_mem mem_calreq) * (item month m_days)  ; Total calories required by hhold each month

    ; Total calories from milk
    set cal_milk (milk_cal_cow * cow-milk) + (milk_cal_cam * camel-milk)  + (milk_cal_sh * sh-milk) + (milk_cal_gt * gt-milk)  ; Calories from milk
    ; Total calories from maize
    set cal_maize maize_cal * maize
    ; Total calories from animals that died of natural causes
    set dead-meat dead-meat-ca + dead-meat-cam + dead-meat-gt + dead-meat-sh

    ;; Determine if slaughter occurs and determine calories obtained from meat; Here we assume ceremonial slaughter of a bull

    let slaughter 0
   if random-float 1 < opportunistic_slaughter [set slaughter 1]  ; opportunistic slaughter is the probability of slaughter in a month

   if slaughter = 1 and (sh_r > 0 or gt_b > 0)[   ; Whether ram or buck is killed depends on abundance

     if sh_r > gt_b
     [let animal_slaughtered random sh_r  ; pick the id of the animal that is slaughtered
       set cal_meat meat_cal * (item animal_slaughtered sh_r_wt * 0.3 + dead-meat * 0.3 * 0.3)   ; 30 % of the weight of the animal slaughtered is available
       set sh_r_ag remove-item animal_slaughtered sh_r_ag                                        ; Total meat from dead is the weight of slaughtered animal and 9 % of the total
       set sh_r_wt remove-item animal_slaughtered sh_r_wt                                        ; weight of animals that died from natural causes. 30% dead animals retrieved and 30 % of retrieved
       set sh_r length sh_r_wt]                                                                  ; dead animals may be consumed


     if sh_r < gt_b
     [let animal_slaughtered random gt_b  ; pick the id of the animal that is slaughtered
       set cal_meat meat_cal * (item animal_slaughtered gt_b_wt * 0.3 + dead-meat * 0.3 * 0.3)   ; 30 % of the weight of the animal slaughtered is available
       set gt_b_ag remove-item animal_slaughtered gt_b_ag                                        ; Total meat from dead is the weight of slaughtered animal and 9 % of the total
       set gt_b_wt remove-item animal_slaughtered gt_b_wt                                        ; weight of animals that died from natural causes. 30% dead animals retrieved and 30 % of retrieved
       set gt_b length gt_b_wt]
    ]



    if slaughter = 0
    [set cal_meat meat_cal * dead-meat * 0.95 * 0.3]; dead animal weights * proportion edible animals * proprotion body weight that can be consumed

    set liv_cal (cal_meat + cal_milk) / tot_calreq_month
    ;; Update livestock totals and weight

    set sh-tot sum (list sh_r sh_e)
    set sh_tot_wt sum (map [x -> sum x] (list sh_r_wt sh_e_wt))

    set gt-tot sum (list gt_b gt_d)
    set gt_tot_wt sum (map [x -> sum x] (list gt_b_wt gt_d_wt))

    set cal_ava (cal_milk + cal_meat + cal_maize)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;  Determine cal needs remaining after calories from milk is used

    set maize_cons 0
    set cal_needs 0

   set cal_needs1 tot_calreq_month - cal_milk


    ifelse cal_needs1 <=  0                                 ; if sufficient milk is available, fill caories needs with milk
      [set cal_needs 0                                      ; if not, deplete milk and set food sufficiency as deficient
       set food_sufficiency  "sufficient"
       set sufficiency-source  "milk"
       set cal_milk cal_milk - tot_calreq_month]
      [set food_sufficiency  "deficient"
       ifelse cal_milk > 0 [set sufficiency-source "milk"][set sufficiency-source ""]
       set cal_needs cal_needs1
       set cal_milk 0

    ]
  ]

  ask hholds with [food_sufficiency = "deficient"][       ; if sufficient meat is available, fill remaining caories needs with meat
       set cal_needs2 cal_needs - cal_meat                 ; if not, deplete meat and set food sufficiency as deficient

       ifelse cal_needs2 <= 0
      [set food_sufficiency  "sufficient"
       set sufficiency-source  (word sufficiency-source "meat")
       set cal_meat cal_meat - cal_needs
       set cal_needs 0]
      [set food_sufficiency  "deficient"
       ifelse cal_meat > 0 [set sufficiency-source (word sufficiency-source "meat")][set sufficiency-source (word sufficiency-source "")]
       set cal_meat 0
       set cal_needs cal_needs2
       ]
      ]

  ask hholds with [food_sufficiency = "deficient"] [       ; if sufficient maize is available, fill remaining caories needs with maize
      set cal_needs3 cal_needs - cal_maize                  ; if not, deplete maize and set food sufficiency as deficient
      ifelse cal_needs3 <= 0
    [set food_sufficiency  "sufficient"
     set sufficiency-source  (word sufficiency-source "maize")
     set maize maize - (cal_needs / maize_cal)
      set maize_cons (cal_needs / maize_cal)
      set cal_needs 0]

    [set food_sufficiency  "deficient"
     ifelse cal_maize > 0 [set sufficiency-source (word sufficiency-source "maize")][set sufficiency-source (word sufficiency-source "")]
      set maize_cons maize
      set maize 0
     set cal_needs cal_needs3
     ]
  ]

  ask hholds with [food_sufficiency = "deficient"] [           ; Food deficient holds are those that fail to meet less than 90 % of total monthly calorie needs. Label rest as sufficient.
     ifelse cal_needs > 0.1 * tot_calreq_month
    [set food_sufficiency  "deficient"]
     [set food_sufficiency  "sufficient"]
    ]

  ask hholds [ifelse maize_cons * maize_cal > 0.8 * tot_calreq_month [set store_cal 1][set store_cal 0]]



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The recurring monthly expenses and income is tallied and differences drive livestock purchase and sales decisions. An economic state determines whether household is in debt or is assetless
;; The expenses and income are tallied over a three month period, the current month + two months in the future. So when income is gained in the current month, some of it is used to pay off the
;; months expenses. Similarly, the cash in hand reflects existing cash earned from sales and income for the month.

to cash-flow


set month ticks - (12 * floor (ticks / 12))
    if member? ticks n-values years [x -> x * 12] [ set month 0]


  ask hholds [            ; Six temporary indicators of whether sale or purchase of each livestock type occurs in the month

  set sales_ca 0
  set sales_cam 0
  set sales_sht 0
  set purchases_ca 0
  set purchases_cam 0
  set purchases_sht 0
  set sale_income 0

   set assets 0 ; reset indicator of asset holdings
    ;; Calculate monthly expenses as sum of general veterinary food expenses and the expenses towards meeting calorie deficits.
   let temp-TLU cam-tot + cat-tot  + gt-tot * 0.1 + sh-tot * 0.1 ; Convert livestock holding to TLU

   ;; Tally expenses

   let expenses ((AE *  100) + (temp-TLU * 25) +  ((tot_calreq_month / 3700) * Maize_price) ) * 3  ; 100 Ksh  general expenses per family member; We assume 25 Ksh / TLU as vet expenses Thornton et al., 2014;


   set cash_in_hand cash_in_hand + labour  + business + base_income ; Update cash in hand with income from labour , business or base_income for the month

   let income cash_in_hand + ((labour + business + base_income) * 2)     ;; income is what is available in hand + current month income + income over next 2 months from assured sources (labour, business)


    ;; If expenses  are greater than income
    if expenses >  income                                               ; If expenses are greater that twice the income.

          [ifelse cat-tot > 0 or gt-tot > 0 or sh-tot > 0 or cam-tot > 0   ;If the hhold has any livestock
           [ifelse expenses -  income  > 10000                              ; and If expenses - income are greater than 5000 Ksh
              [set sell  0                                                 ; start steps to sell one or more individuals. There is a preference to sell males over females

             if sell = 0 and ca_aM > 1                                     ; If an adult bull is avaialble, sell it.

                 [let animal_sold position (max ca_aM_wt)  ca_aM_wt
                     set ca_aM_wt remove-item animal_sold ca_aM_wt
                     set ca_aM_ag remove-item animal_sold ca_aM_ag
                     set ca_aM length ca_aM_wt
                     set cash_in_hand cash_in_hand + item month income_catcam
                     set sell 1
                     set sales_ca 1
                     set sale_income item month income_catcam]

             if sell = 0 and ca_aF > 1                                     ; Else sell a cow if one is available
                   [let animal_sold position (max ca_aF_wt) ca_aF_wt
                     set ca_aF_wt remove-item animal_sold ca_aF_wt
                     set ca_aF_ag remove-item animal_sold ca_aF_ag
                     set fem_lact remove-item animal_sold fem_lact
                     set ca_aF length ca_aF_wt
                     set cash_in_hand cash_in_hand + item month income_catcam
                     set sell 1
                     set sales_ca 1
                     set sale_income item month income_catcam]

             if sell = 0 and cam_aM > 1                                     ; Else sell a bull camel if one is available
                   [ let animal_sold position (max cam_aM_wt)  cam_aM_wt
                     set cam_aM_wt remove-item animal_sold cam_aM_wt
                     set cam_aM_ag remove-item animal_sold cam_aM_ag
                     set cam_aM length cam_aM_wt
                     set cash_in_hand cash_in_hand + item month income_catcam
                     set sell 1
                     set sales_cam 1
                     set sale_income item month income_catcam]

             if sell = 0 and cam_aF > 1                                      ; Else sell a cow camel if one is available
                   [let animal_sold position (max cam_aF_wt) cam_aF_wt
                     set cam_aF_wt remove-item animal_sold cam_aF_wt
                     set cam_aF_ag remove-item animal_sold cam_aF_ag
                     set cam_aF length cam_aF_wt
                     set cam_fem_lact remove-item animal_sold cam_fem_lact
                     set cash_in_hand cash_in_hand + item month income_catcam
                     set sell 1
                     set sales_cam 1
                     set sale_income item month income_catcam]

                if sell = 0 and sh_r > 3        ; or sell rams
                    [let num_sold 3
                     set sh_r_wt sublist sh_r_wt 3 sh_r
                     set sh_r_ag sublist sh_r_ag 3 sh_r
                     set sh_r length sh_r_wt
                     set cash_in_hand cash_in_hand + (item month income_shoat) * num_sold
                     set sell 1
                     set sales_sht num_sold
                     set sale_income (item month income_shoat) * num_sold]


              if sell = 0 and gt_b > 3         ; Else sell as may bucks as needed to earn amount needed
                    [let num_sold 3
                     set gt_b_wt sublist gt_b_wt 3 gt_b
                     set gt_b_ag sublist gt_b_ag 3 gt_b
                     set gt_b length gt_b_wt
                     set cash_in_hand cash_in_hand + (item month income_shoat) * num_sold
                     set sell 1
                     set sales_sht num_sold
                     set sale_income (item month income_shoat) * num_sold]

                   ]

                [set sell 0                                                     ;; If expenses are less than 3000 KsH; smaller stock are sold if at least 2 individuals are available

                 if sell = 0 and sh_r > 3
                    [let num_sold 1
                     set sh_r_wt sublist sh_r_wt 1 sh_r
                     set sh_r_ag sublist sh_r_ag  1 sh_r
                     set sh_r length sh_r_wt
                     set cash_in_hand cash_in_hand + item month income_shoat
                     set sell 1
                     set sales_sht num_sold
                     set sale_income item month income_shoat]

                if sell = 0 and gt_b > 3                                    ;; with a preference to sell males.
                    [let num_sold 1
                     set gt_b_wt sublist gt_b_wt 1 gt_b
                     set gt_b_ag sublist gt_b_ag 1 gt_b
                     set gt_b length gt_b_wt
                     set cash_in_hand cash_in_hand + item month income_shoat
                     set sell 1
                     set sales_sht num_sold
                     set sale_income item month income_shoat]

                 if sell = 0 and sh_e > 3
                    [let num_sold 1
                     set sh_e_wt sublist sh_e_wt 1 sh_e
                     set sh_e_ag sublist sh_e_ag  1 sh_e
                     set sh_fem_lact sublist sh_fem_lact 1 sh_e
                     set sh_e length sh_e_wt
                     set cash_in_hand cash_in_hand + item month income_shoat
                     set sell 1
                     set sales_sht num_sold
                     set sale_income item month income_shoat]

                if sell = 0 and gt_d > 3
                    [let num_sold 1
                     set gt_d_wt sublist gt_d_wt 1 gt_d
                     set gt_d_ag sublist gt_d_ag 1 gt_d
                     set gt_fem_lact sublist gt_fem_lact 1 gt_d
                     set gt_d length gt_d_wt
                     set cash_in_hand cash_in_hand + item month income_shoat
                     set sell 1
                     set sales_sht num_sold
                     set sale_income item month income_shoat]





                       ]
                  ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;ELSE  If livestock are not available

   [if cat-tot = 0 and gt-tot = 0 and sh-tot = 0 and cam-tot = 0 [set assets "assetless"]]]     ; If no livestock are avaiable to sell,
                                                                                                        ; if expenses not covered, set assetless

 ;; Update all livestock totals
    set cat-tot sum (list ca_aF ca_aM)
    ;set cat matrix:from-column-list (list(list ca_aF  ca_aM))
    set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))

   set cam-tot sum (list cam_aF cam_aM)
   set cam_tot_wt sum (map [x -> sum x] (list cam_aF_wt cam_aM_wt))

    set gt-tot sum (list gt_b gt_d)
    set gt_tot_wt sum (map [x -> sum x] (list gt_b_wt gt_d_wt))

    set sh-tot sum (list sh_r sh_e)
    set sh_tot_wt sum (map [x -> sum x] (list sh_r_wt sh_e_wt))

    set liv_sales_income lput sale_income liv_sales_income
; Deplete cash in hand to account for the months expenses such as general expenses, veterinary expenses and food expenses
 ;; Set maize stores food expenses / cost of unit calorie.
 ;; Prioritize food expenses first. If money is available, use it to buy food. Then decide if money can be used to complete other expenses.

    let food_money  cash_in_hand                                  ;; Maize available is compared against minimum needed to meet cal needs; 3700 kcal / kg maize
    let maize_needs (tot_calreq_month) / 3700

    if maize < (maize_needs) [                                            ;; if maize stores are less than the minimum needed
       ifelse food_money < maize_needs * Maize_price                             ;; ifelse cash in hand is less than needed


       [set maize maize + (food_money / Maize_price)
        set expenses expenses - (food_money)                          ;; If money is spent on maize, update expenses and cash_in_hand
        set cash_in_hand 0
        set maize_purchased (food_money / Maize_price)]

       [set maize maize + maize_needs                                ;; Use money for monthly food expeneses (150 Ksh / member) to update maize stores. 50 ksh /kg maize.Do this only if store is depleted
        set expenses expenses - (Maize_price * maize_needs)                       ;; If money is spent on maize, update expenses and cash_in_hand
        set cash_in_hand cash_in_hand - (maize_needs * Maize_price)
        set maize_purchased maize_needs]
    ]

    ifelse cash_in_hand > ((AE * 100) + (temp-TLU * 25))              ;; Can cash in hand (money from previous month + this months income) meet the months expenses?

     [set cash_in_hand cash_in_hand - ((AE * 50) + (temp-TLU * 25))  ;; The months genral and veterniary expenses are taken care of
      set expenses expenses - ((AE * 100) + (temp-TLU * 25))         ;; Adjust expenses to reflect this reality
      set economic_state lput "nodebt" economic_state]

    [ set cash_in_hand 0
      set economic_state lput "debt" economic_state]

     set income cash_in_hand + ((labour +  business + base_income) * 2)   ;; Update income to reflect the expenses that were met
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buying livestock
;; A distinction is made between homes that traditionally did and did not own camels. The ones that did not can look back over the last two years and assess the performance of cattle herds
;; and make a decision to buy camels for the first time. This is intended as an adaptive response. Homes that did traditionally own camels can assess performance of both cattle and camel herds
;; and decide based on performance what animal to buy

    set purchases_ca 0
    set purchases_sht 0
    set purchases_cam 0


   if   expenses <  income and food_sufficiency = "sufficient" [  ;;  Triggers to buy livestock . if income is > than anticipated expenses and hhold is not calorie deficient

      if  cash_in_hand > 10000 and camel-owner = 0 [         ; if household did not traditionally own camels and a large sum of cash is available

        let temp_lambda 1
        ifelse length hh-cat-lam > 24 [set temp_lambda mean (sublist hh-cat-lam (ticks - 23) (ticks - 1) )]  ;; Cattle survival over last 24 timesteps.
                      [set temp_lambda 1]
     ;else
        let sp 0                                                  ;; Buy sheep, goat or camels with roughly equal probability
         let temp random-float 1
          set sp (ifelse-value temp < 0.85 ["cat"]
                               temp < 0.9 ["gt" ]
                               temp < 0.95 ["shp"]
                                          ["cam"])

       if sp = "cat" and cat-tot < 200 [                                        ;  If cattle lambda over alst 2 years is greater than 0.9 or total cattle is less than the adult equivalents in the house

         ifelse ca_aM < 0.1 * cat-tot                                           ; if males are less than 10 % of the stock then buy a male, else buy females
            [set ca_aM ca_aM + 1
             set ca_aM_wt lput (floor abs random-normal 240 1) ca_aM_wt
             set ca_aM_ag lput  (random (84 - 36 + 1) + 36) ca_aM_ag
             set cash_in_hand cash_in_hand - (item month income_catcam)
             set purchases_ca 1]

             [set ca_aF ca_aF + 1
             set ca_aF_wt lput (floor abs random-normal 190 1) ca_aF_wt
             set ca_aF_ag lput  (random (45 - 37 + 1) + 37) ca_aF_ag
             set fem_lact lput 0 fem_lact
             set cash_in_hand cash_in_hand - (item month income_catcam)
             set purchases_ca 1]
           ]

          if sp = "gt" and gt-tot < 500[
            set gt_d gt_d + 3
            set gt_d_wt sentence gt_d_wt n-values 3 [random-normal 30 1]
            set gt_d_ag sentence gt_d_ag n-values 3 [24]
            set gt_fem_lact sentence gt_fem_lact n-values 3 [0]
            set cash_in_hand cash_in_hand - (item month income_shoat) * 3
            set purchases_sht 3]

          if sp = "shp" and sh-tot < 500
             [set sh_e sh_e + 3
             set sh_e_wt sentence sh_e_wt n-values 3 [random-normal 30 1]
             set sh_e_ag sentence sh_e_ag n-values 3 [24]
             set sh_fem_lact sentence sh_fem_lact n-values 3 [0]
             set cash_in_hand cash_in_hand - (item month income_shoat) * 3
             set purchases_sht 3]

         if sp = "cam" and cam-tot < 150
             [set cam_aF cam_aF + 1
             set cam_aF_wt lput (random-normal 350 1) cam_aF_wt
             set cam_aF_ag lput 60 cam_aF_ag
             set cam_fem_lact lput 0 cam_fem_lact
             set cash_in_hand cash_in_hand - (item month income_catcam)
             ;set camel-owner 1
             set purchases_cam 1]
          ]


  ;; Now look at households that are traditionally camel owners

     if cash_in_hand > 10000 and camel-owner = 1 [         ; if household did traditionaly own camels

        let sp  0
        let temp-lam-cam 1
        let temp-lam-cat 1
        ;let temp-random random-float 1

       ; ifelse length hh-cam-lam > 12 [set temp-lam-cam mean (sublist hh-cam-lam (ticks - 11) (ticks - 1))] [set temp-lam-cam 1]
        ;ifelse length hh-cat-lam > 12 [set temp-lam-cat mean (sublist hh-cat-lam (ticks - 11) (ticks - 1))] [set temp-lam-cat 1]

        ;set sp (ifelse-value temp-lam-cat > 0.9 ["cat"]   ; Do camel herds lose less than 20 % individuals monthly on average over 2 years
         ;                    temp-random < 0.6 ["cam"]   ; Do cattle herds lose less than 20 % individuals monthly on average over 2 years
          ;                   temp-random < 0.8 ["shp"] ; If above two are not true, then buy either sheep or goat (50 % probability)
            ;                                   ["gt"])
          let temp-random random-float 1
          set sp (ifelse-value temp-random < 0.4 ["cat"]   ; Do camel herds lose less than 20 % individuals monthly on average over 2 years
                               temp-random < 0.8 ["cam"]    ; Do cattle herds lose less than 20 % individuals monthly on average over 2 years
                               temp-random < 0.9 ["gt"]
                                                 ["shp"])


        if sp = "gt" and gt-tot < 500[
           set gt_d gt_d + 3
            set gt_d_wt sentence gt_d_wt n-values 3 [random-normal 30 1]
            set gt_d_ag sentence gt_d_ag n-values 3 [24]
            set gt_fem_lact sentence gt_fem_lact n-values 3 [0]
            set cash_in_hand cash_in_hand - (item month income_shoat) * 3
            set purchases_sht 3]

          if sp = "shp" and sh-tot < 500
             [set sh_e sh_e + 3
             set sh_e_wt sentence sh_e_wt n-values 3 [random-normal 30 1]
             set sh_e_ag sentence sh_e_ag n-values 3 [24]
             set sh_fem_lact sentence sh_fem_lact n-values 3 [0]
             set cash_in_hand cash_in_hand - (item month income_shoat) * 3
             set purchases_sht 3]

         if sp = "cam" and cam-tot < 150
             [set cam_aF cam_aF + 1
             set cam_aF_wt lput (random-normal 350 1) cam_aF_wt
             set cam_aF_ag lput 60 cam_aF_ag
             set cam_fem_lact lput 0 cam_fem_lact
             set cash_in_hand cash_in_hand - (item month income_catcam)
             set purchases_cam 1]

         if sp = "cat" and cat-tot < 200
        [set ca_aF ca_aF + 1
             set ca_aF_wt lput (floor abs random-normal 190 1) ca_aF_wt
             set ca_aF_ag lput  (random (45 - 37 + 1) + 37) ca_aF_ag
             set fem_lact lput 0 fem_lact
             set cash_in_hand cash_in_hand - (item month income_catcam)
             set purchases_ca 1]

      ]



     set cat-tot sum (list ca_aF ca_aM)                             ; Update all the livestock entries.
     set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))

     set cam-tot sum (list cam_aF cam_aM)                             ; Update all the livestock entries.
     set cam_tot_wt sum (map [x -> sum x] (list cam_aF_wt cam_aM_wt))

     set gt-tot sum (list gt_d gt_b)                             ; Update all the livestock entries.
     set gt_tot_wt sum (map [x -> sum x] (list gt_b_wt gt_d_wt))

     set sh-tot sum (list sh_r sh_e)                             ; Update all the livestock entries.
     set sh_tot_wt sum (map [x -> sum x] (list sh_r_wt sh_e_wt))

;;; If cash available is less than 10000 but greater than 3000


    if cash_in_hand > 5000 and cash_in_hand < 10000 [

       let sp 0
       ifelse random-float 1 < 0.6 [set sp "gt" ] [set sp "shp"]
       if sp = "gt" and gt-tot < 500[

             set gt_d gt_d + 1
             set gt_d_wt lput (floor abs random-normal 30 1) gt_d_wt
             set gt_d_ag lput  (random (36 - 12 + 1) + 12) gt_d_ag
             set gt_fem_lact lput 0 gt_fem_lact
             set cash_in_hand cash_in_hand - (item month income_shoat)
             set purchases_sht 1]
       if sp = "shp" and sh-tot < 500
             [set sh_e sh_e + 1
             set sh_e_wt lput (floor abs random-normal 30 1) sh_e_wt
             set sh_e_ag lput  (random (36 - 12 + 1) + 12) sh_e_ag
             set sh_fem_lact lput 0 sh_fem_lact
             set cash_in_hand cash_in_hand - (item month income_shoat)
             set purchases_sht 1]
      ]

     set gt-tot sum (list gt_d gt_b)                             ; Update all the livestock entries.
     set sh-tot sum (list sh_e sh_r)
     ;set cat matrix:from-column-list (list(list ca_aF  ca_aM))
     set gt_tot_wt sum (map [x -> sum x] (list gt_b_wt gt_d_wt))
     set sh_tot_wt sum (map [x -> sum x] (list sh_r_wt sh_e_wt))

    ]
   ;; Update counters for sales and purchases
  set sales_ca_m lput sales_ca sales_ca_m
  set sales_cam_m lput sales_cam sales_cam_m
  set sales_sht_m lput sales_sht sales_sht_m
  set purchases_ca_m lput purchases_ca purchases_ca_m
  set purchases_cam_m lput purchases_cam purchases_cam_m
  set purchases_sht_m lput purchases_sht purchases_sht_m

  ]

end

to exchange-stock   ;; If green herb availability is deemed high then hholds exchange 3 goats for a cow from the market.

  set month ticks - (12 * floor (ticks / 12))
    if member? ticks n-values years [x -> x * 12] [ set month 0]

if month = 2 [                      ;; In March, hholds with more than 20 does and green pastures
  ask hholds with [gt_d > 20 and [greenH] of grazing_land > 300]

      [set ca_aF ca_aF + 2
      set ca_aF_wt sentence n-values 2 [floor abs random-normal 190 5] ca_aF_wt      ;; Buy 2 cows
      set ca_aF_ag sentence n-values 2  [random (45 - 37 + 1) + 37] ca_aF_ag
      set fem_lact sentence n-values 2 [0] fem_lact


            set gt_d gt_d - 6                                               ;; In exchange for 6 goats
            set gt_d_wt sublist gt_d_wt 6 length gt_d_wt
            set gt_d_ag sublist gt_d_ag 6 length gt_d_ag
            set gt_fem_lact sublist gt_fem_lact 6 length gt_fem_lact

            set gt-tot sum (list gt_d gt_b)                                    ; Update all the livestock entries.
            set gt_tot_wt sum (map [x -> sum x] (list gt_d_wt gt_b_wt))

            set cat-tot sum (list ca_aF ca_aM)
            set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))
        ]

  ]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;Hholds tht have excess milk may take it to a market and sell it or give it to a family member in need. Similarly a hhold that is meeting its calorie needs and is not in debt can
; gift livestock to a family member in need

to gifting

  ask hholds[
   set temp_given 0
   set temp_recieved 0
   set temp_gift_given 0
   set temp_gift_recieved 0
   set milk_inc 0]

ask hholds with  [cal_milk > 1000][

    ifelse mark < 120    ;; Milk with hhold is measured in terms of left over calories. Market distance of 120 reflect the time taken in mins to get to a market
         [set cash_in_hand cash_in_hand + (cal_milk / milk_cal_cow) * 40 ;;If markets are close sell milk and make money
          set milk_inc (cal_milk / milk_cal_cow) * 40
          set cal_milk 0
          set milk_sold 1]

; else
    [let temp_milk cal_milk
         let temp one-of (hholds in-radius 0) with [food_sufficiency = "deficient"]
           if temp != nobody

           [ask temp [
             set cal_needs cal_needs - temp_milk
             set temp_recieved 1

             ifelse cal_needs > 0.1 * tot_calreq_month

              [set food_sufficiency  "deficient"
               set sufficiency-source sufficiency-source]
              [set food_sufficiency  "sufficient"
               set sufficiency-source word sufficiency-source "gift"
               set cal_needs 0]
           ]
          set temp_given 1
          set cal_milk 0
      ]
    ]
  ]

 ;; Update the milk given and received counters for all hosueholds
  ask hholds with [assets = "assetless"][

;; Gifting of livestock
  ; HHolds that do not have any livestock can receive gifts from wealthier family members
      let temp_gifter one-of link-neighbors with [ca_aF > 10 and gt_d > 20]   ; If holdings exceed 25TLU MAKE THIS IN TERMS OF TLU-cap > 5
      let an_gift_wt []
      let an_gift_ag []
      let ag_gifted 0
      let gift_lact []
      if temp_gifter != nobody [
      ask temp_gifter [
       ifelse random-float 1 < 0.5         ;; Gift cattle or goats with a 50% probability.

         [set ca_aF ca_aF - 2
          set an_gift_wt sublist ca_aF_wt 0 2
          set ca_aF_wt sublist ca_aF_wt 2 length ca_aF_wt
          set an_gift_ag sublist ca_aF_ag 0 2
          set gift_lact sublist fem_lact 0 2
          set fem_lact sublist fem_lact 2 length fem_lact
          set ca_aF_ag sublist ca_aF_ag 2 length ca_aF_ag
          set cat-tot sum (list ca_aF ca_aM)                             ; Update all the livestock entries.
          ;set cat matrix:from-column-list (list(list ca_aF  ca_aM))
          set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))
          set temp_gift_given "cattle"]
          ;set gift lput (word ticks "ca-given") gift]  ;; This is a way to note the iteration during which gifting occured

          [set gt_d gt_d - 2
          set an_gift_wt sublist gt_d_wt 0 2
          set gt_d_wt sublist gt_d_wt 2 length gt_d_wt
          set an_gift_ag sublist gt_d_ag 0 2
          set gt_d_ag sublist gt_d_ag 2 length gt_d_ag
          set gt_fem_lact sublist gt_fem_lact 2 length gt_fem_lact
          set gift_lact sublist gt_fem_lact 0 2
          set gt-tot sum (list gt_d gt_b)                             ; Update all the livestock entries.
          ;set gt matrix:from-column-list (list(list gt_d gt_b))
          set gt_tot_wt sum (map [x -> sum x] (list gt_d_wt gt_b_wt))
          set temp_gift_given "goat"]
          ;set gift lput (word ticks "gt-given") gift]
        ]



    if ([temp_gift_given] of temp_gifter = "goat")
        [set gt_d gt_d + 2
         set gt_d_ag sentence gt_d_ag an_gift_ag
         set gt_d_wt sentence gt_d_wt an_gift_wt
         set gt_fem_lact sentence gt_fem_lact gift_lact
          set temp_gift_recieved "goat"]
         ;set gift lput (word ticks "gt-received") gift]

     if ([temp_gift_given] of temp_gifter = "cattle")
        [set ca_aF ca_aF + 2
         set ca_aF_ag sentence ca_aF_ag an_gift_ag
         set ca_aF_wt sentence ca_aF_wt an_gift_wt
         set fem_lact sentence fem_lact gift_lact
         set temp_gift_recieved "cattle"]
         ;set gift lput (word ticks "ca-received") gift]
  ]

  ]

 ask hholds [
      set cat-tot sum (list ca_aF ca_aM)                             ; Update all the livestock entries.
      set ca_tot_wt sum (map [x -> sum x] (list ca_aF_wt ca_aM_wt))

      set gt-tot sum (list gt_d gt_b)                             ; Update all the livestock entries.
      set gt_tot_wt sum (map [x -> sum x] (list gt_b_wt gt_d_wt))


             set milk_given lput temp_given milk_given
             set milk_recieved lput temp_recieved milk_recieved
             set gift_given lput temp_gift_given gift_given
             set gift_recieved lput temp_gift_recieved gift_recieved
             set hh-cat-tot lput cat-tot hh-cat-tot
             set hh-cam-tot lput cam-tot hh-cam-tot

            ifelse (ticks > 0  and  item (ticks - 1) hh-cat-tot != 0)
           [set hh-cat-lam lput ((item ticks hh-cat-tot) / (item (ticks - 1) hh-cat-tot)) hh-cat-lam]
           [set hh-cat-lam lput 1 hh-cat-lam]

           ifelse (ticks > 0 and  item (ticks - 1) hh-cam-tot != 0)
           [set hh-cam-lam lput ((item ticks  hh-cam-tot) / (item (ticks - 1)  hh-cam-tot)) hh-cam-lam]
           [set hh-cam-lam lput 1 hh-cam-lam]
  ]
end


;;;; Wrap up the model by writing out the ASCII file of interest and deleting the npp file
to wrap-up
; let month ticks - (12 * floor (ticks / 12))
 ;   if member? ticks n-values years [x -> x * 12] [ set month 0]

  set month ticks + 1

  ask hholds [let temp-TLU cam-tot + cat-tot  + gt-tot * 0.1 + sh-tot * 0.1
              set TLU-owned lput temp-TLU TLU-owned   ; tracks changes in TLU each month for each hhold
              set TLU-cap lput (temp-TLU / AE) TLU-cap   ; Tracks TLY per adult equivalent each month
              set hunger-stat lput food_sufficiency hunger-stat  ; track hunger status
              set cal-source lput sufficiency-source cal-source ; track calorie surce
              set ca_s_tot sum sales_ca_m   ;; Track sales and purchases of livestock speciees each month
              set ca_p_tot sum purchases_ca_m
              set cam_s_tot sum sales_cam_m
              set cam_p_tot sum  purchases_cam_m
              set sht_s_tot sum sales_sht_m
              set sht_p_tot sum purchases_sht_m
              set cat_m lput cat-tot cat_m
              set cam_m lput cam-tot cam_m
              set gt_m lput gt-tot gt_m
              set sh_m lput sh-tot sh_m]

  ;; Update total number of cattle, camel, sheep and goat in Kenya

  set cattle-total lput (sum [cat-tot] of turtles) cattle-total     ; Across Kenya, total cattle, camel, sheep and goat
  set camel-total lput (sum [cam-tot] of turtles) camel-total
  set sheep-total lput (sum [sh-tot] of turtles) sheep-total
  set goat-total lput (sum [gt-tot] of turtles) goat-total

  ;ask hholds [set economic_state 0]
  ask hholds with [cat-tot + cam-tot + gt-tot + sh-tot = 0] [set assets "assetless"]  ;; Assetless hholds can stay on the system as is or can be given livestock at the start of next month
  set drop-outs lput (count hholds with [assets = "assetless"]) drop-outs
  ;set hungry lput (count hholds with [food_sufficiency = "deficient"]) hungry  ; Total hunger across Kenya each month
  set hungry (count hholds with [food_sufficiency = "deficient"]) / count hholds


  ;;Write out the temp_grazed file


if ticks < R  [
let p_sort sort patches
let pools ["GREEN_HERB" "DEAD_HERB"  "GREEN_SHRUB" "DEAD_SHRUB" "SHRUB_BRNCH" "GREEN_TREE" "DEAD_TREE" "TREE_BRNCH"]
let i 1
;let k 0

file-delete read-from-string bio_out
 file-open read-from-string grazed_out

foreach pools [b ->
    file-type " " file-type  b  file-type "           " file-print  month
  foreach p_sort [p ->
    ifelse (i != (count patches) / (max-pycor + 1) )
      [file-write [runresult b] of p file-type "      "
       set i i + 1]
      [file-write [runresult b] of p file-type "      "  file-print ""
       set i 1]

   ]
     file-print ""
    set i 1
    ;set k k + 1
  ]
  file-print "END_OF_FILE"
 file-close
  ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  let turk hholds with [my-tribe = "Turkana"]
  let kaj hholds with [my-tribe = "Kajiado"]
  let man hholds with [my-tribe = "Mandera"]
  let mar hholds with [my-tribe = "Marsabit"]
  let lai hholds with [my-tribe = "Laikipia"]
  let sam hholds with [my-tribe = "Samburu"]
  let wp  hholds with [my-tribe = "West Pokot"]
  let nar hholds with [my-tribe = "Narok"]
  let tr hholds with [my-tribe = "Tana River"]
  let waj hholds with [my-tribe = "Wajir"]
  let isi hholds with [my-tribe = "Isiolo"]
  let lam  hholds with [my-tribe = "Lamu"]
  let gar hholds with [my-tribe = "Garissa"]
  let bar hholds with [my-tribe = "Baringo"]

  set hungry_turk (count turk with [food_sufficiency = "deficient"])/ (count turk)
  set hungry_kaj (count kaj with [food_sufficiency = "deficient" ])/(count kaj)
  set hungry_man (count man with [food_sufficiency = "deficient"])/ (count man)
  set hungry_mar (count mar with [food_sufficiency = "deficient"])/ (count mar)
  set hungry_lai (count lai with [food_sufficiency = "deficient"])/ (count lai)
  set hungry_sam (count sam with [food_sufficiency = "deficient"])/ (count sam)
  set hungry_wp (count wp with [food_sufficiency = "deficient"])/ (count wp)
  set hungry_nar (count nar with [food_sufficiency = "deficient"])/ (count nar)
  set hungry_tr (count tr with [food_sufficiency = "deficient"])/ (count tr)
  set hungry_waj (count waj with [food_sufficiency = "deficient"])/ (count waj)
  set hungry_isi (count isi with [food_sufficiency = "deficient"])/ (count isi)
  set hungry_lam (count lam with [food_sufficiency = "deficient"])/ (count lam)
  set hungry_gar (count gar with [food_sufficiency = "deficient"])/ (count gar)
  set hungry_bar (count bar with [food_sufficiency = "deficient"])/ (count bar)

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;



to print-output

  ;; County specific estimates of hunger

  let turk hholds with [my-tribe = "Turkana"]
  let kaj hholds with [my-tribe = "Kajiado"]
  let man hholds with [my-tribe = "Mandera"]
  let mar hholds with [my-tribe = "Marsabit"]
  let lai hholds with [my-tribe = "Laikipia"]
  let sam hholds with [my-tribe = "Samburu"]
  let wp  hholds with [my-tribe = "West Pokot"]
  let nar hholds with [my-tribe = "Narok"]
  let tr hholds with [my-tribe = "Tana River"]
  let waj hholds with [my-tribe = "Wajir"]
  let isi hholds with [my-tribe = "Isiolo"]
  let lam  hholds with [my-tribe = "Lamu"]
  let gar hholds with [my-tribe = "Garissa"]
  let bar hholds with [my-tribe = "Baringo"]

  ;let hungry_turk (count turk with [food_sufficiency = "deficient"])/ (count turk)
  ;let hungry_kaj (count kaj with [food_sufficiency = "deficient" ])/(count kaj)
  ;let hungry_man (count man with [food_sufficiency = "deficient"])/ (count man)
  ;let hungry_mar (count mar with [food_sufficiency = "deficient"])/ (count mar)
  ;let hungry_lai (count lai with [food_sufficiency = "deficient"])/ (count lai)
  ;let hungry_sam (count sam with [food_sufficiency = "deficient"])/ (count sam)
  ;let hungry_wp (count wp with [food_sufficiency = "deficient"])/ (count wp)
  ;let hungry_nar (count nar with [food_sufficiency = "deficient"])/ (count nar)
  ;let hungry_tr (count tr with [food_sufficiency = "deficient"])/ (count tr)
  ;let hungry_waj (count waj with [food_sufficiency = "deficient"])/ (count waj)
  ;let hungry_isi (count isi with [food_sufficiency = "deficient"])/ (count isi)
  ;let hungry_lam (count lam with [food_sufficiency = "deficient"])/ (count lam)
  ;let hungry_gar (count gar with [food_sufficiency = "deficient"])/ (count gar)
  ;let hungry_bar (count bar with [food_sufficiency = "deficient"])/ (count bar)

  let hungry_turk_1 (count turk with [food_sufficiency = "deficient" and h_quant = 1])/ (count turk with [ h_quant = 1])
  let hungry_kaj_1 (count kaj with [food_sufficiency = "deficient"  and h_quant = 1])/(count kaj with [ h_quant = 1])
  let hungry_man_1 (count man with [food_sufficiency = "deficient" and h_quant = 1])/ (count man with [ h_quant = 1])
  let hungry_mar_1 (count mar with [food_sufficiency = "deficient" and h_quant = 1])/ (count mar with [ h_quant = 1])
  let hungry_lai_1 (count lai with [food_sufficiency = "deficient" and h_quant = 1])/ (count lai with [ h_quant = 1])
  let hungry_sam_1 (count sam with [food_sufficiency = "deficient" and h_quant = 1])/ (count sam with [ h_quant = 1])
  let hungry_wp_1  (count wp with [food_sufficiency = "deficient" and h_quant = 1])/ (count wp with [ h_quant = 1])
  let hungry_nar_1 (count nar with [food_sufficiency = "deficient" and h_quant = 1])/ (count nar with [ h_quant = 1])
  let hungry_tr_1  (count tr with [food_sufficiency = "deficient" and h_quant = 1])/ (count tr with [ h_quant = 1])
  let hungry_waj_1 (count waj with [food_sufficiency = "deficient" and h_quant = 1])/ (count waj with [ h_quant = 1])
  let hungry_isi_1 (count isi with [food_sufficiency = "deficient" and h_quant = 1])/ (count isi with [ h_quant = 1])
  let hungry_lam_1 (count lam with [food_sufficiency = "deficient" and h_quant = 1])/ (count lam with [ h_quant = 1])
  let hungry_gar_1 (count gar with [food_sufficiency = "deficient" and h_quant = 1])/ (count gar with [ h_quant = 1])
  let hungry_bar_1 (count bar with [food_sufficiency = "deficient" and h_quant = 1])/ (count bar with [ h_quant = 1])

    let hungry_turk_3 (count turk with [food_sufficiency = "deficient" and h_quant = 3])/ (count turk with [ h_quant = 3])
  let hungry_kaj_3 (count kaj with [food_sufficiency = "deficient"  and h_quant = 3])/(count kaj with [ h_quant = 3])
  let hungry_man_3 (count man with [food_sufficiency = "deficient" and h_quant = 3])/ (count man with [ h_quant = 3])
  let hungry_mar_3 (count mar with [food_sufficiency = "deficient" and h_quant = 3])/ (count mar with [ h_quant = 3])
  let hungry_lai_3 (count lai with [food_sufficiency = "deficient" and h_quant = 3])/ (count lai with [ h_quant = 3])
  let hungry_sam_3 (count sam with [food_sufficiency = "deficient" and h_quant = 3])/ (count sam with [ h_quant = 3])
  let hungry_wp_3  (count wp with [food_sufficiency = "deficient" and h_quant = 3])/ (count wp with [ h_quant = 3])
  let hungry_nar_3 (count nar with [food_sufficiency = "deficient" and h_quant = 3])/ (count nar with [ h_quant = 3])
  let hungry_tr_3  (count tr with [food_sufficiency = "deficient" and h_quant = 3])/ (count tr with [ h_quant = 3])
  let hungry_waj_3 (count waj with [food_sufficiency = "deficient" and h_quant = 3])/ (count waj with [ h_quant = 3])
  let hungry_isi_3 (count isi with [food_sufficiency = "deficient" and h_quant = 3])/ (count isi with [ h_quant = 3])
  let hungry_lam_3 (count lam with [food_sufficiency = "deficient" and h_quant = 3])/ (count lam with [ h_quant = 3])
  let hungry_gar_3 (count gar with [food_sufficiency = "deficient" and h_quant = 3])/ (count gar with [ h_quant = 3])
  let hungry_bar_3 (count bar with [food_sufficiency = "deficient" and h_quant = 3])/ (count bar with [ h_quant = 3])

  let hungry_turk_6 (count turk with [food_sufficiency = "deficient" and h_quant = 6])/ (count turk with [ h_quant = 6])
  let hungry_kaj_6 (count kaj with [food_sufficiency = "deficient"  and h_quant = 6])/(count kaj with [ h_quant = 6])
  let hungry_man_6 (count man with [food_sufficiency = "deficient" and h_quant = 6])/ (count man with [ h_quant = 6])
  let hungry_mar_6 (count mar with [food_sufficiency = "deficient" and h_quant = 6])/ (count mar with [ h_quant = 6])
  let hungry_lai_6 (count lai with [food_sufficiency = "deficient" and h_quant = 6])/ (count lai with [ h_quant = 6])
  let hungry_sam_6 (count sam with [food_sufficiency = "deficient" and h_quant = 6])/ (count sam with [ h_quant = 6])
  let hungry_wp_6  (count wp with [food_sufficiency = "deficient" and h_quant = 6])/ (count wp with [ h_quant = 6])
  let hungry_nar_6 (count nar with [food_sufficiency = "deficient" and h_quant = 6])/ (count nar with [ h_quant = 6])
  let hungry_tr_6  (count tr with [food_sufficiency = "deficient" and h_quant = 6])/ (count tr with [ h_quant = 6])
  let hungry_waj_6 (count waj with [food_sufficiency = "deficient" and h_quant = 6])/ (count waj with [ h_quant = 6])
  let hungry_isi_6 (count isi with [food_sufficiency = "deficient" and h_quant = 6])/ (count isi with [ h_quant = 6])
  let hungry_lam_6 (count lam with [food_sufficiency = "deficient" and h_quant = 6])/ (count lam with [ h_quant = 6])
  let hungry_gar_6 (count gar with [food_sufficiency = "deficient" and h_quant = 6])/ (count gar with [ h_quant = 6])
  let hungry_bar_6 (count bar with [food_sufficiency = "deficient" and h_quant = 6])/ (count bar with [ h_quant = 6])

  let hungry_turk_ag (count turk with [food_sufficiency = "deficient" and agrop = 1])/ (count turk with [ agrop = 1])
  let hungry_kaj_ag (count kaj with [food_sufficiency = "deficient"  and agrop = 1])/(count kaj with [ agrop = 1])
  let hungry_man_ag (count man with [food_sufficiency = "deficient" and agrop = 1])/ (count man with [ agrop = 1])
  let hungry_mar_ag (count mar with [food_sufficiency = "deficient" and agrop = 1])/ (count mar with [ agrop = 1])
  let hungry_lai_ag (count lai with [food_sufficiency = "deficient" and agrop = 1])/ (count lai with [ agrop = 1])
  let hungry_sam_ag (count sam with [food_sufficiency = "deficient" and agrop = 1])/ (count sam with [ agrop = 1])
  let hungry_wp_ag  (count wp with [food_sufficiency = "deficient" and agrop = 1])/ (count wp with [ agrop = 1])
  let hungry_nar_ag (count nar with [food_sufficiency = "deficient" and agrop = 1])/ (count nar with [ agrop = 1])
  let hungry_tr_ag  (count tr with [food_sufficiency = "deficient" and agrop = 1])/ (count tr with [ agrop = 1])
  let hungry_waj_ag (count waj with [food_sufficiency = "deficient" and agrop = 1])/ (count waj with [ agrop = 1])
  let hungry_isi_ag (count isi with [food_sufficiency = "deficient" and agrop = 1])/ (count isi with [ agrop = 1])
  let hungry_lam_ag (count lam with [food_sufficiency = "deficient" and agrop = 1])/ (count lam with [ agrop = 1])
  let hungry_gar_ag (count gar with [food_sufficiency = "deficient" and agrop = 1])/ (count gar with [ agrop = 1])
  let hungry_bar_ag (count bar with [food_sufficiency = "deficient" and agrop = 1])/ (count bar with [ agrop = 1])

  let debt_turk (count turk with [item ticks economic_state = "debt"])/ (count turk)
  let debt_kaj (count kaj with [item ticks economic_state = "debt" ])/(count kaj)
  let debt_man (count man with [item ticks economic_state = "debt"])/ (count man)
  let debt_mar (count mar with [item ticks economic_state = "debt"])/ (count mar)
  let debt_lai (count lai with [item ticks economic_state = "debt"])/ (count lai)
  let debt_sam (count sam with [item ticks economic_state = "debt"])/ (count sam )
  let debt_wp  (count wp with [item ticks economic_state = "debt"])/ (count wp )
  let debt_nar (count nar with [item ticks economic_state = "debt"])/ (count nar)
  let debt_tr  (count tr with [item ticks economic_state = "debt"])/ (count tr)
  let debt_waj  (count waj with [item ticks economic_state = "debt"])/ (count waj)
  let debt_isi  (count isi with [item ticks economic_state = "debt"])/ (count isi)
  let debt_lam (count lam with [item ticks economic_state = "debt"])/ (count lam)
  let debt_gar  (count gar with [item ticks economic_state = "debt"])/ (count gar)
  let debt_bar  (count bar with [item ticks economic_state = "debt"])/ (count bar)

  let store_turk (count turk with [store_cal = 1])/ (count turk)
  let store_kaj (count kaj with [store_cal = 1 ])/(count kaj)
  let store_man (count man with [store_cal = 1])/ (count man)
  let store_mar (count mar with [store_cal = 1])/ (count mar)
  let store_lai (count lai with [store_cal = 1])/ (count lai)
  let store_sam (count sam with [store_cal = 1])/ (count sam)
  let store_wp (count wp with [store_cal = 1])/ (count wp)
  let store_nar (count nar with [store_cal = 1])/ (count nar)
  let store_tr (count tr with [store_cal = 1])/ (count tr)
  let store_waj (count waj with [store_cal = 1])/ (count waj)
  let store_isi (count isi with [store_cal = 1])/ (count isi)
  let store_lam (count lam with [store_cal = 1])/ (count lam)
  let store_gar (count gar with [store_cal = 1])/ (count gar)
  let store_bar (count bar with [store_cal = 1])/ (count bar)

  let catS_turk sum [sales_ca] of turk
  let catS_kaj  sum [sales_ca] of kaj
  let catS_man  sum [sales_ca] of man
  let catS_mar  sum [sales_ca] of mar
  let catS_lai  sum [sales_ca] of lai
  let catS_sam  sum [sales_ca] of sam
  let catS_wp   sum [sales_ca] of wp
  let catS_nar  sum [sales_ca] of nar
  let catS_tr   sum [sales_ca] of tr
  let catS_waj  sum [sales_ca] of waj
  let catS_isi  sum [sales_ca] of isi
  let catS_lam  sum [sales_ca] of lam
  let catS_gar  sum [sales_ca] of gar
  let catS_bar  sum [sales_ca] of bar

  let catP_turk sum [purchases_ca] of turk
  let catP_kaj  sum [purchases_ca] of kaj
  let catP_man  sum [purchases_ca] of man
  let catP_mar  sum [purchases_ca] of mar
  let catP_lai  sum [purchases_ca] of lai
  let catP_sam  sum [purchases_ca] of sam
  let catP_wp   sum [purchases_ca] of wp
  let catP_nar  sum [purchases_ca] of nar
  let catP_tr   sum [purchases_ca] of tr
  let catP_waj  sum [purchases_ca] of waj
  let catP_isi  sum [purchases_ca] of isi
  let catP_lam  sum [purchases_ca] of lam
  let catP_gar  sum [purchases_ca] of gar
  let catP_bar  sum [purchases_ca] of bar

  let camS_turk sum [sales_cam] of turk
  let camS_kaj  sum [sales_cam] of kaj
  let camS_man  sum [sales_cam] of man
  let camS_mar  sum [sales_cam] of mar
  let camS_lai  sum [sales_cam] of lai
  let camS_sam  sum [sales_cam] of sam
  let camS_wp   sum [sales_cam] of wp
  let camS_nar  sum [sales_cam] of nar
  let camS_tr   sum [sales_cam] of tr
  let camS_waj  sum [sales_cam] of waj
  let camS_isi  sum [sales_cam] of isi
  let camS_lam  sum [sales_cam] of lam
  let camS_gar  sum [sales_cam] of gar
  let camS_bar  sum [sales_cam] of bar

  let camP_turk sum [purchases_cam] of turk
  let camP_kaj  sum [purchases_cam] of kaj
  let camP_man  sum [purchases_cam] of man
  let camP_mar  sum [purchases_cam] of mar
  let camP_lai  sum [purchases_cam] of lai
  let camP_sam  sum [purchases_cam] of sam
  let camP_wp   sum [purchases_cam] of wp
  let camP_nar  sum [purchases_cam] of nar
  let camP_tr   sum [purchases_cam] of tr
  let camP_waj  sum [purchases_cam] of waj
  let camP_isi  sum [purchases_cam] of isi
  let camP_lam  sum [purchases_cam] of lam
  let camP_gar  sum [purchases_cam] of gar
  let camP_bar  sum [purchases_cam] of bar


  let shtS_turk sum [sales_sht] of turk
  let shtS_kaj  sum [sales_sht] of kaj
  let shtS_man  sum [sales_sht] of man
  let shtS_mar  sum [sales_sht] of mar
  let shtS_lai  sum [sales_sht] of lai
  let shtS_sam  sum [sales_sht] of sam
  let shtS_wp   sum [sales_sht] of wp
  let shtS_nar  sum [sales_sht] of nar
  let shtS_tr   sum [sales_sht] of tr
  let shtS_waj  sum [sales_sht] of waj
  let shtS_isi  sum [sales_sht] of isi
  let shtS_lam  sum [sales_sht] of lam
  let shtS_gar  sum [sales_sht] of gar
  let shtS_bar  sum [sales_sht] of bar

  let shtP_turk sum [purchases_sht] of turk
  let shtP_kaj  sum [purchases_sht] of kaj
  let shtP_man  sum [purchases_sht] of man
  let shtP_mar  sum [purchases_sht] of mar
  let shtP_lai  sum [purchases_sht] of lai
  let shtP_sam  sum [purchases_sht] of sam
  let shtP_wp   sum [purchases_sht] of wp
  let shtP_nar  sum [purchases_sht] of nar
  let shtP_tr   sum [purchases_sht] of tr
  let shtP_waj  sum [purchases_sht] of waj
  let shtP_isi  sum [purchases_sht] of isi
  let shtP_lam  sum [purchases_sht] of lam
  let shtP_gar  sum [purchases_sht] of gar
  let shtP_bar  sum [purchases_sht] of bar


  let gift_turk (count turk with [temp_recieved = 1])/ (count turk)
  let gift_kaj (count kaj with [temp_recieved = 1 ])/(count kaj)
  let gift_man (count man with [temp_recieved = 1])/ (count man)
  let gift_mar (count mar with [temp_recieved = 1])/ (count mar)
  let gift_lai (count lai with [temp_recieved = 1])/ (count lai)
  let gift_sam (count sam with [temp_recieved = 1])/ (count sam)
  let gift_wp (count wp with [temp_recieved = 1])/ (count wp)
  let gift_nar (count nar with [temp_recieved = 1])/ (count nar)
  let gift_tr (count tr with [temp_recieved = 1])/ (count tr)
  let gift_waj (count waj with [temp_recieved = 1])/ (count waj)
  let gift_isi (count isi with [temp_recieved = 1])/ (count isi)
  let gift_lam (count lam with [temp_recieved = 1])/ (count lam)
  let gift_gar (count gar with [temp_recieved = 1])/ (count gar)
  let gift_bar (count bar with [temp_recieved = 1])/ (count bar)

  let cat_turk (sum [cat-tot] of turk)
  let cat_kaj  (sum [cat-tot] of kaj)
  let cat_man  (sum [cat-tot] of man)
  let cat_mar  (sum [cat-tot] of mar)
  let cat_lai  (sum [cat-tot] of lai)
  let cat_sam  (sum [cat-tot] of sam)
  let cat_wp   (sum [cat-tot] of wp)
  let cat_nar  (sum [cat-tot] of nar)
  let cat_tr   (sum [cat-tot] of tr)
  let cat_waj  (sum [cat-tot] of waj)
  let cat_isi  (sum [cat-tot] of isi)
  let cat_lam  (sum [cat-tot] of lam)
  let cat_gar  (sum [cat-tot] of gar)
  let cat_bar  (sum [cat-tot] of bar)

  let cam_turk (sum [cam-tot] of turk)
  let cam_kaj  (sum [cam-tot] of kaj)
  let cam_man  (sum [cam-tot] of man)
  let cam_mar  (sum [cam-tot] of mar)
  let cam_lai  (sum [cam-tot] of lai)
  let cam_sam  (sum [cam-tot] of sam)
  let cam_wp   (sum [cam-tot] of wp)
  let cam_nar  (sum [cam-tot] of nar)
  let cam_tr   (sum [cam-tot] of tr)
  let cam_waj  (sum [cam-tot] of waj)
  let cam_isi  (sum [cam-tot] of isi)
  let cam_lam  (sum [cam-tot] of lam)
  let cam_gar  (sum [cam-tot] of gar)
  let cam_bar  (sum [cam-tot] of bar)

  let sh_turk (sum [sh-tot] of turk)
  let sh_kaj  (sum [sh-tot] of kaj)
  let sh_man  (sum [sh-tot] of man)
  let sh_mar  (sum [sh-tot] of mar)
  let sh_lai  (sum [sh-tot] of lai)
  let sh_sam  (sum [sh-tot] of sam)
  let sh_wp   (sum [sh-tot] of wp)
  let sh_nar  (sum [sh-tot] of nar)
  let sh_tr   (sum [sh-tot] of tr)
  let sh_waj  (sum [sh-tot] of waj)
  let sh_isi  (sum [sh-tot] of isi)
  let sh_lam  (sum [sh-tot] of lam)
  let sh_gar  (sum [sh-tot] of gar)
  let sh_bar  (sum [sh-tot] of bar)

  let gt_turk (sum [gt-tot] of turk)
  let gt_kaj  (sum [gt-tot] of kaj)
  let gt_man  (sum [gt-tot] of man)
  let gt_mar  (sum [gt-tot] of mar)
  let gt_lai  (sum [gt-tot] of lai)
  let gt_sam  (sum [gt-tot] of sam)
  let gt_wp   (sum [gt-tot] of wp)
  let gt_nar  (sum [gt-tot] of nar)
  let gt_tr   (sum [gt-tot] of tr)
  let gt_waj  (sum [gt-tot] of waj)
  let gt_isi  (sum [gt-tot] of isi)
  let gt_lam  (sum [gt-tot] of lam)
  let gt_gar  (sum [gt-tot] of gar)
  let gt_bar  (sum [gt-tot] of bar)


  let raid_turk   count turk with [raid-loss = 1]
  let raid_kaj count kaj with [raid-loss = 1]
  let raid_man  count man with [raid-loss = 1]
  let raid_mar count mar with [raid-loss = 1]
  let raid_lai  count lai with [raid-loss = 1]
  let raid_sam  count sam with [raid-loss = 1]
  let raid_wp  count wp with [raid-loss = 1]
  let raid_nar  count nar with [raid-loss = 1]
  let raid_tr  count tr with [raid-loss = 1]
  let raid_waj  count waj with [raid-loss = 1]
  let raid_isi  count isi with [raid-loss = 1]
  let raid_lam  count lam with [raid-loss = 1]
  let raid_gar  count gar with [raid-loss = 1]
  let raid_bar  count bar with [raid-loss = 1]

  let saleinc_turk (sum [sale_income] of turk)
  let saleinc_kaj  (sum [sale_income] of kaj)
  let saleinc_man  (sum [sale_income] of man)
  let saleinc_mar  (sum [sale_income] of mar)
  let saleinc_lai  (sum [sale_income] of lai)
  let saleinc_sam  (sum [sale_income] of sam)
  let saleinc_wp   (sum [sale_income] of wp)
  let saleinc_nar  (sum [sale_income] of nar)
  let saleinc_tr   (sum [sale_income] of tr)
  let saleinc_waj  (sum [sale_income] of waj)
  let saleinc_isi  (sum [sale_income] of isi)
  let saleinc_lam  (sum [sale_income] of lam)
  let saleinc_gar  (sum [sale_income] of gar)
  let saleinc_bar  (sum [sale_income] of bar)

  let move_turk (mean [item ticks move-cost] of turk )
  let move_kaj (mean [item ticks move-cost] of kaj )
  let move_man (mean [item ticks move-cost] of man )
  let move_mar (mean [item ticks move-cost] of mar )
  let move_lai (mean [item ticks move-cost] of lai )
  let move_sam (mean [item ticks move-cost] of sam )
  let move_wp (mean [item ticks move-cost] of wp )
  let move_nar (mean [item ticks move-cost] of nar )
  let move_tr (mean [item ticks move-cost] of tr )
  let move_waj (mean [item ticks move-cost] of waj )
  let move_isi (mean [item ticks move-cost] of isi )
  let move_lam (mean [item ticks move-cost] of lam )
  let move_gar (mean [item ticks move-cost] of gar )
  let move_bar (mean [item ticks move-cost] of bar )

  let milk_turk (sum [milk_inc] of turk)
  let milk_kaj (sum [milk_inc] of kaj)
  let milk_man (sum [milk_inc] of man)
  let milk_mar (sum [milk_inc] of mar)
  let milk_lai (sum [milk_inc] of lai)
  let milk_sam (sum [milk_inc] of sam)
  let milk_wp (sum [milk_inc] of wp)
  let milk_nar (sum [milk_inc] of nar)
  let milk_tr (sum [milk_inc] of tr)
  let milk_waj (sum [milk_inc] of waj)
  let milk_isi (sum [milk_inc] of isi)
  let milk_lam (sum [milk_inc] of lam)
  let milk_gar (sum [milk_inc] of gar)
  let milk_bar (sum [milk_inc] of bar)

  let hunger1 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE01"] / count hholds with [[zone] of hm_patch = "KE01"]
  let hunger3 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE03"] / count hholds with [[zone] of hm_patch = "KE03"]
  let hunger5 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE05"] / count hholds with [[zone] of hm_patch = "KE05"]
  let hunger7 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE07"] / count hholds with [[zone] of hm_patch = "KE07"]
  let hunger9 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE09"] / count hholds with [[zone] of hm_patch = "KE09"]
  let hunger10 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE10"] / count hholds with [[zone] of hm_patch = "KE10"]
  let hunger11 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE11"] / count hholds with [[zone] of hm_patch = "KE11"]
  let hunger15 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE15"] / count hholds with [[zone] of hm_patch = "KE15"]
 let hunger24 count hholds with [food_sufficiency = "deficient" and [zone] of hm_patch = "KE24"] / count hholds with [[zone] of hm_patch = "KE24"]

  let liv_cal_turk (mean [liv_cal] of turk)
  let liv_cal_kaj (mean [liv_cal] of kaj)
  let liv_cal_man (mean [liv_cal] of man)
  let liv_cal_mar (mean [liv_cal] of mar)
  let liv_cal_lai (mean [liv_cal] of lai)
  let liv_cal_sam (mean [liv_cal] of sam)
  let liv_cal_wp (mean [liv_cal] of wp)
  let liv_cal_nar (mean [liv_cal] of nar)
  let liv_cal_tr (mean [liv_cal] of tr)
  let liv_cal_waj (mean [liv_cal] of waj)
  let liv_cal_isi (mean [liv_cal] of isi)
  let liv_cal_lam (mean [liv_cal] of lam)
  let liv_cal_gar (mean [liv_cal] of gar)
  let liv_cal_bar (mean [liv_cal] of bar)

  let pro_turk count turk with [[protect] of grazing_land > 0]
  let pro_kaj count kaj with [[protect] of grazing_land > 0]
  let pro_man count man with [[protect] of grazing_land > 0]
  let pro_mar count mar with [[protect] of grazing_land > 0]
  let pro_lai count lai with [[protect] of grazing_land > 0]
  let pro_sam count sam with [[protect] of grazing_land > 0]
  let pro_wp count wp with [[protect] of grazing_land > 0]
  let pro_nar count nar with [[protect] of grazing_land > 0]
  let pro_tr count tr with [[protect] of grazing_land > 0]
  let pro_waj count waj with [[protect] of grazing_land > 0]
  let pro_isi count isi with [[protect] of grazing_land > 0]
  let pro_lam count lam with [[protect] of grazing_land > 0]
  let pro_gar count gar with [[protect] of grazing_land > 0]
  let pro_bar count bar with [[protect] of grazing_land > 0]

  let tlu_turk mean [item ticks TLU-cap] of turk
  let tlu_kaj mean [item ticks TLU-cap] of kaj
  let tlu_man mean [item ticks TLU-cap] of man
  let tlu_mar mean [item ticks TLU-cap] of mar
  let tlu_lai mean [item ticks TLU-cap] of lai
  let tlu_sam mean [item ticks TLU-cap] of sam
  let tlu_wp mean [item ticks TLU-cap] of wp
  let tlu_nar mean [item ticks TLU-cap] of nar
  let tlu_tr mean [item ticks TLU-cap] of tr
  let tlu_waj mean [item ticks TLU-cap] of waj
  let tlu_isi mean [item ticks TLU-cap] of isi
  let tlu_lam mean [item ticks TLU-cap] of lam
  let tlu_gar mean [item ticks TLU-cap] of gar
  let tlu_bar mean [item ticks TLU-cap] of bar


  let tlu1_turk mean [item ticks TLU-cap] of turk with [h_quant = 1]
  let tlu1_kaj mean [item ticks TLU-cap] of kaj with [h_quant = 1]
  let tlu1_man mean [item ticks TLU-cap] of man with [h_quant = 1]
  let tlu1_mar mean [item ticks TLU-cap] of mar with [h_quant = 1]
  let tlu1_lai mean [item ticks TLU-cap] of lai with [h_quant = 1]
  let tlu1_sam mean [item ticks TLU-cap] of sam with [h_quant = 1]
  let tlu1_wp mean [item ticks TLU-cap] of wp with [h_quant = 1]
  let tlu1_nar mean [item ticks TLU-cap] of nar with [h_quant = 1]
  let tlu1_tr mean [item ticks TLU-cap] of tr with [h_quant = 1]
  let tlu1_waj mean [item ticks TLU-cap] of waj with [h_quant = 1]
  let tlu1_isi mean [item ticks TLU-cap] of isi with [h_quant = 1]
  let tlu1_lam mean [item ticks TLU-cap] of lam with [h_quant = 1]
  let tlu1_gar mean [item ticks TLU-cap] of gar with [h_quant = 1]
  let tlu1_bar mean [item ticks TLU-cap] of bar with [h_quant = 1]


  let tlu3_turk mean [item ticks TLU-cap] of turk with [h_quant = 3]
  let tlu3_kaj mean [item ticks TLU-cap] of kaj with [h_quant = 3]
  let tlu3_man mean [item ticks TLU-cap] of man with [h_quant = 3]
  let tlu3_mar mean [item ticks TLU-cap] of mar with [h_quant = 3]
  let tlu3_lai mean [item ticks TLU-cap] of lai with [h_quant = 3]
  let tlu3_sam mean [item ticks TLU-cap] of sam with [h_quant = 3]
  let tlu3_wp mean [item ticks TLU-cap] of wp with [h_quant = 3]
  let tlu3_nar mean [item ticks TLU-cap] of nar with [h_quant = 3]
  let tlu3_tr mean [item ticks TLU-cap] of tr with [h_quant = 3]
  let tlu3_waj mean [item ticks TLU-cap] of waj with [h_quant = 3]
  let tlu3_isi mean [item ticks TLU-cap] of isi with [h_quant = 3]
  let tlu3_lam mean [item ticks TLU-cap] of lam with [h_quant = 3]
  let tlu3_gar mean [item ticks TLU-cap] of gar with [h_quant = 3]
  let tlu3_bar mean [item ticks TLU-cap] of bar with [h_quant = 3]

  let tlu6_turk mean [item ticks TLU-cap] of turk with [h_quant = 6]
  let tlu6_kaj mean [item ticks TLU-cap] of kaj with [h_quant = 6]
  let tlu6_man mean [item ticks TLU-cap] of man with [h_quant = 6]
  let tlu6_mar mean [item ticks TLU-cap] of mar with [h_quant = 6]
  let tlu6_lai mean [item ticks TLU-cap] of lai with [h_quant = 6]
  let tlu6_sam mean [item ticks TLU-cap] of sam with [h_quant = 6]
  let tlu6_wp mean [item ticks TLU-cap] of wp with [h_quant = 6]
  let tlu6_nar mean [item ticks TLU-cap] of nar with [h_quant = 6]
  let tlu6_tr mean [item ticks TLU-cap] of tr with [h_quant = 6]
  let tlu6_waj mean [item ticks TLU-cap] of waj with [h_quant = 6]
  let tlu6_isi mean [item ticks TLU-cap] of isi with [h_quant = 6]
  let tlu6_lam mean [item ticks TLU-cap] of lam with [h_quant = 6]
  let tlu6_gar mean [item ticks TLU-cap] of gar with [h_quant = 6]
  let tlu6_bar mean [item ticks TLU-cap] of bar with [h_quant = 6]

let path word read-from-string (f_path) scenario

;; Print info on hunger to file
file-open word path "/Hunger_zones.csv"
if ticks = 0 [file-print (word "KE01" "," "KE03" "," "KE05" "," "KE07" "," "KE09" "," "KE10" "," "KE11" "," "KE15" ","  "KE24")]
file-print (word hunger1 "," hunger3 "," hunger5 "," hunger7 "," hunger9 "," hunger10 "," hunger11 "," hunger15  "," hunger24)
file-close

;; Print info on hunger to file
file-open word path "/Hunger.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" ","  "Wajir" ","  "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word hungry_turk "," hungry_kaj "," hungry_lai "," hungry_mar "," hungry_man "," hungry_sam "," hungry_nar "," hungry_wp "," hungry_tr "," hungry_waj "," hungry_isi "," hungry_lam "," hungry_gar "," hungry_bar)
file-close

;; print fraction of poor households going hungry
file-open word path "/Hunger1.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word hungry_turk_1 "," hungry_kaj_1 "," hungry_lai_1 "," hungry_mar_1 "," hungry_man_1 ","  hungry_sam_1 "," hungry_nar_1 ","  hungry_wp_1 "," hungry_tr_1 ","  hungry_waj_1 "," hungry_isi_1 "," hungry_lam_1 "," hungry_gar_1 "," hungry_bar_1)
file-close

;; print fraction of middle income households going hungry
file-open word path "/Hunger3.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word hungry_turk_3 "," hungry_kaj_3 "," hungry_lai_3 "," hungry_mar_3 "," hungry_man_3 ","  hungry_sam_3 "," hungry_nar_3 ","  hungry_wp_3 "," hungry_tr_3 ","  hungry_waj_3 "," hungry_isi_3 "," hungry_lam_3 "," hungry_gar_3 "," hungry_bar_3)
file-close

;; print fraction of rich households going hungry
file-open word path "/Hunger6.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word hungry_turk_6 "," hungry_kaj_6 "," hungry_lai_6 "," hungry_mar_6 "," hungry_man_6 ","  hungry_sam_6 "," hungry_nar_6 ","  hungry_wp_6 "," hungry_tr_6 ","  hungry_waj_6 "," hungry_isi_6 "," hungry_lam_6 "," hungry_gar_6 "," hungry_bar_6)
file-close


;; print fraction of agropastoral households going hungry
file-open word path "/Hunger_ag.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word hungry_turk_ag "," hungry_kaj_ag "," hungry_lai_ag "," hungry_mar_ag "," hungry_man_ag ","  hungry_sam_ag "," hungry_nar_ag ","  hungry_wp_ag "," hungry_tr_ag ","  hungry_waj_ag "," hungry_isi_ag "," hungry_lam_ag "," hungry_gar_ag "," hungry_bar_ag)
file-close

;; fraction of households meeting more than 50 % cal req via maize.
file-open word path "/store_cal.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word store_turk "," store_kaj "," store_lai ","  store_mar "," store_man ","  store_sam "," store_nar "," store_wp "," store_tr "," store_waj "," store_isi "," store_lam "," store_gar "," store_bar)
file-close

;;proportion in debt in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word  path "/debt.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word debt_turk "," debt_kaj ","  debt_lai "," debt_mar ","debt_man ","   debt_sam "," debt_nar ","  debt_wp ","  debt_tr "," debt_waj "," debt_isi ","  debt_lam "," debt_gar "," debt_bar)
file-close

;;proportion cattle seller in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word path "/cat_sales.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word catS_turk "," catS_kaj "," catS_lai ","  catS_mar "," catS_man ","  catS_sam "," catS_nar "," catS_wp "," catS_tr ","  catS_waj ","  catS_isi "," catS_lam ","  catS_gar "," catS_bar)
file-close

;;proportion cattle buyers in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word path "/cattle_pur.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word catP_turk "," catP_kaj ","  catP_mar "," catP_man "," catP_lai "," catP_sam ","  catP_nar "," catP_wp "," catP_tr "," catP_waj ","  catP_isi "," catP_lam "," catP_gar "," catP_bar)
file-close

;;proportion camel sellers in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word path "/cam_sales.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word camS_turk "," camS_kaj "," camS_lai "," camS_mar ","  camS_man ","  camS_sam ","  camS_nar "," camS_wp "," camS_tr "," camS_waj ","   camS_isi "," camS_lam "," camS_gar "," camS_bar)
file-close

;;proportion camel buyers in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word path "/cam_pur.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word camP_turk "," camP_kaj "," camP_lai "," camP_mar ","camP_man ","   camP_sam ","   camP_nar "," camP_wp "," camP_tr "," camP_waj ","  camP_isi ","  camP_lam "," camP_gar "," camP_bar)
file-close

 ;;proportion shoat sellers in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word path "/sht_sales.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
  file-print (word shtS_turk "," shtS_kaj "," shtS_lai "," shtS_mar "," shtS_man ","   shtS_sam "," shtS_nar "," shtS_wp "," shtS_tr ","  shtS_waj "," shtS_isi "," shtS_lam ","  shtS_gar "," shtS_bar)
file-close

;;proportion shoat buyers in Turkana, Kajiado, Laikipia, Marsabit and Mandera, WP and Narok counties
file-open word path "/sht_pur.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word shtP_turk "," shtP_kaj "," shtP_lai "," shtP_mar "," shtP_man ","   shtP_sam "," shtP_nar "," shtP_wp "," shtP_tr "," shtP_waj ","  shtP_isi ","  shtP_lam "," shtP_gar "," shtP_bar)
file-close

;;proportion households meeting cal req via gifting
file-open word path "/gift_r.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word gift_turk "," gift_kaj "," gift_lai "," gift_mar "," gift_man ","   gift_sam "," gift_nar "," gift_wp ","   gift_tr "," gift_waj "," gift_isi "," gift_lam ","  gift_gar "," gift_bar)
file-close

 ; cattle population in counties
file-open word path "/cattle.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word cat_turk "," cat_kaj "," cat_lai "," cat_mar "," cat_man ","  cat_sam ","  cat_nar ","  cat_wp "," cat_tr "," cat_waj ","  cat_isi "," cat_lam "," cat_gar "," cat_bar)
file-close

; goat population in counties
file-open word path "/goat.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word gt_turk "," gt_kaj ","  gt_lai "," gt_mar "," gt_man "," gt_sam "," gt_nar "," gt_wp ","   gt_tr "," gt_waj ","  gt_isi "," gt_lam ","  gt_gar "," gt_bar)
file-close

; sheep population in counties
file-open word path "/sheep.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word sh_turk "," sh_kaj "," sh_lai "," sh_mar "," sh_man ","  sh_sam "," sh_nar "," sh_wp "," sh_tr ","  sh_waj ","  sh_isi "," sh_lam "," sh_gar "," sh_bar)
file-close

; camel population in counties
file-open word path "/camel.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print (word cam_turk "," cam_kaj "," cam_lai "," cam_mar "," cam_man ","  cam_sam "," cam_nar "," cam_wp ","  cam_tr "," cam_waj ","  cam_isi "," cam_lam ","  cam_gar "," cam_bar)
file-close


;; Print info on raids to file
file-open word path "/Raid.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word raid_turk "," raid_kaj "," raid_lai "," raid_mar "," raid_man ","  raid_sam "," raid_nar "," raid_wp "," raid_tr ","  raid_waj ","  raid_isi "," raid_lam "," raid_gar "," raid_bar)
file-close

;; Print info on income for livestokc sales to file
file-open word path "/Sale_inc.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word saleinc_turk "," saleinc_kaj "," saleinc_lai "," saleinc_mar "," saleinc_man ","  saleinc_sam "," saleinc_nar "," saleinc_wp "," saleinc_tr ","  saleinc_waj ","  saleinc_isi "," saleinc_lam "," saleinc_gar "," saleinc_bar)
file-close

file-open word path "/Move.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word move_turk "," move_kaj "," move_lai "," move_mar "," move_man ","  move_sam "," move_nar "," move_wp "," move_tr ","  move_waj ","  move_isi "," move_lam "," move_gar "," move_bar)
file-close


file-open word path "/Milk_inc.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word milk_turk "," milk_kaj "," milk_lai "," milk_mar "," milk_man ","  milk_sam "," milk_nar "," milk_wp "," milk_tr ","  milk_waj ","  milk_isi "," milk_lam "," milk_gar "," milk_bar)
file-close


file-open word path "/liv_cal.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word liv_cal_turk "," liv_cal_kaj "," liv_cal_lai "," liv_cal_mar "," liv_cal_man ","  liv_cal_sam "," liv_cal_nar "," liv_cal_wp "," liv_cal_tr ","  liv_cal_waj ","  liv_cal_isi "," liv_cal_lam "," liv_cal_gar "," liv_cal_bar)
file-close

file-open word path "/pa_use.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word pro_turk "," pro_kaj "," pro_lai "," pro_mar "," pro_man ","  pro_sam "," pro_nar "," pro_wp "," pro_tr ","  pro_waj ","  pro_isi "," pro_lam "," pro_gar "," pro_bar)
file-close

file-open word path "/tlu-cap.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word tlu_turk "," tlu_kaj "," tlu_lai "," tlu_mar "," tlu_man ","  tlu_sam "," tlu_nar "," tlu_wp "," tlu_tr ","  tlu_waj ","  tlu_isi "," tlu_lam "," tlu_gar "," tlu_bar)
file-close

file-open word path "/tlu1-cap.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word tlu1_turk "," tlu1_kaj "," tlu1_lai "," tlu1_mar "," tlu1_man ","  tlu1_sam "," tlu1_nar "," tlu1_wp "," tlu1_tr ","  tlu1_waj ","  tlu1_isi "," tlu1_lam "," tlu1_gar "," tlu1_bar)
file-close

file-open word path "/tlu3-cap.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word tlu3_turk "," tlu3_kaj "," tlu3_lai "," tlu3_mar "," tlu3_man ","  tlu3_sam "," tlu3_nar "," tlu3_wp "," tlu3_tr ","  tlu3_waj ","  tlu3_isi "," tlu3_lam "," tlu3_gar "," tlu3_bar)
file-close

file-open word path "/tlu6-cap.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word tlu6_turk "," tlu6_kaj "," tlu6_lai "," tlu6_mar "," tlu6_man ","  tlu6_sam "," tlu6_nar "," tlu6_wp "," tlu6_tr ","  tlu6_waj ","  tlu6_isi "," tlu6_lam "," tlu6_gar "," tlu6_bar)
file-close


file-open word path "/pa_use.csv"
if ticks = 0 [file-print (word "Turkana" "," "Kajiado" "," "Laikipia" "," "Marsabit" "," "Mandera" "," "Samburu" "," "Narok" "," "West Pokot" "," "Tana River" "," "Wajir" "," "Isiolo" "," "Lamu" "," "Garissa" "," "Baringo")]
file-print  (word pro_turk "," pro_kaj "," pro_lai "," pro_mar "," pro_man ","  pro_sam "," pro_nar "," pro_wp "," pro_tr ","  pro_waj ","  pro_isi "," pro_lam "," pro_gar "," pro_bar)
file-close
end


to export-start
let path word read-from-string (f_path) scenario
  let tribes (list "Turkana"  "Kajiado" "Laikipia"  "Marsabit"  "Mandera"  "Samburu"  "Narok"  "West Pokot" "Tana River" "Wajir" "Isiolo"  "Lamu"  "Garissa" "Baringo")
   let tlucaps ["Mean TLU-cap"]
   let tothouses ["Total households"]
   let meanind ["Mean households size"]
   let tot-cat ["Total cattle"]
   let tot-camel ["Total camel"]
   let tot-sh ["Total sheep"]
   let tot-gt ["Total goats"]
   let sed-fr ["Proportion Sedentary"]
   let split ["Proportion herd splitting"]
   let area ["Area"]

  foreach tribes [x ->
    set tlucaps lput mean [item 0 TLU-cap] of hholds with [my-tribe = x] tlucaps
    set tothouses lput count hholds with [my-tribe = x] tothouses
    set meanind lput mean [hh_tot] of hholds with [my-tribe = x] meanind
    set tot-cat lput sum [cat-tot] of hholds with [my-tribe = x] tot-cat
    set tot-camel lput sum [cam-tot] of hholds with [my-tribe = x] tot-camel
    set tot-sh lput sum [sh-tot] of hholds with [my-tribe = x] tot-sh
    set tot-gt lput sum [gt-tot] of hholds with [my-tribe = x] tot-gt
    set sed-fr lput ((count hholds with [my-tribe = x and nonsed = 0]) / (count hholds with [my-tribe = x])) sed-fr
    set split lput ((count hholds with [my-tribe = x and past_type = "splitter"]) / (count hholds with [my-tribe = x])) split
    set area lput (count patches with [tribe = x]) area
  ]


;file-open
  csv:to-file word path "/County_attributes.csv"  (list tribes tlucaps tothouses meanind sed-fr split tot-cat tot-camel tot-sh tot-gt area)

end


to export-end
  let path word read-from-string (f_path) scenario
  csv:to-file word path "/raid-tribe.csv" ([(list my-tribe raid-tribe)] of hholds)
  csv:to-file word path "/raid-loss.csv" ([(list my-tribe raid-loss)] of hholds)
  csv:to-file word path "/move-cost.csv" ([(list my-tribe move-cost)] of hholds)

end
@#$#@#$#@
GRAPHICS-WINDOW
210
10
798
555
-1
-1
4.0
1
10
1
1
1
0
0
0
1
0
144
0
133
0
0
1
ticks
30.0

BUTTON
8
65
74
98
NIL
setup
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1

BUTTON
9
109
72
142
NIL
go
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1

CHOOSER
6
11
144
56
llhood
llhood
"farmer" "pastoralist" "all"
1

MONITOR
814
12
941
57
Mean household size
(sum reduce sentence [hh_mem] of turtles ) / count turtles
1
1
11

PLOT
1697
221
2055
441
Livestock Turkana
Iteration
Total animals
0.0
180.0
0.0
10.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot sum [cat-tot] of hholds with [my-tribe = \"Turkana\"]"
"pen-1" 1.0 0 -7500403 true "" "plot sum [cam-tot] of hholds with [my-tribe = \"Turkana\"]"
"pen-2" 1.0 0 -2674135 true "" "plot sum [sh-tot] of hholds with [my-tribe = \"Turkana\"]"
"pen-3" 1.0 0 -15575016 true "" "plot sum [gt-tot] of hholds with [my-tribe = \"Turkana\"]"

MONITOR
814
70
917
115
% Herd Splitting
count turtles with [past_type =\"splitter\"]  * 100 / \n  count turtles
3
1
11

MONITOR
814
125
891
170
% Non-Sed
count hholds with [move-stat = \"non-sedentary\"] * 100 /\ncount hholds
3
1
11

PLOT
1323
203
1658
367
Mean Biomass Availability - Turkana
ticks
mean biomass
0.0
180.0
0.0
1000.0
true
true
"" ""
PENS
"GShrub" 1.0 0 -2674135 true "" "plot mean (reduce sentence [greenS] of patches with [kenya = 1 and tribe = \"Turkana\"])"
"DShrub" 1.0 0 -955883 true "" "plot mean (reduce sentence [deadS] of patches with [kenya = 1 and tribe = \"Turkana\"])"
"GTree" 1.0 0 -6459832 true "" "plot mean (reduce sentence [greenT] of patches with [kenya = 1 and tribe = \"Turkana\"])"
"DTree" 1.0 0 -1184463 true "" "plot mean  (reduce sentence [deadT] of patches with [kenya = 1 and tribe = \"Turkana\"])"
"pen-4" 1.0 0 -7500403 true "" "plot mean (reduce sentence [greenH] of patches with [kenya = 1])"
"pen-5" 1.0 0 -10899396 true "" "plot mean (reduce sentence [deadH] of patches with [kenya = 1])"

INPUTBOX
7
334
86
394
orbit_normal
100.0
1
0
Number

BUTTON
2
486
68
519
profile
print profiler:report
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1

PLOT
1926
468
2346
705
Turkana-food insecurity
Months
Proportion of households that are food deficient
0.0
180.0
0.0
1.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot (count turtles with [ food_sufficiency = \"deficient\" and my-tribe = \"Turkana\"]) / (count turtles with [ my-tribe = \"Turkana\"])"

BUTTON
75
486
175
519
NIL
export-start
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1

PLOT
1466
468
1913
704
kajiado food insecurity
Iteration
Proportion hungry hholds
0.0
180.0
0.0
1.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot (count turtles with [ food_sufficiency = \"deficient\" and my-tribe = \"Kajiado\"]) / (count turtles with [my-tribe = \"Kajiado\"])"

INPUTBOX
124
275
199
335
years
20.0
1
0
Number

INPUTBOX
139
413
197
473
sam_p
5.0
1
0
Number

INPUTBOX
0
577
243
637
bio_out
\"C:/SOGES/L_range/L_range/Output/temp_biomass.out\"
1
0
String

INPUTBOX
0
647
244
707
grazed_out
\"C:/SOGES/L_range/L_range/Output/temp_grazed.out\"
1
0
String

PLOT
1321
10
1650
179
Mean biomass Kajiado
Months
Biomass
0.0
180.0
0.0
500.0
true
false
"" ""
PENS
"GreenS" 1.0 0 -2674135 true "" "plot mean (reduce sentence [greenS] of patches with [kenya = 1 and tribe = \"Kajiado\"])"
"pen-1" 1.0 0 -955883 true "" "plot mean (reduce sentence [deadS] of patches with [kenya = 1 and tribe = \"Kajiado\"])"
"pen-2" 1.0 0 -8431303 true "" "plot mean (reduce sentence [greenT] of patches with [kenya = 1 and tribe = \"Kajiado\"])"
"pen-3" 1.0 0 -1184463 true "" "plot mean (reduce sentence [deadT] of patches with [kenya = 1 and tribe = \"Kajiado\"])"
"pen-4" 1.0 0 -7500403 true "" "plot mean (reduce sentence [greenH] of patches with [kenya = 1 and tribe = \"Kajiado\"])"
"pen-5" 1.0 0 -14439633 true "" "plot mean (reduce sentence [deadH] of patches with [kenya = 1 and tribe = \"Kajiado\"])"

PLOT
1695
10
2052
210
Livestock-Kajiado
Months
Livestock pop
0.0
180.0
0.0
100.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot sum [cat-tot] of turtles with [my-tribe  = \"Kajiado\"]"
"pen-1" 1.0 0 -7500403 true "" "plot sum [cam-tot] of turtles with [my-tribe  = \"Kajiado\"]"
"pen-2" 1.0 0 -2674135 true "" "plot sum [sh-tot] of turtles with [my-tribe  = \"Kajiado\"]"
"pen-3" 1.0 0 -14439633 true "" "plot sum [gt-tot] of turtles with [my-tribe  = \"Kajiado\"]"

INPUTBOX
3
715
158
775
grazing
1.0
1
0
Number

INPUTBOX
124
344
200
404
unavailable
0.97
1
0
Number

BUTTON
91
65
166
98
NIL
set-spin
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1

PLOT
976
10
1289
182
plot 2
NIL
NIL
0.0
10.0
0.0
10.0
true
false
"" ""
PENS
"cattle" 1.0 0 -16777216 true "" "plot sum [cat-tot] of hholds"
"goat" 1.0 0 -7500403 true "" "plot sum [gt-tot] of hholds"
"sheep" 1.0 0 -2674135 true "" "plot sum [sh-tot] of hholds"
"camel" 1.0 0 -955883 true "" "plot sum [cam-tot] of hholds"

PLOT
815
196
1015
346
Protected area use
NIL
NIL
0.0
10.0
0.0
10.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot count hholds with [[protect] of grazing_land = 1]"

CHOOSER
322
569
460
614
PA_access
PA_access
"No access" "Access allowed"
1

INPUTBOX
16
406
96
466
Maize_price
40.0
1
0
Number

PLOT
814
486
1155
663
sale turnover
NIL
NIL
0.0
10.0
0.0
10.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot sum [ca_p_tot - ca_s_tot] of turtles"
"pen-1" 1.0 0 -7500403 true "" "plot sum [cam_p_tot - cam_s_tot] of turtles"
"pen-2" 1.0 0 -2674135 true "" "plot sum [sht_p_tot - sht_s_tot] of turtles"

CHOOSER
33
164
171
209
scenario
scenario
"pa" "nopa" "sed"
0

INPUTBOX
4
213
200
273
f_path
\"C:/SOGES/NETLOGO/SPIRALL/Test/\"
1
0
String

BUTTON
79
531
173
564
NIL
export-end
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1

PLOT
1040
239
1297
450
dr
NIL
NIL
0.0
10.0
0.0
10.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "plot cat-dr"
"pen-1" 1.0 0 -7500403 true "" "plot cam-dr"
"pen-2" 1.0 0 -2674135 true "" "plot gt-dr"
"pen-3" 1.0 0 -955883 true "" "plot sh-dr"

PLOT
1180
490
1380
640
move
NIL
NIL
0.0
10.0
0.0
10.0
true
false
"" ""
PENS
"default" 1.0 0 -16777216 true "" "histogram (reduce sentence [move-cost] of hholds)"

INPUTBOX
507
558
594
618
cat_energy
7.0
1
0
Number

INPUTBOX
612
559
694
619
cam_energy
5.0
1
0
Number

INPUTBOX
507
629
592
689
sh_energy
7.0
1
0
Number

INPUTBOX
612
631
694
691
gt_energy
8.0
1
0
Number

INPUTBOX
34
272
106
332
pop_fact
1.0
1
0
Number

@#$#@#$#@
## WHAT IS IT?

SPIRALL is a spatilly explict, region-scale model that simulates decisions by  households engaged in pastoral livelihoods in Kenya. Decisions are made in response to environmental conditions, particularly biomass availability, simulated by L-Range, an ecosystem model. It is thus the 'social" half of a coupled socio-ecological systems model. It produces estimates of monthly food insecurity across multiple arid and semi-arid counties in Kenya. 

## HOW IT WORKS
The model  starts by setting up (Setup) agents across the regeion of interest (Kenya). Agents (pastoralists and agropastoralists) are distibuted on patches that are 100 s.km each.  The agents are individual pastoral households. These households are endowed with attributes that are based on their livelihood type and their grographical location. The distribution of agents and the assignment of attributes is guided by freely available, remotely sensed and survey based datasets. Following setup, a monthly simualtion of household decisions is initited (Go). This includes decisions pertaining to herding of livestock by households, the trading of livestock and social interactions such as the giving and receiving of gifts. At the start of each simulation month, the ecosystem model L-Range supplies information on the spatial distribution of mutliple forage types. Following this, agents sense their environment and determine the availability of forage on patches that they are located on and that may be accessed based on movement rules. Two of these rules, concern the maximum distances over which pastoralists may move under normal and drought conditions. These may be altered by the use using the slidign scale made available on the itnerface to simualte conditions of rangeland fragmentation and constrained movements. The 'find pasture" procedure represents the complexity of these movement deicisions, that involve considerations of not only forage availability, but also ethnic group boundaries, type of pastoralism (sedentary / non-sedentary) and livestock composition. 

Once agents redistribute themselves on the landscape,livestock acquire forage and gain energy. The difference in energy expended (resulting from maintenenace needs, movement  to and within a patch) over the epriod of a month is tallied. Similary the energy acquired from forage consumption is tallied. The difference in energy acquired and expended then determines monthly weight gain (or loss) for each individual livestock. Livestock are modeled explicitly, i.e herds associted with each household are modeled as individuals with attrbutes (age, sex, wt, reproduction and lactation status) and not as aggregated species-age-sex groups. The simualted weights of individual livestock are compared to an idealized age-sex specific weight and a body condition score is determined, which impacts monthly survival probabiliity, reproduction and lactation. 

Subsequently, households tally calorie requirements based on household members, and calorie availability based on livestock production, maize stores and cash available in hand. Households also tally anticipated expenses and income over a three month period in the future and depending on cash available in hand, make livestock trading decisions. The trading decisions take into account both cash needs and livestock preferences and performance.  Finally, households interact with each through the gifting of milk and livestock. 

At the end of each month, households that have failed to meet 90 % of their calori requirements are designated as deficeint. The total number of deficient households are tallied. The population sizeof each livestock species is also tallied. Lastly, it writes a file that includes information on what fraction of available forage within each patch was consumed by livestock. This file is read in by L-Range, initiating the simualtions for the next month.


## HOW TO USE IT

Running the model involves the following steps

Years: The user sets up the number of years over which simulations occur 
Orbit_normal: Sets up the maximum distance pastoralists may travel from their home patch in search of pastures during nomal months
Orbit_drought: Sets up the maximum distance pastoralists may travel from their home patch in search of pastures during droughts.
Unavailable: The fraction of forage within each patch that is unavailable to liestock can be set to explore how contractions of rangeland due to changes in land tenure imapct pastoralists.

Setup: This sets up the the landscape, the patches, the agents and their attributes

Setup L-Range to read from and write into a folder that SPIRALL can access and initiate simulations in L-Range

Go: This starts the monthly simulation cycle in SPIRALL.

## THINGS TO NOTICE

(suggested things for the user to notice while running the model)

## THINGS TO TRY

(suggested things for the user to try to do (move sliders, switches, etc.) with the model)

## EXTENDING THE MODEL

(suggested things to add or change in the Code tab to make the model more complicated, detailed, accurate, etc.)

## NETLOGO FEATURES

(interesting or unusual features of NetLogo that the model uses, particularly in the Code tab; or where workarounds were needed for missing features)

## RELATED MODELS

(models in the NetLogo Models Library and elsewhere which are of related interest)

## CREDITS AND REFERENCES

(a reference to the model's URL on the web if it has one, as well as any other necessary credits, citations, and links)
@#$#@#$#@
default
true
0
Polygon -7500403 true true 150 5 40 250 150 205 260 250

airplane
true
0
Polygon -7500403 true true 150 0 135 15 120 60 120 105 15 165 15 195 120 180 135 240 105 270 120 285 150 270 180 285 210 270 165 240 180 180 285 195 285 165 180 105 180 60 165 15

arrow
true
0
Polygon -7500403 true true 150 0 0 150 105 150 105 293 195 293 195 150 300 150

box
false
0
Polygon -7500403 true true 150 285 285 225 285 75 150 135
Polygon -7500403 true true 150 135 15 75 150 15 285 75
Polygon -7500403 true true 15 75 15 225 150 285 150 135
Line -16777216 false 150 285 150 135
Line -16777216 false 150 135 15 75
Line -16777216 false 150 135 285 75

bug
true
0
Circle -7500403 true true 96 182 108
Circle -7500403 true true 110 127 80
Circle -7500403 true true 110 75 80
Line -7500403 true 150 100 80 30
Line -7500403 true 150 100 220 30

butterfly
true
0
Polygon -7500403 true true 150 165 209 199 225 225 225 255 195 270 165 255 150 240
Polygon -7500403 true true 150 165 89 198 75 225 75 255 105 270 135 255 150 240
Polygon -7500403 true true 139 148 100 105 55 90 25 90 10 105 10 135 25 180 40 195 85 194 139 163
Polygon -7500403 true true 162 150 200 105 245 90 275 90 290 105 290 135 275 180 260 195 215 195 162 165
Polygon -16777216 true false 150 255 135 225 120 150 135 120 150 105 165 120 180 150 165 225
Circle -16777216 true false 135 90 30
Line -16777216 false 150 105 195 60
Line -16777216 false 150 105 105 60

car
false
0
Polygon -7500403 true true 300 180 279 164 261 144 240 135 226 132 213 106 203 84 185 63 159 50 135 50 75 60 0 150 0 165 0 225 300 225 300 180
Circle -16777216 true false 180 180 90
Circle -16777216 true false 30 180 90
Polygon -16777216 true false 162 80 132 78 134 135 209 135 194 105 189 96 180 89
Circle -7500403 true true 47 195 58
Circle -7500403 true true 195 195 58

circle
false
0
Circle -7500403 true true 0 0 300

circle 2
false
0
Circle -7500403 true true 0 0 300
Circle -16777216 true false 30 30 240

cow
false
0
Polygon -7500403 true true 200 193 197 249 179 249 177 196 166 187 140 189 93 191 78 179 72 211 49 209 48 181 37 149 25 120 25 89 45 72 103 84 179 75 198 76 252 64 272 81 293 103 285 121 255 121 242 118 224 167
Polygon -7500403 true true 73 210 86 251 62 249 48 208
Polygon -7500403 true true 25 114 16 195 9 204 23 213 25 200 39 123

cylinder
false
0
Circle -7500403 true true 0 0 300

dot
false
0
Circle -7500403 true true 90 90 120

face happy
false
0
Circle -7500403 true true 8 8 285
Circle -16777216 true false 60 75 60
Circle -16777216 true false 180 75 60
Polygon -16777216 true false 150 255 90 239 62 213 47 191 67 179 90 203 109 218 150 225 192 218 210 203 227 181 251 194 236 217 212 240

face neutral
false
0
Circle -7500403 true true 8 7 285
Circle -16777216 true false 60 75 60
Circle -16777216 true false 180 75 60
Rectangle -16777216 true false 60 195 240 225

face sad
false
0
Circle -7500403 true true 8 8 285
Circle -16777216 true false 60 75 60
Circle -16777216 true false 180 75 60
Polygon -16777216 true false 150 168 90 184 62 210 47 232 67 244 90 220 109 205 150 198 192 205 210 220 227 242 251 229 236 206 212 183

fish
false
0
Polygon -1 true false 44 131 21 87 15 86 0 120 15 150 0 180 13 214 20 212 45 166
Polygon -1 true false 135 195 119 235 95 218 76 210 46 204 60 165
Polygon -1 true false 75 45 83 77 71 103 86 114 166 78 135 60
Polygon -7500403 true true 30 136 151 77 226 81 280 119 292 146 292 160 287 170 270 195 195 210 151 212 30 166
Circle -16777216 true false 215 106 30

flag
false
0
Rectangle -7500403 true true 60 15 75 300
Polygon -7500403 true true 90 150 270 90 90 30
Line -7500403 true 75 135 90 135
Line -7500403 true 75 45 90 45

flower
false
0
Polygon -10899396 true false 135 120 165 165 180 210 180 240 150 300 165 300 195 240 195 195 165 135
Circle -7500403 true true 85 132 38
Circle -7500403 true true 130 147 38
Circle -7500403 true true 192 85 38
Circle -7500403 true true 85 40 38
Circle -7500403 true true 177 40 38
Circle -7500403 true true 177 132 38
Circle -7500403 true true 70 85 38
Circle -7500403 true true 130 25 38
Circle -7500403 true true 96 51 108
Circle -16777216 true false 113 68 74
Polygon -10899396 true false 189 233 219 188 249 173 279 188 234 218
Polygon -10899396 true false 180 255 150 210 105 210 75 240 135 240

house
false
0
Rectangle -7500403 true true 45 120 255 285
Rectangle -16777216 true false 120 210 180 285
Polygon -7500403 true true 15 120 150 15 285 120
Line -16777216 false 30 120 270 120

leaf
false
0
Polygon -7500403 true true 150 210 135 195 120 210 60 210 30 195 60 180 60 165 15 135 30 120 15 105 40 104 45 90 60 90 90 105 105 120 120 120 105 60 120 60 135 30 150 15 165 30 180 60 195 60 180 120 195 120 210 105 240 90 255 90 263 104 285 105 270 120 285 135 240 165 240 180 270 195 240 210 180 210 165 195
Polygon -7500403 true true 135 195 135 240 120 255 105 255 105 285 135 285 165 240 165 195

line
true
0
Line -7500403 true 150 0 150 300

line half
true
0
Line -7500403 true 150 0 150 150

pentagon
false
0
Polygon -7500403 true true 150 15 15 120 60 285 240 285 285 120

person
false
0
Circle -7500403 true true 110 5 80
Polygon -7500403 true true 105 90 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285 180 195 195 90
Rectangle -7500403 true true 127 79 172 94
Polygon -7500403 true true 195 90 240 150 225 180 165 105
Polygon -7500403 true true 105 90 60 150 75 180 135 105

plant
false
0
Rectangle -7500403 true true 135 90 165 300
Polygon -7500403 true true 135 255 90 210 45 195 75 255 135 285
Polygon -7500403 true true 165 255 210 210 255 195 225 255 165 285
Polygon -7500403 true true 135 180 90 135 45 120 75 180 135 210
Polygon -7500403 true true 165 180 165 210 225 180 255 120 210 135
Polygon -7500403 true true 135 105 90 60 45 45 75 105 135 135
Polygon -7500403 true true 165 105 165 135 225 105 255 45 210 60
Polygon -7500403 true true 135 90 120 45 150 15 180 45 165 90

sheep
false
15
Circle -1 true true 203 65 88
Circle -1 true true 70 65 162
Circle -1 true true 150 105 120
Polygon -7500403 true false 218 120 240 165 255 165 278 120
Circle -7500403 true false 214 72 67
Rectangle -1 true true 164 223 179 298
Polygon -1 true true 45 285 30 285 30 240 15 195 45 210
Circle -1 true true 3 83 150
Rectangle -1 true true 65 221 80 296
Polygon -1 true true 195 285 210 285 210 240 240 210 195 210
Polygon -7500403 true false 276 85 285 105 302 99 294 83
Polygon -7500403 true false 219 85 210 105 193 99 201 83

square
false
0
Rectangle -7500403 true true 30 30 270 270

square 2
false
0
Rectangle -7500403 true true 30 30 270 270
Rectangle -16777216 true false 60 60 240 240

star
false
0
Polygon -7500403 true true 151 1 185 108 298 108 207 175 242 282 151 216 59 282 94 175 3 108 116 108

target
false
0
Circle -7500403 true true 0 0 300
Circle -16777216 true false 30 30 240
Circle -7500403 true true 60 60 180
Circle -16777216 true false 90 90 120
Circle -7500403 true true 120 120 60

tree
false
0
Circle -7500403 true true 118 3 94
Rectangle -6459832 true false 120 195 180 300
Circle -7500403 true true 65 21 108
Circle -7500403 true true 116 41 127
Circle -7500403 true true 45 90 120
Circle -7500403 true true 104 74 152

triangle
false
0
Polygon -7500403 true true 150 30 15 255 285 255

triangle 2
false
0
Polygon -7500403 true true 150 30 15 255 285 255
Polygon -16777216 true false 151 99 225 223 75 224

truck
false
0
Rectangle -7500403 true true 4 45 195 187
Polygon -7500403 true true 296 193 296 150 259 134 244 104 208 104 207 194
Rectangle -1 true false 195 60 195 105
Polygon -16777216 true false 238 112 252 141 219 141 218 112
Circle -16777216 true false 234 174 42
Rectangle -7500403 true true 181 185 214 194
Circle -16777216 true false 144 174 42
Circle -16777216 true false 24 174 42
Circle -7500403 false true 24 174 42
Circle -7500403 false true 144 174 42
Circle -7500403 false true 234 174 42

turtle
true
0
Polygon -10899396 true false 215 204 240 233 246 254 228 266 215 252 193 210
Polygon -10899396 true false 195 90 225 75 245 75 260 89 269 108 261 124 240 105 225 105 210 105
Polygon -10899396 true false 105 90 75 75 55 75 40 89 31 108 39 124 60 105 75 105 90 105
Polygon -10899396 true false 132 85 134 64 107 51 108 17 150 2 192 18 192 52 169 65 172 87
Polygon -10899396 true false 85 204 60 233 54 254 72 266 85 252 107 210
Polygon -7500403 true true 119 75 179 75 209 101 224 135 220 225 175 261 128 261 81 224 74 135 88 99

wheel
false
0
Circle -7500403 true true 3 3 294
Circle -16777216 true false 30 30 240
Line -7500403 true 150 285 150 15
Line -7500403 true 15 150 285 150
Circle -7500403 true true 120 120 60
Line -7500403 true 216 40 79 269
Line -7500403 true 40 84 269 221
Line -7500403 true 40 216 269 79
Line -7500403 true 84 40 221 269

wolf
false
0
Polygon -16777216 true false 253 133 245 131 245 133
Polygon -7500403 true true 2 194 13 197 30 191 38 193 38 205 20 226 20 257 27 265 38 266 40 260 31 253 31 230 60 206 68 198 75 209 66 228 65 243 82 261 84 268 100 267 103 261 77 239 79 231 100 207 98 196 119 201 143 202 160 195 166 210 172 213 173 238 167 251 160 248 154 265 169 264 178 247 186 240 198 260 200 271 217 271 219 262 207 258 195 230 192 198 210 184 227 164 242 144 259 145 284 151 277 141 293 140 299 134 297 127 273 119 270 105
Polygon -7500403 true true -1 195 14 180 36 166 40 153 53 140 82 131 134 133 159 126 188 115 227 108 236 102 238 98 268 86 269 92 281 87 269 103 269 113

x
false
0
Polygon -7500403 true true 270 75 225 30 30 225 75 270
Polygon -7500403 true true 30 75 75 30 270 225 225 270
@#$#@#$#@
NetLogo 6.1.1
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
<experiments>
  <experiment name="Stocking density cattle" repetitions="1" runMetricsEveryStep="true">
    <setup>setup</setup>
    <go>go</go>
    <metric>count turtles with [food_sufficiency = "deficient"]</metric>
    <enumeratedValueSet variable="llhood">
      <value value="&quot;pastoralist&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="years">
      <value value="39"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="orbit_normal">
      <value value="50"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="unavailable">
      <value value="0.6"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="max_cat">
      <value value="900"/>
      <value value="500"/>
      <value value="100"/>
      <value value="25"/>
    </enumeratedValueSet>
  </experiment>
  <experiment name="experiment" repetitions="1" runMetricsEveryStep="true">
    <setup>setup</setup>
    <go>go</go>
    <metric>count turtles</metric>
    <enumeratedValueSet variable="grazed_out">
      <value value="&quot;\&quot;C:/SOGES/L_range/L_range/Output/temp_grazed.out\&quot;&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="cam_energy">
      <value value="5"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="gt_energy">
      <value value="8"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="f_path">
      <value value="&quot;\&quot;C:/SOGES/NETLOGO/SPIRALL/Test/\&quot;&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="bio_out">
      <value value="&quot;\&quot;C:/SOGES/L_range/L_range/Output/temp_biomass.out\&quot;&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="grazing">
      <value value="1"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="years">
      <value value="20"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="unavailable">
      <value value="0.97"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="sh_energy">
      <value value="7"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="cat_energy">
      <value value="7"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="sam_p">
      <value value="5"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="llhood">
      <value value="&quot;pastoralist&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="Maize_price">
      <value value="40"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="PA_access">
      <value value="&quot;Access allowed&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="scenario">
      <value value="&quot;pa&quot;"/>
    </enumeratedValueSet>
    <enumeratedValueSet variable="orbit_normal">
      <value value="100"/>
    </enumeratedValueSet>
  </experiment>
</experiments>
@#$#@#$#@
@#$#@#$#@
default
0.0
-0.2 0 0.0 1.0
0.0 1 1.0 0.0
0.2 0 0.0 1.0
link direction
true
0
Line -7500403 true 150 150 90 180
Line -7500403 true 150 150 210 180
@#$#@#$#@
0
@#$#@#$#@
