saline-ecosystem

saline-ecosystem preview image

1 collaborator

Default-person Richard Taylor (Author)

Tags

(This model has yet to be categorized with any tags)
Visible to everyone | Changeable by everyone
Model was written in NetLogo 5.0.4 • Viewed 740 times • Downloaded 36 times • Run 0 times
Download the 'saline-ecosystem' modelDownload this modelEmbed this model

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)


Comments and Questions

Please start the discussion about this model! (You'll first need to log in.)

Click to Run Model

;; Bangladesh Saline Ecosystem Model
;; 3rd May 2012

breed [individuals individual]               ;; individual has a life-stage associated : Child; Young adult; Elder adult
                                             ;; subtype of person who is supposed to attend school sometimes also work informally
breed [households household]
breed [farms farm]

breed [villages village]                     ;; village at 0,0 landless or casual labourer may live here
breed [outsiders outsider]                    ;; shrimpfarmer from outside the village
breed [rivernodes rivernode]

breed [spinners spinner]                     ;; clock face which rivers the month. coloured blue during monsoon and grey during dry season
;;breed [rivers river]
breed [mangroves mangrove]

undirected-link-breed [salinitylinks salinitylink]

;; todo make directed - change salinity links to directed using a new breed for them
undirected-link-breed [riverlinks riverlink]
undirected-link-breed [kinships kinship]     ;; relationship that determines remittance flows as well as decision-making  
;; directed-link-breed [rentals rental]         ;; rental of a farm/ land
farms-own [                               
  size-xy area owner manager
  salinity health 
  harvest   
  labour-farm labour-guard             ;; these are set corresponding to the type of farm and size of farm
  farm-workforce                       ;; set of individuals employed, not including those from the occupier's household
  rotation landuse                     ;; rotation is one of paddy, shrimp, or paddy-cum-shrimp; landuse is current use
  labour-cost total-cost               ;; farm accounting variables
  farm-income farm-profit annual-profit
  rental-rate payment-deferred         ;; monthly payment amount, actuality of payment
  riveraccess                          ;; access to river and natural source of saline water and PL fish stock - through which farm?
]     
                                       ;; landuse not to be confused with calendar globals which vary every month
rivernodes-own [ID ]
households-own [
  hhtype head members  
  location zoom-location homeset       ;; location is in the village at 0,0. zoom-location the position when village is shown and homeset is the patchset 
  hh-workforce                         ;; workforce may or may not include children. total income from farm labour , migrant or mangrove work 
  income profit                        ;; variables for the current tick. assume that profit (or loss) accrues to savings of the hh head
  nutrition salinity                   ;; nutrition is a number between 0 and 4 signifying availability of different foods to household.
  food-cost annual-food-cost
  nutrition-method                     ;; market or subsistence
] 
villages-own [salinity health]         ;; health depends only on salinity: see health-homestead reporter
mangroves-own [                        
  salinity
  adult-count juvenile-count           ;; includes fishy variables here
  shoal-size                           ;; there is only one shoal
]
individuals-own [
  life-stage                ;; individual has a life-stage associated : Child; Young adult; Elder adult
  hh class assets savings
  preference                ;; if not employed in local farming, preference for "migrant" or "mangrove" work
  health income occupied    ;; TODO if health is poor, then occupation and income not possible
  land-use-decision         ;; decision can take one of several values : shrimp-farmer paddy-farmer paddy-cum-shrimp labourer
  location
  take                      ;; fish catch
  accessed-income           ;; income due to initial set up of power scenario
]

globals
[
  ;; the following are fixed, user-defined global variables chosen or input by the user
  number-people             ;; overall number of people, set before they are assigned into networks, occupations, households etc
  number-households         ;; hh vary in terms of structure and assets (may be landless)
  tries-paddys              ;; a maximum number. number-paddys is also constrained by min-distance
  initial-shrimpfarms       ;; number of initial shrimpfarms
  monsoon-saltrinse         ;; percentage by which salinity decreases at onset of monsoon
  monsoon-onset             ;; list containing month and period
  prop-diffused             ;; proportion of salt at a location that gets diffused to linked locations
  farmsize-min farmsize-max ;; minimum and maximum (acres)
  min-distance              ;; min distance between any two agents              
  max-distance              ;; maximum for there to be a connection
  riverbank-distance        ;; min distance from a farm node to river nodes - to improve display
  ticks-per-month           ;; allow for time-level below the month
  days-per-tick             ;; a variable that is calculated in setup that is used in setting labour requirements and allocating labour
  pareto-rule               ;; % of overall income earned by % of highest-earners
  village-law
  LZ-buffer?
         
  ;; parameters for setting up the household structures are described in setup procedure
  number-hhtype-CYE  number-hhtype-CY number-hhtype-CE
  number-hhtype-YE number-hhtype-Y number-hhtype-E
  more-elders               ;; value between 1 and 5
 
  ;; labour requirement (number of people per acre) for shrimpfarms, paddys
  labour-guards-perfarm  labour-shrimps-peracre  labour-paddys-peracre  ;;
  cost-shrimps-peracre cost-paddys-peracre   ;; owners' costs associated with each type of farming
  max-shrimp-harvest max-paddy-harvest       ;; max harvest (yield) in metric ton
  
  initial-rental-rate       ;; to simplify have an agreed rental amount that is paid per month. this is initally set for all agreements
  ;; income (wage payment) for casual labour (fixed)
  income-guards             ;; security
  income-shrimps            ;; maintenance
  income-paddys             ;; includes: transplantation, harvesting and weeding
  income-migrant            ;; outside (migrant) work
  ;;outside-paddys          ;; assuming that incomes are about the same whether local or migrant worker
  
  ;;income-fries              ;; incomes from collecting shrimp fries (unwaged ? or are people hired? variable income?)
  income-mangroves            ;; and from collecting forest products (variable?)
  
  max-daily-food-cost min-daily-food-cost            ;; used in nutrition rules
  hsh-condition             ;; health of homestead for which veg produciton is possible
  fishtick                  ;; the length of time the pond is in a good enough condition for cultivation of fish
  fish-maturity             ;; the minimum time condition for which it is possible to cultivate fish in ponds
  vegtick                   ;; time veg has been successfully cultivated
  veg-avail                 ;; true or false
  veg-maturity
  ;; non-fixed variables
  number-paddys             ;; count of number
  the-month                 ;; string variable in bengali
  month-id                  ;; integer from 0 to 11 incl.
  the-period                ;; integer - time level below month
  year-id                   ;; integer initial value of 0
  ;;climate                   ;; string variable can take value monsoon or dry
  price-shrimps             ;; price for sale of shrimp to exporter
  price-rice                ;; market price
  price-fish                ;; market price
  
  paddycalendar             ;; strings that denote the task of the current month. Either harvest or cultivate (or empty string).
  shrimpcalendar
  
  migrant-work              ;; a percentage set in the calendar procedure
  migrant-jobcount          ;; number of actual jobs based on the above and the total number of adults
                
  ;; agentsets
  headset                   ;; turtleset of all household heads, set in set-livelihoods
  workforce                 ;; all individuals not allocated to jobs yet
  all-locations             ;; farms, mangrove, village
  
  ;; other features of the terrain
  hyp                       ;; track length
  mangrove-forest           ;; patch set
  labelled-mangrove-patch   ;; patch selected for label
  ;; village law
  buffer-distance           ;; buffer zone around village where shrimp ponds are not allowed to be established
]

to plot-profit
  set-current-plot "farms' profitability"
  clear-plot 
  let sbp sort-on [annual-profit] farms
  foreach sbp [plot precision ([annual-profit] of ? / 100000) 1 ] 
end 

to go
  reset-tick
  ifelse (the-period = ticks-per-month)
  [set the-period 1 ]                   ;; new month has started
  [set the-period the-period + 1]
  
  set-month                              ;; set the month (string and id) 
 ;; output-print (word the-month " -" the-period)    ;; output goes to monitor on interface
  update-spinner                         ;; track the current month
  
  ;; set paddy and shrimpcalendar variables, and set the landuse
  if the-period = 1 [
    print (word "*** " the-month " ***")
    set-calendar
    ask farms [
      if rotation = "paddy" [ set landuse "paddy" ]
      if rotation = "shrimp" [ set landuse "shrimp" ]
      if rotation = "paddy-cum-shrimp" [ifelse paddycalendar != "" [set landuse "paddy"] [set landuse "shrimp"]]
    ]
  ]
  ;; TODO Set the demand for fries. Collecting fries will be done if there is strong demand from shrimpfarms
  ;; print (word "Shrimp acreage: " sum [area] of farms with [landuse = "shrimp"])

  ;; 1. climate
  ;; monsoon rule is that monsoon washes away a percentage of salt. Studies indicate that there is residual sailinity that is likely to increase over time. See Karim.
  if the-month = item 0 monsoon-onset and the-period = item 1 monsoon-onset
  [
    ask (all-locations) [
      ;;let n1 salinity / 2
      ;;let n2 salinity - monsoon-saltrinse
      ;;set salinity max list n1 n2 ;;up to half of salt, or amount equal to monsoon-saltrinse (eg. 0.2) whichever is lesser
      set salinity salinity * (1 - monsoon-saltrinse) ;; reduces by 40 percent
    ]
    print (word the-month ": monsoon saltrinse")
  ]
  
  ;; 2. labour
  if the-period = 1 [
     set-livelihoods  ;; eg. permanent livelihoods that don't need to change from tick to tick - licensed fin-fisher, crab fisher, guard
  ]
  ;; set labour requirement for the current period - a number of days (global values are days per month, so divide by ticks-per-month) 
  ;; number of people per ha multipied by area of shrimpfarms, paddys
  ;; define hh-workforce of each household. first allocate to own household
  ;; allocate work to overall workforce (ie those not occupied) which includes members of landless households
  ;; set preferences of the remaining workforce for migrant or mangrove work
  set-labour-local
  set-labour-migrant   ;; labour outside - eg building work and paddy work
  set-labour-mangrove 
  
  ;; 3. harvesting - takes place in period 1  of the particular month.  There are consecutive harvesting months for shrimp.
  ;; TODO deviants (shrimp farmers that are still producing)
  if the-period = 1 [
    if paddycalendar = "harvest"
    [
      ask farms with [landuse = "paddy"] [get-harvest-paddy]
    ] 
    if shrimpcalendar = "harvest"
    [
      ask farms with [landuse = "shrimp"] [get-harvest-shrimpfarm]
    ]    
    current-price-shrimps          ;; update the export price (in this case according to year), update the price of rice?
  ]
  
  ;; farm accounting is done every tick (owner or current tenant)
  ;; pay input costs for shrimp, pay labour costs, calculate profit using harvest information and farmgate price information
  ;; TODO IF first tick THEN pay-rental-costs if neccess.
  
  ;; calculate income of labourers, calculate profitability of farms
  ask farms [
    farm-accounting  
  ]
  ;; income from other types of work
  ;; TODO introduce factors affecting days of work obtained and income per day in mangroves and migrant work (eg. fishing)
  ask individuals with [occupied != []] [
    if item 1 occupied = "migrant"
    [ set income income-migrant * first occupied]      ;; migrant wage income multiplied by number of days worked
    if item 1 occupied = "mangroves"
    [ set income income-mangroves * first occupied] 
  ]
  
  ;; food source globals
  ;; harvesting of produce grown on homestead, benefits from livestock etc, as a food source is based on 'nutrition' variable
  ask one-of villages [ set health health-homestead
;    if climate-regime = "Monsoon" and the-period =  1 [
;      ifelse health > hsh-condition
;      [print (word "Village homesteads are in healthy condition to produce vegetables")]
;      [print (word "Village homesteads are NOT in condition to produce vegetables")]
;    ]
  ]
  
  ;; update the fishtick, the length of time the pond is in a good enough condition for cultivation of fish 
  ifelse [health] of one-of villages > hsh-condition 
  [set fishtick fishtick + 1]
  [set fishtick 0]
  ;; fish variable is set in the household accounting procedure
  ;; test if salinity has stayed low enough for at least the threshold ticks, ie sufficient time for fish to grow in pond 
  ifelse fishtick > fish-maturity
  [print (word "Village ponds stayed in healthy condition long enough to provide fish")]
  [print (word "Village ponds have NOT stayed in condition long enough to provide fish")]
  
  let veg-harvest (list "Ashwin" 1)          ;; when it is harvested the tick is set back to zero
  let veg-destock (list "Agrahayan" 3)       ;; end of potential availability period
  
  ;; similarly use a veg tick for time in good condition for fruit and veg cultivation
  ifelse the-month = item 0 monsoon-onset and the-period = item 1 monsoon-onset
  [ 
    set vegtick 1        ;; planting is done at monsoon onset 
  ]
  [ 
    if [health] of one-of villages > hsh-condition and vegtick > 0 [ set vegtick vegtick + 1 ]   ;; if in healthy condition, increase the tick counter
    if vegtick > veg-maturity [set veg-avail true]
    if the-month = item 0 veg-harvest and the-period = item 1 veg-harvest [set vegtick 0]        ;; final harvesting occurs and vegtick is reset to 0
  ]
  ;; provides veg until mid Agrahayan
  if the-month = item 0 veg-destock and the-period = item 1 veg-destock [set veg-avail false]
  ifelse veg-avail
  [print (word "Village homesteads stayed in healthy condition long enough to produce vegetables")]
  [print (word "Village homesteads did NOT stay in healthy condition long enough to produce vegetables")]
  
  ;; household calculation of income - expenses is done every tick
  ask households [
    household-accounting
    ;; security is another variable
  ]
 
  ;; 4. farm-owner decision-making about whether to lease land
  ;; Per hectare income from lease is about 6000 Taka per year (Karim figure) or 2500-3000 for 7 ha small-scale farmers (Swapan)
  ;; those with land have the opportunity to change their strategy
  ;; a) farm owner can carry on doing paddy and can start to also do shrimp hiself (paddy-cum-shrimp) - no need for lease   
  ;; b) farm owner can carry on doing paddy and lease to shrimpfarmer in winter (paddy-cum-shrimp) with lease
  ;; b is preferred where sf is perceived as risky
  ;; These strategies may work if there are not too many other shrimp ponds nearby and not too high salinity during rice growing.
  ;; If rice production does becomes uneconomic the next stage would be
  ;; c) farm owner can stop doing paddy and lease to shrimpfarmer (year round) 
  ;; This may work because owner will get a little more money and able to take other work as labourer in summer (eg. paddy work)

  if the-period = 1 and the-month =  "Kartik" [
    ;; plot from the code tab - just the profit distribution one
    ;; profit does not take into account own labour
    plot-profit 
    
    ;; the rental rate goes up each year. Check all of current farm rates and find the highest rate. Farms leased in this period will have a new rate a bit higher.
    ;; this is the monthly rate, which excludes the monsoon rains normally
    let rate max [rental-rate] of farms
    let rental-opportunities []                                 ;; add farms to this list when hh heads decide to lease them
    
    let sort-farms sort-on [annual-profit] farms
    foreach sort-farms [
      print (word "annual profit of farm-" [who] of ? " is: " precision ([annual-profit] of ? / 100000) 1 " Lakh") ;; one hundred thousand
      ;; set annual-profit 0      ;; reset variable done in reset-tick   
    ] 

    ;; those who own or manage land have the opportunity to change their strategy. 
    ;; TODO first check if the leasee decides to stop renting (exits) and if this happens reset owner= manager 
    
;    let owners headset with [assets != []] 
;    ask headset with [assets != []][
;      show (turtle-set assets) with [owner = manager]
;    ]
;    ;;let ownermanagers headset with [assets with [owner = manager] != []] 
;    ;;show owners
;    ;;ask headset to show assets (farms) that are owner managed
;    ask headset [
;      let omassets (turtle-set assets) with [owner = manager]
;      ifelse any? omassets 
;      [print (word "o/m assets: " omassets)]
;      [print "empty"]
;    ]

    ;; You only get nobody back in situations where you were expecting a single agent, not a whole agentset. 
    ask headset with [any? (turtle-set assets) with [owner = manager] ]   
    ;;ask headset with [assets != []] 
    [
      ;; decision may be taken to lease an unprofitable farm (however ignoring own labour supplied)
      ;; partly based on financial situation - could also be based on owners risk aversion, profitability of other farms, preferences for paddy
      let affordability true
      let profitability true
      let acceptability true
      let last-protest 12                      ;; TODO make an individual {breed} or global variable?
      
      print (word "Head of HH-" [who] of hh " has the following assets: " [assets] of self)   
      ;;let managed-assets assets
      let rnset (turtle-set assets) with [owner != manager]
      let omset (turtle-set assets) with [owner = manager]
      
      let sort-assets sort-on  [annual-profit] omset         ;; ie. exclude existing rentals
      
      foreach sort-assets [print (word "annual profit of " ? " is " [annual-profit] of ?)]
      let fa first sort-assets                 ;; select the least profitable
      
      ;; 1. if any farms are unprofitable change to mixed strategy immediately
      ;; a) if farmer has enough savings to afford conversion. is not too risk averse, profitability of other mixed farms is good
      ifelse [annual-profit] of first sort-assets < 0 [
        ;; ask fa [ set shape "mixed"]             ;; assuming that the least profitable are paddy, change to mixed
        ;; TODO check if zoning law applies
        ;;ask fa [set rotation "paddy-cum-shrimp"]
        ask fa [
          set rotation "shrimp"
          set shape "shrimp"
          set color red
        ]
        print (word "Change strategy with farm-" [who] of fa " to " [shape] of fa)
        
        ;; decide whether to self-manage
        let conv-cost 10000 * [area] of fa   ;; TODO estimate of conversion cost - a barrier to conversion
        ifelse any? farms with [rotation = "shrimp" or rotation = "paddy-cum-shrimp"]  [
          let nearest-neighbour min-one-of farms with [rotation = "shrimp" or rotation = "paddy-cum-shrimp"] [distance myself]
        
          ifelse [annual-profit] of nearest-neighbour / [area] of nearest-neighbour > rate * 12
          [ set profitability true] [set profitability false]  
        ]
        [
          set profitability true ;; in the absence of information from other farms, 
        ]
              
        ifelse savings > conv-cost [set affordability true] [set affordability false]
        
        ifelse last-protest < 10  [set acceptability false] [set acceptability true] ;; if there have been some protests in the last periods, it might have an impact
        let conditions (list affordability profitability acceptability)
        ifelse occurrences true conditions = 3 [
          print (word "keep same owner farm-" [who] of fa)         ;; keep same owner-manager
          set savings savings - conv-cost                           ;; make conversion payment
        ]
        [
          set rental-opportunities lput fa rental-opportunities ;; add to the rental list
        ]
      ]
      [
        ;; 2. (otherwise ..) if hh security is too low, change to mixed strategy. again, do strategy a)
        ;; overall annual negative profit of household or low savings compared to foodcost
        ;; higher foodcost indicates a more secure household. if savings drops below this value it may indicate changing circumstances
        ;; if [profit] of hh < 0 [
        
;        ;;if [profit] of hh < 0 or savings < [annual-food-cost] of hh  [
;        if savings < [annual-food-cost] of hh  [
;          if [profit] of hh < 0  [print (word "HH-" [who] of hh " annually in the negative")]
;          if savings < [annual-food-cost] of hh [print (word "HH-" [who] of hh " savings low")]
;          ;; do strategy a) - again applying to the least profitable
;          ask fa [ set shape "mixed"]                ;; assuming that the least profitable are paddy, change to mixed
;          ask fa [set rotation "paddy-cum-shrimp"]
;          print (word "Change strategy with farm-" [who] of fa " to " [shape] of fa)
;          ;; decide whether to self-manage
;          let conv-cost 10000 * [area] of fa     ;; TODO estimate of conversion cost - a barrier to conversion
;          ifelse any? farms with [rotation = "shrimp" or rotation = "paddy-cum-shrimp"]  [
;            let nearest-neighbour min-one-of farms with [rotation = "shrimp" or rotation = "paddy-cum-shrimp"] [distance myself]   
;            ;; assume knowledge of profit of nearest shrimpfarmer -neighbour
;            ifelse [annual-profit] of nearest-neighbour / [area] of nearest-neighbour > rate * 12   ;; this is not very plausible rule; other factors must be considered
;            [ set profitability true] [set profitability false]  
;          ]
;          [
;            set profitability true ;; in the absence of information from other farms, 
;          ]    
;          ifelse savings > conv-cost [set affordability true] [set affordability false]
;        
;          ifelse last-protest < 10  [set acceptability false] [set acceptability true] ;; if there have been some protests in the last periods, it might have an impact
;          let conditions (list affordability profitability acceptability)
;          ifelse occurrences true conditions = 3 [
;            print (word "keep same owner farm-" [who] of fa)          ;; keep same owner manager
;            set savings savings - conv-cost                           ;; make conversion payment
;          ]
;          [
;            set rental-opportunities lput fa rental-opportunities     ;; change manager - add to the rental list
;          ]
;        ]  
      ];; end of 2.
      
      ;; TODO a third possibility is transition from paddy-cum-shrimp to only shrimp   - a second stage of transformation?
    ] ; end of ask headset with assets 
    ;; TODO d) farm owner can lease to another paddy farmer (year round) - presumably labour shortage is the issue - maybe not so common
    ;; TODO e) farm is abandoned - worthless as paddy or as shrimpfarm
    print (word "Rental opportunities are : " rental-opportunities)
  
    ;; bidding can include any hh. can bid for a farm if can show significant savings
    ;; bids also come from investors outside of village
    ;; change the occupier of farms in the rental-opportunities list and set the new rental rate as a property of farms
    foreach rental-opportunities [
      let renters []
      let newrenter 0
      let conv-cost 10000 * [area] of ?   ;; TODO data needed for estimate of conversion cost - a barrier to conversion 
      ask headset [
        ;; there are those looking to rent land - become farm-manager - they have different criteria than the leaser
        let affordability true
        ifelse savings > conv-cost [set affordability true] [set affordability false]
        
        ;; TODO other preferences - may not all be keen on shrimpfarming
        ;;let profitability true
        ;;let acceptability true
        if affordability [set renters lput self renters]
        
      ]
      print (word "Potential new managers for farm-" [who] of ? " are: " renters)
      ifelse length renters > 0
      [
        set newrenter one-of renters
        ;; set a new rate a bit higher than the highest current farm rate
        ask ? [
          set rental-rate rate + random 20
          set manager newrenter   ;; payments on a monthly basis should be taken care of      
        ]
       
        ask newrenter [
          set savings savings - conv-cost
        ]
      ]
       ;; if no-one satisfies these criteria, outsider can get it 
      [set newrenter one-of outsiders]    ;; do not record costs to outsider
      print (word "new manager is: " newrenter)
    ] 
    ;; TODO the price may vary according to perceived profitablity of shrimp (status of access to saline water) driven up by strong demand 
    
    ;; ask households [show annual-food-cost]
  ] ;; end of 4 K-1
  
  
  ;; reset-tick is done at beginning and reset-annual is done near to end of procedure
  if the-period = 1 and the-month =  "Kartik" [reset-annual] 
    
  
 
  ;; TODO decision can be taken  in Jaistha to foregoe the paddy planting, if it is not likely profitable
  
  ;; then reset variables
  ;;if the-month = "Ashwin" and the-period = 1 [
  ;;  set-livelihoods the-month
  ;;]
  ;;if the-month = "Jaistha" and the-period = 1 [
   ;;  set-livelihoods the-month
  ;;]
 
 
  ;; 5. diffusion and resalinisation 
  ;; set salinity of all shrimpfarms to 1 by means of brackish or seawater being channeled in to ponds
  ;; this is possible if the access to channel is available - may need to be negotiated with other farmers
  ;; assume they resalinise once every permitted month at the beginning of the month
  if the-month != "Jaistha" and the-month != "Ashar" and the-month != "Sraban" and the-month != "Bhadra" and the-period = 1
  [
    ask farms with [landuse = "shrimp"] [set salinity 1]
    print (word the-month ": resalinisation of shrimpfarms")
  ] 
  ;; diffusion procedure. the argument defines what proportion of the salinity at this location is shared
  ;; this is the only command to happen in periods other than the initial period
  diffuse-link prop-diffused
  ;; correct for when salinity sometimes exceeds 1.0 in places - probably due to high clustering of shrimpfarms
  ask farms with [salinity > 1.0] [set salinity 1.0]
  check-view-state
  tick
end 

;; resetting of different variables at start of tick

to reset-tick
  ;; do every tick
  ask individuals [
    set occupied []
    set income 0
  ]
  ask farms [
    set farm-workforce no-turtles
    set harvest 0
  ]
end 


;; rules to reset variables annually - Kartik 1

to reset-annual
  ask farms [
    set annual-profit 0
  ]
  ask households [
    set annual-food-cost 0
  ]
end 

;; these two procedures are executed in an agent context
;; pay input costs for shrimp, pay-labour-costs and pay-rental-costs
;; calculate-income  ;; income minus labour and rental costs, calculate profitability that can be used in decision-making
;; stop harvesting rice if poor yield

to farm-accounting
  ;; TODO explore variation in shrimp input cost, consider that management can be extensive or semi-intensive
  let input-cost 0   ;; input cost is established at the start of farming
  
  let rental-cost 0
  let daily-wage 0
  let price 0
  if landuse = "shrimp" [
    ifelse the-period = 1 and shrimpcalendar = "start"
    [ set input-cost cost-shrimps-peracre]
    [ set input-cost 0]   ;; this is probably not paid out weekly but annually at harvest accounting
    set daily-wage income-shrimps
    set price price-shrimps
  ]
  if landuse = "paddy" [
    set input-cost 0
    set daily-wage income-paddys
    set price price-rice
  ]
  let actors []
  foreach sort farm-workforce [                 ;; total up the hours that labourers were employed
    set actors lput first [occupied] of ? actors
    ask ? [set income price * first occupied]   ;; set the income of the employee, price * time worked
  ]
  let total-hours sum actors  
  set labour-cost total-hours * daily-wage
  
  ;; calculate rental costs and make payment (via savings of individuals) if first period of month
  if (the-period = 1 and owner != manager and payment-deferred = false) [
    set rental-cost rental-rate * area
    ask owner [set savings savings + rental-cost]   ;; a rental payment is made
    ;;ask manager [set savings savings - rental-cost] ;; managers savings are updated later
  ]
  
  set total-cost labour-cost + input-cost + rental-cost
 
  ;; calculate income (and profit) using harvest information and farmgate price information
  ;; note this does not capture value of labour supplied by the manager's household
  set farm-income precision (harvest * price * 1000) 0                 ;; because price is measured in kg and harvest is measured in metric ton
  set farm-profit precision (farm-income - total-cost) 0
  ;; set label (word "Profit:" farm-profit) ;; now controlled by switch on interface
  ;; profitability can be used in decision-making    
  ;; let fp farm-profit
  ;; additional income goes into hh accounting??
  ;; income (or loss) accrues to savings of head of household - done in household accounting procedure
 
  ;; keep track of running annual profit
  ;; TODO check if manager runs out of money
  set annual-profit annual-profit + farm-profit
end 

;; calculate income and expenses, household nutrition rules, profit and savings
;; TO CHECK for all migrant workers food costs are included in the work

to household-accounting
  set income 0
  set food-cost 0
  ;; initialise food types
  let rice false           ;; important initial condition for rice
  let fish false
  let veg false
  let prot false
  let hd head              ;; create new variable hd because farms breed doesn't own head
  
  ;; calculate household income from labour
  let earning members with [occupied != []]
  let migrants earning with [item 1 occupied = "migrant"]
  set income sum [income] of turtle-set earning
  ;; Add other forms of income from accessed assets (pareto)
  set income income + [accessed-income] of head  
  ;; add rented out income
  let ts-rentedassets (turtle-set [assets] of head) with [owner != manager]  
  let rental-income sum [rental-rate * area] of ts-rentedassets
  if rental-income > 0 [
    print (word "rental income is " rental-income)
    set income income + rental-income
  ]
  ;; farm-accounting procedure calculates farm profit for both rented-in and owner-managed farms 
  let managed-income sum [farm-profit] of farms with [manager = hd] 
  set income income + managed-income
  
  ;; TODO dining not to include migrants
  ;;let test member? one-of members migrants
  ;;show test
  ;;let test2 turtle-set filter [[income] of ? != 0] (list members)
  ;;show test2
  ;;let dining turtle-set filter [member? ? migrants] (list members)
  let dining members
  ;; let dining members with [item 1 occupied != "migrant"]
  ;;show (word "Earning: " earning) 
  
  let max-expenses max-daily-food-cost * count dining * days-per-tick
  let min-expenses min-daily-food-cost * count dining * days-per-tick
  ;; check availablility of nutrition 4 types: veg, prot, rice, fish (assume the availability means availability for entire household)

  ;; FISH in the pond are available if salinity has stayed low enough for at least the threshold ticks, ie sufficient time for fish to grow in pond
  ;; same for all households   
  ifelse fishtick > fish-maturity
  [set fish true]
  [set fish false]
  ;; TODO availability of fish caught in nearby river depends on what is caught - Ricker model?
  ;; TODO also depends on what is caught in mangrove rivers
  ;; need for fishmeal for shrimp industry reduces the availablilty of small fish
  ;; TODO check if different during spawning season
  
  ;; RICE available to paddy manager year-round if farm is healthy and to paddy worker in harvesting period  
  if any? earning with [item 1 occupied = "paddy" or item 1 occupied = "paddy-cum-shrimp"] [set rice true]
  if any? (turtle-set [assets] of head) with [rotation = "paddy" or rotation = "paddy-cum-shrimp"] [set rice true]
  ;; RICE also available to paddy manager
  if any? farms with [manager = hd and (rotation = "paddy" or rotation = "paddy-cum-shrimp")] [set rice true]
 
  ;; VEG and fruit available from homesteads in post-monsoon if homestead health stayed above the threshold long enough to reach maturity 
  ifelse veg-avail
  ;; ifelse climate-regime = "Monsoon" and [health] of one-of villages > hsh-condition  ;; month-id 2,3 or 4
  [
    set veg true
  ]
  [ set veg false]
  
  ;; PROT: household can get some protein ie. eggs or milk from livestock, if they have somewhere to graze and fodder (i.e. own or manage paddy farm) 
  ifelse any? (turtle-set [assets] of head) with [rotation = "paddy" or rotation = "paddy-cum-shrimp"]
  [set prot true] 
  [set prot false]
  if any? farms with [manager = hd and (rotation = "paddy" or rotation = "paddy-cum-shrimp")] [set prot true]
  ;; TODO livestock can be removed from homestead if social pressure to do so is high enough or if there are shrimp lords (large land owners) nearby
  
  ;; calculate the subsistence nutrition
  let foods (list rice fish veg prot)
  set nutrition occurrences true foods
  ifelse max-expenses < income
  [
    ;; buy full food - in addition to available nutrition
    set food-cost max-expenses
    set nutrition 4
    set nutrition-method "market"
  ]
  [
    ;; buy minimum food, using savings if necessary, which can smooth the nutritional level seasonal fluctuation
    ;; ifelse min-expenses < income
    ifelse min-expenses < income or min-expenses < [savings] of head
    [
      ;; buy minimum food  in addition to available nutrition
      set food-cost min-expenses
      set nutrition-method "market"
      if nutrition < 3 [set nutrition 3]
    ]
    [
      ;; if income does not cover min-expenses they just buy food to satisfy nutritional deficit
      ;; for current tick the income may be less than the food-cost. In this case assume that savings of hh head are used
      ifelse nutrition = 0 [
        set food-cost 30 * count dining * days-per-tick   ;; buy two foods at a cost of 30 per person
        set nutrition 2
      ]
      [
        ifelse nutrition = 1 [
          set food-cost 10 * count dining * days-per-tick   ;; buy one foods at a cost of 10 per person
          set nutrition 2
        ] 
        [ ;; case nutrition = 3
          set food-cost 0
          set nutrition-method "subsistence"                  ;; do not need to buy any food
        ]
      ]
    ]
  ]
  ;; show (word "income of household-" who " is " income " and food expenses " food-cost " , nutrition is " nutrition)
  
  ;; if nutrition = 2 [print (word "savings of head: " [savings] of head)]
  
  ;; annual food cost gives a smoother indicator of how much is spent - the higher the better
  set annual-food-cost annual-food-cost + food-cost
  
  
  set profit income - food-cost
  let pr profit                           ;; create new variable pr because of ownership
  ;; additional income (or loss) accrues to savings of head of household
  ask head [set savings savings + pr]
end 

to set-labour-local
  ;; set labour requirement for the current period (global values are days per month, so divide by ticks-per-month)
  ;; number of people per ha multipied by area of shrimpfarms, paddys
  ;; CHECK whether the labour requirement is the same at different cropping stages
  ask farms with [landuse = "paddy"][
    ;; TODO add planting calendar period
    ifelse paddycalendar = "cultivate"
    [ set labour-farm floor (labour-paddys-peracre * item 0 size-xy * item 1 size-xy / ticks-per-month )]
    [  
      ifelse paddycalendar = "harvest" 
      [ set labour-farm floor (labour-paddys-peracre * item 0 size-xy * item 1 size-xy / ticks-per-month )]
      [ set labour-farm 0 ]   ;; no work in other period
    ]
  ]
  ask farms with [landuse = "shrimp"][
    ;; TODO add collecting/adding fry calendar period
    ifelse shrimpcalendar = "cultivate"
    [ set labour-farm floor (labour-shrimps-peracre * item 0 size-xy * item 1 size-xy / ticks-per-month)]
    [  
      ifelse shrimpcalendar = "harvest" 
      [ set labour-farm floor (labour-shrimps-peracre * item 0 size-xy * item 1 size-xy / ticks-per-month)]
      [ set labour-farm 0 ]   ;; no work in other period
    ]
    ;; A constant. CHECK guards peracre or guards per shrimpfarm?  
    ;; TODO this is usually a more permanent position
    set labour-guard 1        
  ]    

  ;; define hh-workforce of each household
  ask households
  [ 
    ifelse [savings] of head > 1000 
    [ set hh-workforce members with [life-stage != "Child"]]
    [ set hh-workforce members]
    ;; order the hh-workforce by life-stage string alphabetically. Need to reverse list to get: [young, elder, child]
    ;; it needs to be a list because the order matters
    set hh-workforce reverse sort-on [life-stage] hh-workforce 
  ]
  
  ;; allocation of labour available on local farms  
  ;; allocate to own household
  ask farms
  [
    ;; create list from agentset
    let wf  [hh-workforce] of [hh] of manager
    print (word "Farm-" who " (landuse is " landuse ") managed by Ind-" [who] of manager) 
    while [length wf > 0 and labour-farm > 0]
    [
      ;; 
      let time min list labour-farm days-per-tick
      set labour-farm labour-farm - time
      ask item 0 wf [
        set occupied (list time [landuse] of myself)
        print (word " Ind-" [who] of item 0 wf " from this household is occupied " time " days")
      ]
      set wf remove-item 0 wf 
      ;; if labour-farm > 0 [print (word "did not allocate " labour-farm)] 
    ]
    ask [hh] of manager [set hh-workforce wf]  ;; update the hh-workforce
    if labour-farm > 0 [print (word "  Work available is " labour-farm " days")] 
  ] 

  ;; allocate work to overall workforce (ie those not occupied) which includes members of landless households, follow similar pattern to above
  ;; TODO individuals from rich households could be discounted eg. by setting the occupied variable to "no"
  set workforce individuals with [occupied = []]
  ask farms with [labour-farm > 0] [
    print (word "Farm-" who " (landuse is " landuse ") managed by Ind-" [who] of manager " is hiring") 
    while [count workforce > 0 and labour-farm > 0]
    [
      let time min list labour-farm days-per-tick
      set labour-farm labour-farm - time
      let current one-of workforce
      ask current [
        set occupied (list time [landuse] of myself)
        print (word " Ind-" who " is hired for " time " days")
        set workforce other workforce
        
      ]   
      set farm-workforce (turtle-set farm-workforce current)   
    ]
  ]
  print (word "Total employed in farming is " count individuals with [occupied != []])

  ;; individuals seem to have good knowledge about the availability of migrant work, which varies over the year
  ;; may have local, limited, knowledge only about local employment opportunities
  ;; the logic is that the lower the local-fulfillment (farm-related), the more pressure on other local livelihoods (mangrove and fry collection)
  ;; in the case of low scores we assume that people would be more likely to consider migrant jobs 
  ;; TODO include other factors in the decision of casual labourers such as shrimp acreage and demand for fries
  ask workforce [
    let rset n-of 10 (individuals with [life-stage != "Child"])     ;; local knowledge based on contact with 10 random individuals 
    let local-fulfillment count rset with [occupied != []] / 10
    ifelse random-float 1 > local-fulfillment and random-float 1 < migrant-work    ;; use comparison with random numbers to set the preference
    [
      set preference "migrant"
    ] 
    [
      set preference "mangrove"
    ]
  ]
  print (word count workforce with [preference = "mangrove"] " individuals will look for work in mangroves")
  print (word count workforce with [preference = "migrant"] " individuals will look for migrant work")
end 

;; allocate a part of the workforce (ie. those with a preference) to migrant work
;; CHECK for what length of time does an individual migrate ? How many days work does he/she get?

to set-labour-migrant
  let would-be-migrants  workforce with [preference = "migrant"]
  
  ifelse migrant-jobcount <  count would-be-migrants
  [
    ask n-of migrant-jobcount would-be-migrants [set occupied (list days-per-tick  "migrant")]   ;; allocate randomly from workforce
    print (word migrant-jobcount " individuals migrate to find " days-per-tick " days of work")
  ]
  [ 
    ask would-be-migrants [set occupied (list days-per-tick "migrant" )]
    print (word count workforce " individuals migrate to find " days-per-tick " days of work")
  ]
  set workforce individuals with [occupied = []]
end 

;; It may or may not be possible to gain a good income from work in mangroves.
;; There is the seasonal availability (of honey etc) and demand variability (for shrimp fries etc) 
;; Fishing also depends on the availability of a boat and possession of a license.  
;; Those with some of these 'occupations' will not be a part of the casual labour workforce
;; TODO possiblity of illness, which can be associated with some activities - mangrove 

to set-labour-mangrove
  ;; TODO some of the workforce target fish whilst others target shrimp fry
  let would-be-fishers workforce with [preference = "mangrove"]
end 

to-report climate-regime
  ifelse month-id < 2 [report "Pre-monsoon"] [
    ifelse month-id < 5 [report "Monsoon"] [
      ifelse month-id < 7 [report "Post-monsoon"] [report "Fourth"]
    ]
  ]
end 

;; procedure updated at farmer's decision point
;; if they are owner-managed farms  set the occupation correspondingly
;; otherwise - if there is any tenancy arrangement - the occupier will have occupation set
;; and the owner of the leased farm will foresake this livelihood in order to enter the general job market'
 ;; other adults may be employed preferentially on the farm or may be casual workers ie. moving between tourism employment forest collection etc.

;; permanent livelihoods that don't need to change from tick to tick - licensed fin-fisher, crab fisher, guard  

to set-livelihoods
  ;; shrimp specific livelihoods
  ;; farm managers may employ guards if paddy calendar is start
  
  
 ;; ask farms [
  ;;  if owner = occupier [
  ;;    show [breed] of self
  ;;    ask owner [set occupation [breed] of self]
  ;;  ]
  ;;] 
  
 
  ;;  household heads of households near beach are all fishers
  ;;ask households with [member? patch-here mangrove] [ 
  ;;  ask head [
  ;;    set occupation (list "fisher"  )         ;; head
  ;;    set gear (list one-of gears)             ;; random one of gears defined by global list
  ;;    set vessel "canoe"                       ;; each fisher has a canoe
  ;;  ]
    
  
    
    ;; old generation of fishers - either the fisher or other household member may diversify
    ;; activity diversification
 ;;   if random-float 1 < (activity-diversification - 1)
 ;;   [
  ;;    ask head [set occupation list "fisher" "labourer"]
  ;;  ]
    ;; earner diversification
    
  ;;  if random-float 1 < (earner-diversification - 1) and adults > 1
  ;;  [
  ;;    ask one-of members with [occupation = [] and life-stage != "Child"] [ set occupation (list "labourer")]
  ;;  ]
   ;; assume other members are fishers (can assist the head) or look after household or unemployed
    
 ;; ]
  
  ;;  household heads of households near agriculture are all farmers
 ;; ask households with [member? patch-here agriculture] [ 
  ;;  ask head [
 ;;     set occupation (list "farmer")           ;; head
 ;;     set equipment (list one-of equipments)
 ;;   ]
    ;; activity diversification
    ;; new generation - the hh head would be the one to diversify into fishing
  ;;  if random-float 1 < (activity-diversification - 1)
 ;;   [
 ;;     ask head [set occupation list "farmer" "labourer"]
 ;;   ]
    ;; earner diversification
 ;;   if random-float 1 < (earner-diversification - 1) and adults > 1
 ;;   [
 ;;     ask one-of members with [occupation = [] and life-stage != "Child"] [ set occupation (list "labourer")]
 ;;   ]
    ;; assume other members are either farmers (can assist the head) or look after household or unemployed
;;  ]
end 

;; make the spinner for the upper right hand corner

to create-spinner
  create-spinners 1
  [ set shape "clock"
    setxy (min-pxcor + 1.5) (max-pycor - 1.5)
    ;; place it near top left corner, but not on top of a paddy
    if any? other turtles with [distancexy (min-pxcor + 1.5) (max-pycor - 1.5) < 1.8]
    [
      let tow towards min-one-of other turtles [distance myself]
      ;;print (word "found turtle at " tow)
      ifelse tow < 90 or tow > 270
      [
        setxy (min-pxcor + 1.5)(max-pycor - 3) ;; move it down
      ]
      [
        ifelse tow > 180
        [
         setxy (min-pxcor + 3) (max-pycor - 1.5) ;; move it right
        ]
        [
          setxy (min-pxcor + 1) (max-pycor - 1) ;; move it slightly up and left      
        ]
      ]
    ]  
    set color gray - 1.5
    set size 2.5
    set heading 0]
    ;;set label 0 ]
end 

;; move the hand on one unit (one hour)

to update-spinner
  ask spinners
  [ set heading month-id * 30
    ifelse climate-regime = "Monsoon"
    [set color blue]
    [set color grey]]
    ;;set label ticks ]
end 


;; done for each paddy at the relevant month 
;; harvest could be reduced by e.g. up to half due to crop damage by high salinity

to get-harvest-paddy
  ;; harvest depends on salinity ie. health
  ;; step function for health
  let binned ceiling (salinity * 5) ;; binned ranges from 1 to 5
  select-case binned [
       [ 1 "set health 1"]
       [ 2 "set health 0.8"]
       [ 3 "set health 0.6"]
       [ 4 "set health 0.5"]
       [ 5 "set health 0.4"]
  ]
  ;;
  ;; assume quadratic = function for health 1-xsq.
  set health  1 - ( salinity  *  salinity)
  set harvest (precision ( item 0 size-xy * item 1 size-xy * health ) 2) * max-paddy-harvest
  ;; show (word "salinity: " salinity ", health: " health)
   show (word "salinity: " precision salinity 2  ", health: " precision health 2 ", harvest: " harvest )
end 

;; similarly for shrimpfarm (benefits from high salinity)

to get-harvest-shrimpfarm
  ;; assume quadratic function for health  y = sqrt. of xs 
  set health sqrt salinity
  set harvest (precision ( item 0 size-xy * item 1 size-xy * health ) 2) * max-shrimp-harvest
  show (word "salinity: " precision salinity 2 ", health: " precision health 2 ", harvest: " harvest )
end 

;; TODO check the assumption that homestead-based nutrition is available year-round
;; As well as bought food, nutrition is a function of homestead production of fruit, vegetables and maintenance of livestock, poultry
;; It depends on subsistence production of rice, and fodder for livestock. TODO add trees and livestock agents
;; If salinity is too high it is depleted, in the same way as rice production

to-report health-homestead
  ;; assume quadratic = function for health 1-xsq.
  report 1 - ( salinity  *  salinity)    ;; it could represent the number of meals available per person per day
end 

;; diffuse chemical (salinity variable) over a link (rather than over neighbouring patches)
;; give equal shares of (number * 100) percent of the value of patch-variable to its eight neighboring patches

to diffuse-link [number]
  ask all-locations with [salinity > 0] [
    ;; sum the thicknesses of linked locations
    let total sum [thickness] of my-salinitylinks
    let todist salinity * number
    let share ( salinity * number / total )
    ;;show (word self " to distribute: " todist)
    ;; use myself to refer to the agent doing the asking
    ask salinitylink-neighbors [
      let before salinity
      set salinity salinity + share * [thickness] of salinitylink-with myself
      ;;show (word "before: " before ", after: " salinity)
    ]  
    set salinity salinity * number
  ]
end 

;; user will have a slider to control the weighting towards Child-type (CY, CE) households 
;; which will also influence the number of Child individuals within those households
;; the number of CYE will be hardcoded (not controled from interface)
;; more-elders will take a value from 1 to 5

to create-structured-households   
   ;; HH with all three generations present: Child, Young adult, Elder adult
   set number-hhtype-CYE 12
   ;; there should be an additional number of hh that is composed by various types (weighting determined by slider) equal to 24 
   
   select-case more-elders [
    [ 1 "set number-hhtype-CY 10 set number-hhtype-CE 4 set number-hhtype-YE 2 set number-hhtype-Y 6 set number-hhtype-E 2"]
    [ 2 "set number-hhtype-CY 8 set number-hhtype-CE 4 set number-hhtype-YE 4 set number-hhtype-Y 5 set number-hhtype-E 3"]
    [ 3 "set number-hhtype-CY 6 set number-hhtype-CE 4 set number-hhtype-YE 6 set number-hhtype-Y 4 set number-hhtype-E 4"]
    [ 4 "set number-hhtype-CY 4 set number-hhtype-CE 4 set number-hhtype-YE 8 set number-hhtype-Y 3 set number-hhtype-E 5"]
    [ 5 "set number-hhtype-CY 2 set number-hhtype-CE 4 set number-hhtype-YE 10 set number-hhtype-Y 2 set number-hhtype-E 6"]
   ]
   ;; sort the list of households into order in order to add a set of individuals into each
   let hh-list sort households
   
   ;; using gamma distribution for the structuring
   ;; the lower the alpha value the fatter the rh. tail (more skewed) and the higher the beta value the longer the tail 
   ;; 4.0 2 gives an expected value of 2 children
   ;; each additional unit added to alpha increases the expected value by an extra 0.5 
   let kids-alpha 9 - more-elders
   ;; there are likely to be fewer elders than children
   ;; 2 2 gives a mean of 1 elder and 6 2 gives a mean of 3 elders
   let elders-alpha 1 + more-elders
   
   repeat number-hhtype-CYE [
     let agent first hh-list  ;; take the first household agent in the sorted list                             
     let kids ceiling random-gamma kids-alpha 2 
     create-individuals kids [set life-stage "Child" set hh agent]
     let young random 4 + 1       ;; draws an integer strictly less than argument  
     create-individuals young [set life-stage "Young adult" set hh agent]
     let elder ceiling random-gamma elders-alpha 2
     create-individuals elder [set life-stage "Elder adult" set hh agent]
     ask agent [
       set members individuals with [hh = myself]  ;; set the agentset of members
       set hhtype "CYE"
     ]
     ;;print (word agent " C:" kids " Y:" young " E:" elder)
     set hh-list remove agent hh-list                        ;; remove it from the temporary list
   ]
   
   repeat number-hhtype-CY [
     let agent first hh-list
     let kids ceiling random-gamma kids-alpha 2
     create-individuals kids [set life-stage "Child" set hh agent]
     let young random 4 + 1
     create-individuals young [set life-stage "Young adult" set hh agent]
     ask agent [
       set members individuals with [hh = myself]
       set hhtype "CY"
     ]
     ;;print (word agent " C:" kids " Y:" young)
     set hh-list remove agent hh-list
   ]
   
   repeat number-hhtype-CE [
     let agent first hh-list
     let kids ceiling random-gamma kids-alpha 2 
     create-individuals kids [set life-stage "Child" set hh agent]
     let elder ceiling random-gamma elders-alpha 2
     create-individuals elder [set life-stage "Elder adult" set hh agent]
     ask agent [
       set members individuals with [hh = myself]
       set hhtype "CE"
     ]
     ;;print (word agent " C:" kids " E:" elder)
     set hh-list remove agent hh-list
   ]
   
   repeat number-hhtype-YE [
     let agent first hh-list
     let young random 4 + 1
     create-individuals young [set life-stage "Young adult" set hh agent]
     let elder ceiling random-gamma elders-alpha 2
     create-individuals elder [set life-stage "Elder adult" set hh agent]
     ask agent [
       set members individuals with [hh = myself]
       set hhtype "YE"
     ]
     ;; print (word agent " Y:" young " E:" elder)
     set hh-list remove agent hh-list
   ]
   ;; single generation households
   repeat  number-hhtype-Y [
     let agent first hh-list
     let young random 4 + 1
     create-individuals young [set life-stage "Young adult" set hh agent]
     ask agent [
       set members individuals with [hh = myself]
       set hhtype "Y"
     ];;print (word agent " Y:" young)
     set hh-list remove agent hh-list
   ]
   repeat  number-hhtype-E [
     let agent first hh-list
     let elder ceiling random-gamma elders-alpha 2
     create-individuals elder [set life-stage "Elder adult" set hh agent]
     ask agent [
       set members individuals with [hh = myself]
       set hhtype "E"
     ];;print (word agent " E:" elder)
     set hh-list remove agent hh-list
   ]
  
   ;; place individual on one of the homeset patches
   ask individuals [
     set assets []
     set accessed-income 0
     set occupied []
     hide-turtle
     let all-pl [homeset] of hh 
     ;;show all-pl
     ;; compute possible (unoccupied) places in the homeset
     let pos-pl nobody
     foreach sort all-pl [    
       if not any? turtles-on ?[
         set pos-pl (patch-set pos-pl ?)
       ]
     ]
     ;; show pos-pl
     ifelse pos-pl = nobody
     [
       die
       show (word "killed individual-" who " because no place left in homeset" )
     ]
     [
       let place one-of pos-pl
       set location place
       move-to place
     ]
     
     
;     loop [   ;; place individual on one of the homeset patches
;       let place one-of [homeset] of hh
;       if not any? turtles-on place [
;         set location place
;         move-to place
;         stop
;       ] 
;     ]    
   ]
end 

to setup
  clear-all              ;; resets all global variables to zero, and calls reset-ticks, clear-turtles, clear-patches, clear-drawing, clear-all-plots, and clear-output.
  
  set ticks-per-month 4  ;; assume a number of ticks per month (correponding to casual work periods)
  ;; timelevel below the  month
  set the-period 0
  set month-id 0
  set days-per-tick 22 / ticks-per-month ;; ticks-per-month = 4 ->  5.5 work days per tick
  
  ;; parameters needed before agent creation
  ;; world-width and world-height set in view (default is -16 to +16)
  set min-distance 5         ;; distances between two farms
  set max-distance 10
  set tries-paddys 40
  set riverbank-distance 1.2
  
  set farmsize-min 1
  set farmsize-max 5
  set number-households 36    ;; this should equal the number used in the create-structured-households method
  set more-elders 3           ;; value between 1 and 5
  ;; owners' costs associated with each type of farming. input costs (monthly) and payment (income) for casual labour (daily)
  ;; labour required each month (peracre or perfarm)  (can be outside or local work)
  ;; owners' incomes from farming can vary; they are not estimated here
  set labour-shrimps-peracre 3     ;; low labour - 20 days/acre/year according to Datta -  or 3 per acre (own source) 
  set cost-shrimps-peracre 5000    ;; 2000 for larvae (seasonal) and 3000 for fertiliser (annual) 
  set income-shrimps 175           ;; maintenance of shrimpfarm - Akhter
  set income-guards 200            ;; well-paid 
   
  set labour-paddys-peracre 20     ;; high labour requirments based on 200 person days per hectare per year (80 days or 20 days/acre/month) - 63 days/acre/year according to Datta
  set cost-paddys-peracre 0        ;; not intensive
  set income-paddys 200            ;; work includes: transplantation, harvesting and weeding
  set labour-guards-perfarm 1      ;; few jobs in security
  set initial-rental-rate 100      ;; initial farm rental payment per month per ha
  
  set pareto-rule one-of (list "90-10" "80-20" "70-30" "60-40" "50-50")
  ;; two params that didn't seem relevant to the stakeholders in our locations
  set village-law one-of (list "none" "desalinisation law" "land zoning" "desalinisation law and land zoning")
  set LZ-buffer? 10
  
  ;; other livelihoods available to casual worker based on ecosystem exploitation
  ;; labour depends on other factors (like availability of paid work, risk of the activity, ES state) 
  ;; income also depends on other factors
  ;; set income-fries 100         ;; collected from river (illegally)
  set income-mangroves 250        ;; products collected from forest - legally or illegally?
  set income-migrant 150          ;; outside (migrant) work
  set max-daily-food-cost 200
  set min-daily-food-cost 100
  
  ;; other product values and costs
  ;; would give max gross income of 12,500 taka per ha
  set price-rice 15                   ;; 15 - 20 taka per kilo (Akhter), a constant  TODO variable price of paddy - not sure what this depends on
  set max-paddy-harvest 1.8           ;; metric ton (Akhter)
  set max-shrimp-harvest 0.4          ;; ?? TODO ask for local data 
  
  ;; food production globals
  set veg-avail false
  set hsh-condition 0.70
  set fish-maturity 10                ;; 10 ticks to raise fish - estimate
  set fishtick fish-maturity          ;; initialise to meet the condition
  ;; these are parameters chosen in the interface by the model user
  ;; set initial-shrimpfarms chosen-initial-shrimpfarms
  ;;set initial-shrimpfarms round percentage-shrimpfarms * numberi
  set buffer-distance LZ-buffer?      ;; distance between shrimp pond and protected zones - village
 
  ;; set monsoon-saltrinse 0.45       ;; 45 percent reduction according to "rice to shrimp" by A.M.S. Ali. chosen-monsoon-saltrinse
  set monsoon-saltrinse 0.2           ;; in satkhira it is lower
  set prop-diffused 0.5 
  set monsoon-onset ["Ashar" 1]       ;; monsoon normally occurs at the beginning of Ashar
  
  ;; add tracks to/from village at 0. 0
  ;;create-tracks 2
;  [ set xcor 0 set ycor 0
;    set shape "line half"
;    set color brown
;    ;; calculate length of hypotenuse i.e length of track
;    select-case floor (heading / 45)
;    [
;      [ 0 "set hyp max-pxcor / cos heading"]  
;      [ 1 "set hyp max-pxcor / cos (90 - heading)"]   
;      [ 2 "set hyp max-pxcor / cos (heading - 90)"]    
;      [ 3 "set hyp max-pxcor / cos (180 - heading)"] 
;      [ 4 "set hyp max-pxcor / cos (heading - 180)"]  
;      [ 5 "set hyp max-pxcor / cos (270 - heading)"] 
;      [ 6 "set hyp max-pxcor / cos (heading - 270)"]  
;      [ 7 "set hyp max-pxcor / cos (360 - heading)"]  
;    ]
;    ;;print (word "track length: " hyp)
;    set size 2 * hyp
;  ]
; 
  
  ;; create the village in the centre of the window
  create-villages 1
  [ 
    set xcor 0 set ycor 0
    set shape "house"
  ]
  
  ;; add river through village
  position-river
  
  ;; create mangrove - choose one of the corners at random
  create-mangroves 1
  [
    set xcor one-of list max-pxcor min-pxcor   ;; choose one of the corners at random
    set ycor one-of list max-pycor min-pycor
    hide-turtle
    ;;set label "MANGROVE"
  ]
  
  set-default-shape farms "rice"
  create-farms tries-paddys [
    set harvest 0
    set annual-profit 0
    set size-xy (list (farmsize-min + random-float (farmsize-max - farmsize-min)) (farmsize-min + random-float (farmsize-max - farmsize-min)))
    position-paddy
    set area (item 0 size-xy) * (item 1 size-xy)
    set rotation "paddy"
    set landuse "paddy"
    set color green
    set payment-deferred false
    set rental-rate initial-rental-rate
  ]
  
  
   ;; create mangrove patchset
   ;;set mangrove-forest patch-set patches in-radius 7.5 with [distance min-one-of farms [distance one-of-mangroves] > 2 ]
   ;;ask mangrove-forest [set pcolor 52]  
  ask mangroves [ 
    ask patches in-radius 7.5 with [distance min-one-of farms [distance myself] > 2 ]  [set pcolor 52]  ]
  set mangrove-forest patch-set patches with [pcolor = 52]
  ask mangroves [set size count mangrove-forest] 
  show (word "Mangrove area is " [size] of one-of mangroves " acres")
  ask min-one-of mangrove-forest [abs pxcor] [
    set plabel "MANGROVE"
    set labelled-mangrove-patch self 
  ]
  
  set all-locations (turtle-set farms villages mangroves)          ;; create set of all locations
  
  ;; link the locations, including the village & mangroves, and set thickness of links which will determine speed of diffusion
  ask farms [
    create-salinitylinks-with other farms with [distance myself < max-distance]
    ;; link salinity of farmland with salinity of village tubewell used for drinking and irrigation
    if distance one-of villages < max-distance [create-salinitylink-with one-of villages]    
    ;; link salinity of farmland with salinity of mangroves, various ecosystem services (fish, shrimp fry, honey etc)
    if distance one-of mangroves < max-distance [create-salinitylink-with one-of mangroves]
  ]
  ;; the argument to random-float has no incidence on the result because flows are relative to other links
  ask salinitylinks [set thickness random-float 0.2]
  
  ;; turn some of the paddys into shrimpfarms
  set initial-shrimpfarms round (percentage-shrimpfarms * count farms / 100)
  ifelse village-law = "land zoning" or village-law = "desalinisation law and land zoning"
  [ 
    ask n-of initial-shrimpfarms farms with [distance one-of villages > buffer-distance and riveraccess != nobody]
    ;;ask n-of initial-shrimpfarms farms with [distance one-of villages > buffer-distance and distance one-of mangroves > buffer-distance]
    [ 
      set rotation "shrimp"
      set shape "shrimp"
      set color red
    ]
  ]
  [ 
    let possible-isf count farms with [riveraccess != nobody]
    if initial-shrimpfarms > possible-isf [
      print (word "there are only " possible-isf " farms with river access")
      set initial-shrimpfarms possible-isf
    ]
    ask n-of initial-shrimpfarms farms with [riveraccess != nobody]
    [ 
      set rotation "shrimp"
      set shape "shrimp"
      set color red
    ]
  ]
  
  set number-paddys count farms with [rotation = "paddy"]
  print (word "number of paddys: "  number-paddys)
  print (word "number of shrimpfarms: "  count farms with [rotation = "shrimp"])
  
  ;; create households
  create-households number-households [
    set zoom-location []
    set location one-of villages        ;; households will all be located at 0 0, ie the village
    hide-turtle
  ]
  
  ;; create a list of locations in the village
  let x-list n-values 6 [?]
  let y-list n-values 6 [?]
  let zoom-location-list []
  ;; assign each household to one of them
  foreach x-list [
    let x ?
    foreach y-list [
      let y ?
      set zoom-location-list lput (list x y) zoom-location-list
      ask one-of households with [zoom-location = []] 
      [
         set zoom-location (list x y)      ;; assign
         let px x - 3
         let py y - 3
         set homeset patches with [pxcor > px * 5 and pxcor < px * 5 + 5 and pycor > py * 5 and pycor < py * 5 + 5]
         move-to one-of homeset
      ]
    ]
  ]
  ;; set display properties
  set-default-shape households "house"
  ask households [set size 1]
  ask households [set color black]
  
  ;; TODO update this every tick: let landless households with [assets = []]
  
  
  ;; create-individuals and put them in households, initialise assets
  ;; user will have a slider to control the weighting towards Child-type (CY, CE) households 
  ;; which will also influence the number of Child individuals within those households
  ;; the number of CYE will be hardcoded (not controled from interface)
  ;; more-elders will take a value from 1 to 5
  create-structured-households
  
  print (word "number of individuals in " number-households " households: "  count individuals)
  ;; assign heads - random adult
  foreach sort households 
  [
    ask ? [ set head one-of members with [life-stage = "Young adult" or life-stage = "Elder adult"]]
  ]
  ;; make a list of these heads
  let heads []
  foreach sort households [
      set heads lput [head] of ? heads
  ] 
  set headset turtle-set heads
  
  ask individuals [set savings 0] ;; heads control household savings as well as assets
  ;; using inverse transform sampling, compute initial income distribution depending on E slider setting
  ;; The larger the Pareto index, the smaller the proportion of very high-income people
  let alpha 1                             ;; pareto index or tail index or shape parameter α
  let xm 100                              ;; scale parameter xm is the minimum possible value of x
  if pareto-rule = "90-10" [set alpha 1.048] 
  if pareto-rule = "80-20" [set alpha 1.161] ;; income is pareto distributed (but total income is not same for different values of alpha)
  if pareto-rule = "70-30" [set alpha 1.421] ;; α = log(0.3)/log(3/7)
  if pareto-rule = "60-40" [set alpha 2.260]
  if pareto-rule = "50-50" [set alpha 100] 
  let power-term 1 / alpha
  ask headset [
    let denom random-float 1 ^ power-term
    let t xm / denom
    set accessed-income precision t -2   ;; round to nearest 100
    set savings 0
    set label "h"
    set label-color black
  ]
  
  ;; assign each asset (paddys and shrimpfarms) to a household chosen at random
  ;; TODO in some cases they are ousiders to the village 
  let paddy-list sort farms with [rotation = "paddy"] 
  let index 0
  repeat number-paddys [
    let winner one-of heads
    ask winner [set assets lput item index paddy-list assets]
    ask item index paddy-list [set owner winner] 
    set index index + 1
  ]
  
  let shrimpfarm-list sort farms with [rotation = "shrimp"] 
  set index 0
  repeat initial-shrimpfarms [
    let winner one-of heads
    ask winner [set assets lput item index shrimpfarm-list assets]
    ask item index shrimpfarm-list [set owner winner] 
    set index index + 1
  ]
  
  ;; set shape and color of individuals 
  set-default-shape individuals "person"
  ask individuals [
    if life-stage = "Child" [
      set size 0.75
      set color 35
      set color black
    ]
    ;;if life-stage = "Young adult" [set size 1 set color 35]
    ;;if life-stage = "Elder adult" [set size 1 set color 5]
    if life-stage != "Child" [set size 1 set color black]
  ]
 
  ;; TODO set livelihood class of individuals
  ;;ask n-of 10 households [
  ;;  ask members [set class "LNS"]
  ;;]                      ;; set LNS as default

  ;; TODO put individuals into various networks using different links
  ;; can display these using an appropriate layout in a new 'view' window
  ;; I assume that households don't have links but individuals do. However, households may
  ;; linked if an individual in each has links to 2 or more individual in the other household (??)
  
  ;; make shapes twice as big as patch sizes, set colours
  ask farms [set size 2]
  ask villages [set size 2]
  ask villages [set color brown]
  
  
  ;; create the clock in the upper rhs.
  create-spinner
   
  ;; TODO set initial livelihoods/occupations based on  initial decisions of heads not to rent
  ask farms [
    set manager owner
  ]
  
  ;; create the fish population model
  ask mangroves [
    set adult-count 100
    set juvenile-count 0
    set shoal-size adult-count + juvenile-count
    ;;set label juvenile-count
  ]

  display
  reset-ticks
  
  ;; make a road which cuts around farmland rather than through it, with linked elements rather than a patchset
  ;; position-road
end 

;; check display

to check-view-state
  clear-patches
  ifelse zoom = true [
    ask households [ 
      ask homeset [set pcolor white]
      if nutrition = 2 [ask homeset [set pcolor red]]
       if nutrition = 3 [ask homeset [set pcolor 6]]
        if nutrition = 4 [ask homeset [set pcolor 2]]
      
    ]
    ask all-locations [ hide-turtle  ]
    
    ask salinitylinks [set hidden? true]
    ask riverlinks [set hidden? true]
    ask individuals [show-turtle]
    ask households [show-turtle]
    ;; TODO place the individuals in a more regular way
    
    if labels? []  ;; controlled on interface
    
    
     
  ]
  [
    ;; case zoom is false, display the farms and mangrove
    ask all-locations [
      show-turtle
      if salinity? [                                             ;; controlled on interface
        ask patches in-radius (salinity * min-distance) [
          ;;set pcolor (list 100 100 100 100) ;; create an agent and use transparent color?
          set pcolor grey
        ]
      ]
    ]
    
    ask individuals [hide-turtle]
    ask households [hide-turtle]
    ask salinitylinks [set hidden? false]
    ask riverlinks [set hidden? false]
   
    ;; draw mangroves
    ask mangroves [hide-turtle]
    ask labelled-mangrove-patch [set plabel "MANGROVE"]
    ask mangrove-forest [set pcolor 52] 
    
     if labels? [ask farms [set label (word "Profit:" farm-profit)]]  ;; controlled on interface
  ]
end 

;; timelevels are the-month (numeric month-id) and the timelevel below the-month, the-period 

to set-month
  ;; month is calculated from the value of tick
  
  let period-of-year ticks mod (ticks-per-month * 12) ;; "period" is timelevel below "month" timelevel
  set month-id floor (period-of-year / ticks-per-month)
  
  ;; these variables could be useful
  set year-id floor (ticks / (ticks-per-month * 12))
 
  ;; select the correct string for current month (* - not permitted to resalinise)
  select-case month-id [
    [ 0 "set the-month \"Baisakh\""]   ;;  sf harvest pre monsoon
    [ 1 "set the-month \"Jaistha\""]   ;; * MAY-JUNE  add sf harvest here? pre-monsoon
    [ 2 "set the-month \"Ashar\""]     ;; * monsoon-saltrinse add sf harvest here? monsoon
    [ 3 "set the-month \"Sraban\""]    ;; * JULY-AUG aman start? add desalinisation law? monsoon
    [ 4 "set the-month \"Bhadra\""]    ;; * CHANGE sf harvest -> rice culivation  add desalinisation law? monsoon
    [ 5 "set the-month \"Ashwin\""]    ;; paddy harvest add desalinisation law? post monsoon
    [ 6 "set the-month \"Kartik\""]     ;; add sf  here? OCT - NOV aman harvest? post monsoon
    [ 7 "set the-month \"Agrahayan\""]
    [ 8 "set the-month \"Poush\""]       ;; one-cycle shrimp (dec-june )
    [ 9 "set the-month \"Magh\""]        ;; CHANGE sf harvest -> sf cultivation JAN-FEB
    [ 10 "set the-month \"Falgoon\""]
    [ 11 "set the-month \"Chaitra\""]   ;; add sf harvest here? 
  ]
    ;; calculate climate - now using climate-regime reporter  
end 

;; farming work depending on month
;; migrant work depending on month (try to get migrant work if no local work)

to set-calendar
  ;; paddy
  ifelse month-id < 3
  [  set paddycalendar "" ]
  [  ifelse month-id < 6 
    [ set paddycalendar "cultivate" ]
    [ ifelse month-id = 6
      [ set paddycalendar "harvest" ]
      [ set paddycalendar "" ]
    ]
  ]
  if month-id = 3 [set paddycalendar "start"]

  ;; shrimp
  ifelse month-id < 3
  [  set shrimpcalendar "harvest" ]
  [  ifelse month-id < 6 
    [ set shrimpcalendar "" ]
    [ ifelse month-id < 11
      [ set shrimpcalendar "cultivate" ]
      [ set shrimpcalendar "harvest" ]
    ]
  ]  
  if month-id = 6 [set shrimpcalendar "start"]
  
  print (word "Calendar paddy: " paddycalendar ",  shrimp: " shrimpcalendar)
  
  ;  string  calendar  Climate-regime      shrimp     paddy     other              migrant main
;            
;0  Baisakh  APR-MAY   pre monsoon       harvest                                   building  
;1  Jaistha  MAY-JUNE  pre monsoon       harvest                                   building 
;2  Ashar    JUNE-JULY Monsoon-saltrinse harvest                veg start
;3  Sraban   JULY-AUG  Monsoon                      start       cultivate
;4  Bhadra   AUG-SEP   Monsoon                      cultivate   veg avail
;5  Ashwin             post monsoon                 cultivate   veg avail + harvest
;6  Kartik   OCT - NOV post monsoon      start      harvest     veg avail
;7  Agrahayan          fourth            cultivate              veg avail           paddy    
;8  Poush              fourth            cultivate                                  paddy    
;9  Magh     JAN-FEB   fourth            cultivate                                  building    
;10  Falgoon           fourth            cultivate                                  building    
;11  Chaitra MARCH-APR fourth            harvest                                    building    

;; monsoon is aug until december (Rahman)
;; sluice feb-april

  ;; migrant calendar data collected by NM. % people engaged working outside
  ;; assume that this is the maximum that could be employed/ available jobs
  ;; TODO if possible check if this figure is total adults or more specific sector of the workforce 
  let total-adults count individuals with [life-stage != "Child"]
  select-case month-id [
    [ 0 "set migrant-work 0.75"]   ;;  
    [ 1 "set migrant-work 0.5"]    ;; MAY-JUNE  
    [ 2 "set migrant-work 0.25"]     ;; 
    [ 3 "set migrant-work 0.05"]     ;; JULY-AUG 
    [ 4 "set  migrant-work 0.05"]     ;; 
    [ 5 "set  migrant-work 0.0"]      ;; 
    [ 6 "set  migrant-work 0.35"]     ;; OCT - NOV
    [ 7 "set  migrant-work 0.50"]
    [ 8 "set  migrant-work 0.90"]     ;; 
    [ 9 "set  migrant-work 0.75"]     ;;JAN-FEB
    [ 10 "set  migrant-work 0.75"]
    [ 11 "set  migrant-work 0.65"]    ;; MARCH-APR
  ]
  set migrant-jobcount floor (total-adults * migrant-work)
  print (word "Total migrant jobs: " migrant-jobcount)           ;; prospects are calculated in set-local-labour to shape decisions
  ;;ifelse month-id < 2
 ;; [  set migrantcalendar "building" ]
  ;;[  ifelse month-id < 7
  ;;  [ set migrantcalendar "" ]
  ;;  [ ifelse month-id < 9
  ;;    [ set migrantcalendar "paddy" ]
  ;;    [ set migrantcalendar "building" ]
 ;;   ]
end 


;; useful switch/case procedure
;; Agent runs a command task or a string containing commands.

to select-case [ value cases ]
foreach cases
[ 
  if first ? = value [ run last ? stop ]
]
end 

;; paddy context

to position-paddy
  let exit false
  let tries 0
  while [exit = false] [
    ;;print "stuck in while"
     ;; report a random floating point number from the allowable range of turtle coordinates along the given axis, x or y.  
     let rfx random-xcor 
     let rfy random-ycor
     set xcor rfx
     set ycor rfy
     ;; distancexy reports distance from this agent to the point (xcor, ycor) and distance reports distance from this agent to another
     ;; paddys not allowed too close to other paddy or the village or mangrove
     ;; myself here refers to the current paddy that we are positioning
     ;;show distance min-one-of rivernodes [distance myself] ;;< riverbank-distance  
     ifelse any? other farms with [distance myself < min-distance] or distance one-of mangroves < min-distance or distance one-of villages < min-distance or (distance min-one-of rivernodes [distance myself]) <  riverbank-distance
     [
       set tries tries + 1
       if tries > 20 
       [  die 
          set exit true
       ] ;; limit the number of paddy agents
     ]
     [ 
       let river-distance distance min-one-of rivernodes [distance myself]
       ;; if the farm extent reaches to the river - use farmsize-max to be generous
       ;;ifelse river-distance < max size-xy
       ifelse river-distance < farmsize-max
       [ set riveraccess self
         ;;print (word "distance from river: " precision river-distance 2 " access is possible")
       ]
       [ set riveraccess nobody
         ;;print (word "distance from river: " precision river-distance 2 " access is not possible")
       ]
       ifelse riveraccess = nobody
       [set label ""]
       [set label "R"]
       set exit true
     ]
  ] 
end 

;; place a river node at each point along x=0 axis
;; river links are directed from top most point of grid (where y= max value)
;; todo set as directed

to position-river
  let river-x 1
  ;; start at top where y takes maximum value (+16)
  let intlist n-values (max-pycor + 1 ) [?]
  foreach intlist [
    create-rivernodes 1 [
      set xcor river-x
      set ycor ?
    ]
  ]
  set intlist n-values max-pycor [?]
  foreach intlist [
    create-rivernodes 1 [
      set xcor river-x
      set ycor 0 - (1 + ?)
    ]
  ]
  ask rivernodes [
    let mywho who
    ;;create-riverlinks-to rivernodes with [who = mywho + 1] 
    create-riverlinks-with rivernodes with [who = mywho + 1] 
    hide-turtle
  ]
  ask riverlinks [
    set color blue
    set thickness 0.4
  ]
end 

;; update fish shoal in mangroves

to update-fishes
  let reproduction-rate 10
  let my-carrying-capacity 400
  let the-population-growth-rate 0.1
  ask mangroves [
    if ticks mod reproduction-rate = 0 [
      let An adult-count
      show word "adult count now: " adult-count
      let Jn juvenile-count 
      show word "juvenile count now: " Jn
      let An+1 An + Jn
      if An+1 > my-carrying-capacity [set An+1 my-carrying-capacity]   ;; observe the cc
      show word "new total adults: " An+1
      show word "carrying capacity: " my-carrying-capacity
      let power-term  the-population-growth-rate * ( 1 - ( An+1 / my-carrying-capacity ) ) 
      let Jn+1 An+1 * e ^ power-term
      ;;let Jn+1 An+1 * e ^ the-population-growth-rate * ( 1 - ( An+1 / my-carrying-capacity ) )  
      show word "new juveniles: " Jn+1
      set juvenile-count Jn+1
      set adult-count An+1
      set shoal-size adult-count + juvenile-count
      show word "total adults and juveniles: " shoal-size
      show word "+++++++++++++++++++++++++++++++ ignore:" color
    ]
    
    ;; test -assume some kind of constant take
    set adult-count adult-count - 20
  ]
  
;  ask hunters [
;    fd random-float 1
;    rt 30 - random 60
;    if any? fishes in-radius vision [
;      ask one-of fishes in-radius vision [
;        set adult-count adult-count - 5
;        ask myself [ set take take + 5 ]
;        ]
;      ]
;    set label word "I've eaten this many adults: " round take
;  ]
end 

;to position-road
;  ;; start from village
;  create-rivernodes 1 [
;    set ID 0
;    set xcor 0
;    set ycor 0
;  ]
;  
;  create-rivernodes 1 [
;    set ID 1
;    let x1 0
;    let y1 0
;   
;    ask one-of villages [
;      ask one-of my-links [
;        set x1 link-xcor
;        set y1 link-ycor
;      ]
;    ]
;    set xcor x1
;    set ycor y1
;  ]
;        
;     
;end

;; calculate the export price for shrimp, an important external driver - TODO use data
;; According to the comment in Rahman paper that net income is 10 times higher than for than rice production

to current-price-shrimps
  set price-shrimps 400   ;; minimum price is 400, max is 1000 (Akhter) 
  select-case year-id [
    [ 0 "set price-shrimps 400"]   
    [ 1 "set price-shrimps 500"]   
    [ 2 "set price-shrimps 600"]
    [ 3 "set price-shrimps 700"]
    [ 4 "set price-shrimps 800"]
    [ 5 "set price-shrimps 900"]
    [ 6 "set price-shrimps 1000"]
    [ 7 "set price-shrimps 900"]
    [ 8 "set price-shrimps 800"]
    [ 9 "set price-shrimps 700"]     
    [ 10 "set price-shrimps 600"]
    [ 11 "set price-shrimps 500"] ;; current price
  ]
end 

to-report link-xcor
  report mean [xcor] of both-ends
end 

to-report link-ycor
  report mean [ycor] of both-ends
end 

;; count the number of occurrences of an item in a list

to-report occurrences [x the-list]
  report reduce
    [ifelse-value (?2 = x) [?1 + 1] [?1]] (fput 0 the-list)
end 

There are 3 versions of this model.

Uploaded by When Description Download
Richard Taylor almost 11 years ago updated model with Satkhira data Download this version
Richard Taylor almost 12 years ago updated Download this version
Richard Taylor almost 12 years ago Initial upload Download this version

Attached files

File Type Description Last updated
saline-ecosystem.png preview Preview for 'saline-ecosystem' about 11 years ago, by Richard Taylor Download
saline-ecosystem.png preview Preview for updated model almost 11 years ago, by Richard Taylor Download

This model does not have any ancestors.

This model does not have any descendants.