This page was automatically generated by NetLogo 5.0.5.

The applet requires Java 5 or higher. Java must be enabled in your browser settings. Mac users must have Mac OS X 10.4 or higher. Windows and Linux users may obtain the latest Java from Oracle's Java site.


In order for this to work, this file, your model file (AgentBased Switchgrass Model.nlogo), and the files NetLogoLite.jar and NetLogoLite.jar.pack.gz must all be in the same directory. (You can copy NetLogoLite.jar and NetLogoLite.jar.pack.gz from the directory where you installed NetLogo.)

On some systems, you can test the applet locally on your computer before uploading it to a web server. It doesn't work on all systems, though, so if it doesn't work from your hard drive, please try uploading it to a web server.

You don't need to include everything in this file in your page. If you want, you can just take the HTML code beginning with <applet> and ending with </applet>, and paste it into any HTML file you want. It's even OK to put multiple <applet> tags on a single page.

If the NetLogoLite files and your model are in different directories, you must modify the archive= and value= lines in the HTML code to point to their actual locations. (For example, if you have multiple applets in different directories on the same web server, you may want to put a single copy of the NetLogoLite files in one central place and change the archive= lines of all the HTML files to point to that one central copy. This will save disk space for you and download time for your users.)

powered by NetLogo

view/download model file: AgentBased Switchgrass Model.nlogo

WHAT IS IT?

The case study that will be used to demonstrate the usefulness of an AB-LCA framework is the switchgrass bioenergy system. Although it has been grown in buffer strips to reduce non-point source emissions from agriculture, switchgrass is not currently cultivated as a commodity crop. In the long run, switchgrass may grow as a dedicated energy crop as envisioned by both existing bioenergy plans (e.g., EISA or state RPS) or proposed pathways such as the “90-Billion Gallon Biofuel Deployment Study” conducted by the Sandia National Laboratories and General Motors [West et al. 2009].

Switchgrass was chosen for this research effort due to a variety of reasons. First, its broad cultivation range allows it to be grown throughout the U.S. In this way, the heterogeneous nature of different policy regimes and logistical supply chains can be explored.
The model encompasses the following entities:
1. Agents
• Farmers: There are the main actors of this model. The strength of this modeling framework is the explicit use of spatially variable data, which cannot be accurately represented with at traditional LCA approach. Here, each farmer possesses various individual characteristics (e.g., age, land size, familiarity, risk aversion, etc.) that will affect their decision-making.
• Refineries (Fuel Plants): Biofuel refineries process switchgrass into ethanol, which is used as a substitute for gasoline in the transportation sector. Currently, first generation bio-refineries process corn sugars into ethanol. Second generation “advanced cellulosic” refineries have been proven in concept but have not been established on a commercial scale. The switchgrass biofuel supply chain analyzed in our case study uses these second-generation cellulosic refineries. Each refinery agent in the case study has its own operating parameters much like each farmer agent has its own growing conditions. Conversion rates (liters of fuel per tonne of switchgrass), process energy intensity, and location are all factors that vary among refineries. These values need to be set before importing the refineries into the scenario modeler.
• Co-fired Generation Plants (Electric Plants): Another agent type for the switchgrass case study is co-fired generation plant. These electricity-generating utility plants can burn dry switchgrass to heat water in a typical Rankine power cycle. Typically biomass is used to supplement a more energy dense fuel such as coal. The percentage of biomass to total fuel mass is called the co-fired percentage. Typical co-fired percentages are around 6%. The scenario modeler will analyze the emissions associated with burning biomass to produce electricity and will compare it to the fuel that it is replacing in the generation plants. Values such as heat rate, parasitic energy loss, and geographic location are set for each generation plant agent before running the scenario modeler.

  1. Patches
    They represent the agricultural parcel owned by the farmers. Each patch is a parcel. Farmers can decide to increase or decrease the amount of land they devote to switchgrass at each time step.

A farm agent has its own state, which is updated after every simulation period of one. The state of the farm agent includes personal characteristics and potential gain from planting switchgrass. The model encompasses the following entities:
1. Agents
• Farmers: There are the main actors of this model. The strength of this modeling framework is the explicit use of spatially variable data, which cannot be accurately represented with at traditional LCA approach. Here, each farmer possesses various individual characteristics (e.g., age, land size, familiarity, risk aversion, etc.) that will affect their decision-making.
• Refineries (Fuel Plants): Biofuel refineries process switchgrass into ethanol, which is used as a substitute for gasoline in the transportation sector. Currently, first generation bio-refineries process corn sugars into ethanol. Second generation “advanced cellulosic” refineries have been proven in concept but have not been established on a commercial scale. The switchgrass biofuel supply chain analyzed in our case study uses these second-generation cellulosic refineries. Each refinery agent in the case study has its own operating parameters much like each farmer agent has its own growing conditions. Conversion rates (liters of fuel per tonne of switchgrass), process energy intensity, and location are all factors that vary among refineries. These values need to be set before importing the refineries into the scenario modeler.
• Co-fired Generation Plants (Electric Plants): Another agent type for the switchgrass case study is co-fired generation plant. These electricity-generating utility plants can burn dry switchgrass to heat water in a typical Rankine power cycle. Typically biomass is used to supplement a more energy dense fuel such as coal. The percentage of biomass to total fuel mass is called the co-fired percentage. Typical co-fired percentages are around 6%. The scenario modeler will analyze the emissions associated with burning biomass to produce electricity and will compare it to the fuel that it is replacing in the generation plants. Values such as heat rate, parasitic energy loss, and geographic location are set for each generation plant agent before running the scenario modeler.

  1. Patches
    They represent the agricultural parcel owned by the farmers. Each patch is a parcel. Farmers can decide to increase or decrease the amount of land they devote to switchgrass at each time step.

A farm agent has its own state, which is updated after every simulation period of one. The state of the farm agent includes personal characteristics and potential gain from planting switchgrass.

HOW IT WORKS

Farmer agents decide at the beginning of each growing season whether to continue their previous year’s cropland allocation. The growing season is simulated and switchgrass carbon sequestration is calculated. At the end of the growing season, the model calculates farmer’s revenues and determines their profitability, and accounts for the tailpipe emissions when the fuel is eventually used. To better understand the model conceptualization, we present below the detailed model scheduling which is a description of the agent routine and their actions for every iterations, At every time step, each agent performs the following tasks in a chronological order:

  1. At the beginning of each simulation year, each farmer compares their current revenues to the expected revenues from planting switchgrass. The farmer proceeds to the next step only if the potential profit is higher than the current profit.
  2. Each farmer has distinct individual attributes including age, familiarity with switchgrass, level of risk-aversion, and level of education (see Table 1). Farmers determined their eligibility to plant by comparing their level of familiarity, risk-aversion and education to the overall average in the system. Farmers with attribute over the average level will adopt switchgrass in their land. They Farmers will plant switchgrass on a portion of their land, which is randomly determined based on a normal distribution.
  3. At the end of each simulation year, the amount of harvested switchgrass for each farmer is calculated by multiplying the yield with a post-harvesting loss rate. The yield is randomly determined through a normal distribution (yield source: McLaughlin and Kszos 2005). The post-harvesting loss rate is randomly determined with a normal distribution [Samson 2007], representing production losses during harvesting activities such as storage, processing and transportation.
  4. Farmers decide to sell their switchgrass to either a biorefinery to produce bioethanol or a power plant to generate electricity. All farmers with switchgrass feedstock send all of it to the refinery. The decision-making of this part of the model is not studied, therefore no competition between refinery is in place in the current model, they just sell all of their feedstock to the closest refinery, see pseudo code below:
    IF
    age of farmer < average age and Familiarity with switchgrass > average familiarity
    with switchgrass
    and
    Risk aversion < average Risk aversion and Education > average education
    THEN
    [Plant switchgrass]
    Return qualified farmers
  5. CO2 emissions from each process of the life cycle of the system are calculated using life cycle inventory (LCI) data (Appendix E) from GREET model [Argonne National Laboratory 2012]. The LCI includes CO2 emissions sequestrated by switchgrass plantation, emissions generated from harvesting, transportation fuel use in logistics, power generation, and biofuel production, and emissions avoided by replacing fossil fuels or fossil fuel-based electricity.

  6. Only profitable farmers that grow switchgrass in the previous simulation year will replant in the next year.
  7. Farmers who did expect more profits but not plant in this round of simulation have an opportunity to “change their minds” by learning from their neighbor farmers with a certain radius. If the majority of their neighbors plant switchgrass and are profitable, they will plant switchgrass in the next simulation round.

HOW TO USE IT

(how to use the model, including a description of each of the items in the Interface tab)

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

;;;Copyright 2013 by Najet BICHRAOUI. All rights reserved.
;;;No part of this model may be reproduced or transmitted in any form or
;;;by any means, electronic, photocopying, recording, or otherwise, without
;;;prior written permission of the author.

CODE

;;;;; SWITCHGRASS ADOPTION MODEL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; DATE       ;; Ver. ;; By  ;; Comments
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 28-10- 2013;; 001  ;; NB  ;; 



globals        [  
                Price_of_base
                Price_of_SG
                SGPriceMem
                
                MaxSGPrice?
                MeanSGPrice?
                MinSGPrice?
                
                FieldToStorageCost
                StorageToRefineryCost
                FieldToRefineryCost
                
                new_sgprice
                new_basecost
                average_age
                average_education
                
                
                
                SG_root
                Area_planted_global
                PropWithSuccessor
                
                PropComputerUse
                ;  Distance_to_refinery ;; Average distance between farm and fuel refinery ;; 
                
                Co2_Global
                co2_pertonne_km      ; Amount of CO2 equivalents emitted for transporting one tonne of switchgrass one mile
                co2_growth            ; Used to keep a running total of the amount of CO2 equivalents emitted (negative = sequestered) in the entire study area from switchgrass growth
              
                co2_delivery          ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass delivery from farmers to plants
                co2_electric_gen       ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass-based electricity generation
                co2_fuel_gen           ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass-based fuel production/manufacturing
                co2_fuel_burn          ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass-based fuel combustion
                co2_per_liter_burn

                co2_gasoline_TFC   ;per liter
                co2_corn_etoh_TFC  ;per liter
                co2_coal_TFC       ;per MWh
                co2_natgas_TFC     ;per MWh
               
                Lgas_per_Letoh
                fplantegen       ;MWh electricity produced by fuel plants per liter of EtOH produced
               
                market_fuel_supply ;liters of switchgrass EtOH delivered to the market in this itteration
                market_MWh_supply  ;MWH of switchgrass electricity delivered to the market in this itteration
                       
                net_co2_per_liter   ;CO2 emissions from conversion of biomass to fuel in tonnes per liter
                Net_co2_per_tonne
                year_fuel_produced ;sum of total yearly production in liters
                year_fuel_transfo_co2    ;sum of total yearly emissions in tonnes
                
                liters_per_tonne   ;conversion rate in liters of EtOH per tonne of switchgrass
                
                heat_rate         ;thousand Btu per MWh
                MWhper_tonne_coal  ;MWh per tonne coal
                MWh_per_tonne_sg    ;MWh per tonne sg
                tonnes_per_MWh     ;tonnes of sg per MWh
                net_co2_per_MWh     ;CO2 emissions associated with combusting biomass in $ per MWh
                year_MWh_produced  ;Total annual generation in MWh
                year_eplant_co2    ;Total annual CO2 emissions in tonnes
                MWh_per_tonne_coal
                heat_content_coal
                heat_content_sg
                
                TotHarvest              ; Used as a placeholder to quantify the amount of switchgrass harvested
                trade
               
                ] 

                    ;; Main agents (turtle)
breed          [ 
                 Be_Farmers Be_Farmer
                 ]
breed          [ No_Be_Farmers 
                 No_Be_Farmer
                 ]


patches-own    [
                 SG_yield                    ;; yield of SG
                 Base_yield                  ;; yield of whatever they would be planting instead of SG
                 Owned-by                    ;; which farmer owns the field (one patch = one field)
                 Area_to_plant?              ;; for the followraing years;;boolean TRUE or FALSE;; will evolve from year to year  
                 farm_ID]

turtles-own    [
              ;; Economic attributes
              
               ;  farm_color
                 Fixed_cost_peracre          ;; Current FC per acre
                 Total_fixed_cost            ;; Current TFC    
                 Variable_cost_peracre       ;; Current VC per acre
                 Total_variable_cost         ;; Current TVC       
                 Total_cost_peracre          ;; FC per acre + VC per acre
                 Total_cost                  ;; TFC + TVC
                 Sales_price_SG_peracre      ;; slider determined by the user in the GUI
                 Sales_price_Base_peracre
                             
                 Current_revenues            ;; Current revenues based pre-SG based on base_yield
                 Current_profit              ;; Idem; based on current revenues
                 Potential_revenues          ;; of planting SG ;; based on SG price
                 Potential_profit            ;; of planting SG;; based on potential revenues
                 Breakeven?                  ;; TRUE or FALSE;; (Potential prof - Current prof) if TRUE go to next step: generate Interest Score (IS)  
                 
                 SG_harvested               
                 SG_revenues
                 SG_profit
                 
              ;; Personal attributes  
                 age_of_farmer 
                 ageofdeath
                 education
                 computer_use?
                 age_mem
                 successor?
                 
                 risk_aversion
                 farm_successor?
                 Familiarity_with_SG         ;; Index Randomly distributed (Mean 50; SD 30)    
                 
                 highra?
                 medra?
                 lowra?
                 
                 
                 
                 highfa?
                 medfa?     
                 lowfa?
                 
                 highis?
                 medis?
                 lowis?
                 
                 highEd?
                 medEd?
                 lowEd?
                 
                 highPotProf?
                 medPotProf?
                 lowPotProf?
                 
                 highPriceSG?
                 medPriceSG?
                 lowPriceSG?
                 
                 highCost?
                 medCost?
                 lowCost?
           
                 
                 On_the_fence?
                 mindchanged?
                 Interest_score              ;; Score = Familiarity * level_of_financial_risk ;; for the first test year
                 Happy?                     ;; happy if they made a profit selling SG (revenues > 0);; On setup, happy? is FALSE for everybody       
                 
                 Rep?
              ;; Agricultural attributes
                 
                 Number_of_fields_owned      ;; Number of paches owned (just the number)           
                 Farm_root                   ;; Center patch where my farm is located, used to color my land (contiguous patches) with the same shade
                 
           
                 My_farm                     ;; group of paches owned (agentset)
                 Parcels_col                 ;; color of my parcel, used to color the rest of my land with the same color of farm_root
                 Acres_owned                 ;; number_of_field_owned * 10 acres
                 number_of_field_planted
                 
                
                 
                 Plant_SG?                   ;; TRUE or FALSE
                 Initial_Percent_of_planting ;; Random percentage up to 40% of their land
                 My_percent_increase         ;; pseudo random percentage of increase; "proportional to profit made"
                 Percent_of_planting         ;; Increased Initial percent of planting
                 SG_planted_ton
                 SG_harvArea
                 
                 Portion_of_planting         ;; Number of field that will be devoted to SG (just the number)
                 
                 My_SGplant   
                  my_SGparcel
                              ;; Number of paches to be planted (agentset)
                 My_area_planted             ;; Surface SG plantes in acres
                 harv?                       ;; TRUE of FALSE
                 CollRev?                    ;; TRUE of FALSE
                            
                 Memory_planted              ;; Record the number of field planted (list of number)
                 Memory_lot_planted          ;; Record the number of patches planted (list agentset)
                ;;temp variables for troubleshotting; to be deleted when model done!;;
                 BE ;; list
                 Distance_to_refinery 
                 TransCost
                 usingStorage?
                 
                
                   
                Myco2_growth            ; Used to keep a running total of the amount of CO2 equivalents emitted (negative = sequestered) in the entire study area from switchgrass growth         
                Myco2_delivery          ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass delivery from farmers to plants
                Myco2_electric_gen       ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass-based electricity generation
                Myco2_fuel_gen           ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass-based fuel production/manufacturing
                Myco2_fuel_burn          ; Used to keep a running total of the amount of CO2 equivalents emitted in the entire study area from switchgrass-based fuel combustion
               
                Myyear_fuel_transfo_co2
                Myyear_eplant_co2
                
                DistFieldToRefinery 
                DistFieldToStorage
                DistStorageToRefinery
                 ]


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;SETUP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SETUP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SETUP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to setup
  
  ;; (for this model to work with NetLogo's new plotting features,
  ;; __clear-all-and-reset-ticks should be replaced with clear-all at
  ;; the beginning of your setup procedure and reset-ticks at the end
  ;; of the procedure.)
  ;if ticks mod = 3 [go]
  __clear-all-and-reset-ticks
  
;set snapshot-directory user-directory
  setup-patches-and-create-turtles
  set-farmer-attributes
  
  set PropWithSuccessor random-normal 0.4 0.05
  set PropComputerUse random-normal 0.6 0.05
  
  set Price_of_base precision random-normal 350 50 0
  set Price_of_SG precision random-normal 350 100 0
  
  set SGPriceMem []
 
  set Area_planted_global sum [My_area_planted] of turtles
 
  set Co2_Global sum [Co2_total_from_SG] of turtles
 
  set co2_pertonne_km   0.00017623926144      ; (0.00010951 miles)= (0.0094 gal diesel/tonne mile) * (25,630 lbs TFC CO2 emissions/ 1000 gal) * (1 tonne / 2200 lbs)
  set co2_fuel_burn     0.001507        ;tonnes CO2 per liter ethanol, Ethanol = (789 g EtOH/L) / (46.07 g EtOH / mol EtOH) * (2 mol CO2 / mol EtOH) * (44 g CO2 / mol CO2) * (1 tonne / 1,000,000 g)
  set co2_gasoline_TFC  0.00297          ;tonnes CO2 per liter http://solar.gwu.edu/index_files/Resources_files/LCA_for_PHEVs.pdf
  set co2_corn_etoh_TFC 0.003            ;tonnes CO2 per liter Source
  set co2_coal_TFC      1.05             ;tonnes CO2 per MWh (Meta-analysis of TFC emissions) Benjamin K. Sovacool. Valuing the greenhouse gas emissions from nuclear power: A critical survey. Energy Policy, Vol. 36, 2008, p. 2950.
  set co2_natgas_TFC    0.443            ;tonnes CO2 per MWh (Meta-analysis of TFC emissions) Benjamin K. Sovacool. Valuing the greenhouse gas emissions from nuclear power: A critical survey. Energy Policy, Vol. 36, 2008, p. 2950.
;  set co2delivery (co2delivery + (trade * co2pertonnemile * disttoe)) ;using the distance to the electric plant, calculate the transportation CO2 emissions and add them to the running total for co2delivery
  set Lgas_per_Letoh    1.4678             ;Heat content conversion rate (One gallon of gasoline has 1.4678 x the energy content of one liter of EtOH)
  set fplantegen        0.00007407         ;GREET in MWh per L EtOH ; (0.26 kWH/gal EtOH) * (1 gal EtOH / 3.78 L EtOH) * (1 MWh / 1000 kWh)

  set heat_content_sg   20935             ;MJ/tonne
  set heat_content_coal 20000 ;;btu per lb
  set liters_per_tonne floor random-normal 320 20                   ;sets the yield of fuel (in liters) that can be produced per tonne of switchgrass input (normal distribution)
 
  set heat_rate random-normal 11.6 1  ;MJ/kWh (1.0551 * kbtu/kWh) -- Sets the heatrate of the plant   
 
  set MWh_per_tonne_coal (heat_content_coal * 2.326) / (1000 * heat_rate)   ;1 btu/lb = 2.326 MJ/tonne -- Calculates the MWh produced from one tonne of coal
  set MWh_per_tonne_sg (heat_content_sg / (1000 * heat_rate))                 ;Calculates the MWh produced from one tnne of switchgrass
  set tonnes_per_MWh (1 / MWH_per_tonne_sg) 
 
  set net_co2_per_MWh   0.946                   ;tonnes CO2e per MWH = (946 g/kWh) * (1000 kWh / 1 MWh) * (1 tonne / 1,000,000 g)
  set Net_co2_per_tonne -1.097                                  ;Source: GREET (tonnes of CO2 emitted [negative value = sequestered] per tonne of switchgrass during growth phase only). Note this value is slightly highraer than 1 due to extra carbon sequestration in the soil.
 
  set FieldToStorageCost 1.22 ; dollars per tonne ;;http://www.extension.iastate.edu/agdm/crops/pdf/a1-22.pdf
  set StorageToRefineryCost 0.2883 ;dollars per tonne;;;http://www.extension.iastate.edu/agdm/crops/pdf/a1-22.pdf
  
  set FieldToRefineryCost 0.14 ;dollars per tonne ;;;http://www.sciencedirect.com/science/article/pii/S0960852410018006
export-data
;export-dataShort
end


to setup-patches-and-create-turtles
  
   set-default-shape turtles "farm"
   create-turtles initial-number-of-farmers 
   [
   setxy random-pxcor random-pycor
    if any? other turtles-here [ move-to one-of patches with [ not any? turtles-here ] ]
    set color brown 
    set size 1
    set label who set label-color black
       
    set pcolor 43 + random 5
    set farm_root patch-here
    set parcels_col [pcolor] of farm_root  
   set average_age random-normal 55 5
   set ageofdeath random-normal 75 5
   set average_education 1  ;;post high-school
   set successor? FALSE
   
 ;   set Distance_to_refinery random-normal 60 40
    
   set DistFieldToRefinery random-normal 60 20
   set DistFieldToStorage random-normal 20 10
   set DistStorageToRefinery random-normal 50 20
   ; set mindchanged? FALSE
   ;set computer_use? FALSE
   
                                  
   ; set average_age 35 
  
    set age_mem []
    set memory_planted [] 
    set memory_lot_planted []
    
   ;set Plant_SG? FALSE
   ; set harv? FALSE                      
   ; set CollRev? FALSE
   ; set Rep? FALSE
   ]

  ask patches
    [
     set owned-by min-one-of turtles [distance myself]    
     set SG_yield 2.5 ;; ton per acre
     set base_yield random-normal 2 0.5
     set area_to_plant? FALSE
    ]                    
    ;; turtle owns patches it's nearest to

end   

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;GO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to go
  
 farmer-decision-start-point
 ask turtles  [ifelse learn? = TRUE [learn_from_neighbors] []
   ]

;if Price_shock? [shock_price]
ask turtles [if commodity_shock? [commodity_shock]]

   update-attributes
   update_patches
   defineeffect
   update_effect
update_global
;CountPlantbySGprice
;ask turtles [if Transp_Scenarios [Transportation_Scenarios]]
;exportview
;ask patches [recolor]   

 ; export-files
  ;export-filesShort
;if ticks mod 10 = 0 [export-view (word "View-on-tick-" ticks ".png")]

;export-view (word "View-on-tick-" ticks ".eps")
; if record-movie?
;  [update-movie]
  tick
  if ticks = 50 [stop]

end           


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;PROCEDURES;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;PROCEDURES;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;PROCEDURES;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; setting farmers attributes

to set-farmer-attributes
  
  ask turtles
   [
     set age_of_farmer precision (random-normal average_age 10) 0
     ; set average_education 1  ;;post high-school
     set education random-normal average_education 3
     
  ; ask n-of (PropComputerUse * count turtles ) turtles [ set computer_use? TRUE ]  

  set risk_aversion (age_of_farmer + random-normal 0.9 0.3) / 100
        (if (age_of_farmer < average_age) [set risk_aversion risk_aversion - 0.1])
        
  ;  if (computer_use? = TRUE) [    
        set familiarity_with_SG (age_of_farmer + random-normal 4 2 + 2) / 10
        ;]
        (if (age_of_farmer < average_age) [set familiarity_with_SG familiarity_with_SG + 2])
        
   ask n-of (PropWithSuccessor * count turtles ) turtles [ set successor? TRUE ]   
    
 
    
    set number_of_fields_owned count patches with [ owned-by = myself ]
    set my_farm patches with [ owned-by = myself]
    ask my_farm [set pcolor [parcels_col] of myself]
    set acres_owned number_of_fields_owned * 10 ;; 6 acres per patch
    
    set variable_cost_peracre random-normal 250 100 ;;V
    set Total_variable_cost variable_cost_peracre * acres_owned 
    
    set fixed_cost_peracre  random-normal 100 50 ;;;F;; per acre
    set total_fixed_cost  fixed_cost_peracre * acres_owned
    
    set Total_cost_peracre precision (fixed_cost_peracre + variable_cost_peracre) 0
    
    set Total_cost precision (total_fixed_cost + Total_variable_cost) 0
    
      ;SG;;;;
    set Sales_price_SG_peracre  price_of_SG;;S;; formula BEunit= F/(S-V);; $ BEdollars=BEunit*S 
    set Potential_revenues SG_yield * acres_owned * price_of_SG
    set Potential_profit Potential_revenues - Total_cost
    
   ;;Base;;;
    set Sales_price_Base_peracre  price_of_base;;S;; formula BEunit= F/(S-V);; $ BEdollars=BEunit*S 
    set current_revenues base_yield * acres_owned * price_of_base  
    set Current_profit current_revenues - Total_cost
    
  ;;be;;  
    set BE Potential_profit - Current_profit
    
    set initial_Percent_of_planting random-float 0.4
    set my_percent_increase 1 + random-float .3  
    
  ; set Distance_to_refinery random-normal 60 40
    

]
  
  
end

to farmer-decision-start-point
ask turtles
 [ 
  ifelse Potential_profit >= Current_Profit
      [ 
        set Breed Be_farmers  set color 135; set size 1
        calculate_interest_score
        ]
      [
        set Breed No_be_farmers ;set size 2
      ]
   ]
  
end

to calculate_interest_score
  set interest_score (Familiarity_with_SG * risk_aversion) 
     ifelse interest_score > mean [Interest_score] of be_farmers 
           [
             set Plant_SG? TRUE 
            Plant_SG ;set size 3
             ]
            []
            
end

to Plant_SG

 ifelse Plant_SG? = TRUE 
    [ 
  set portion_of_planting precision (number_of_fields_owned * percent_of_planting) 0
  
     set My_SGplant n-of portion_of_planting my_farm ;; number of patches
     ask My_SGplant 
        [ 
       set area_to_plant? TRUE 
       recolor ]
     set number_of_field_planted count my_SGplant  with [ area_to_plant? = TRUE ];;
     set My_area_planted number_of_field_planted * 10 ;; surface planted
      set SG_planted_ton My_area_planted * SG_yield ;; ton planted
     ; recolor
     set harv? TRUE
     harvest_SG
    
     ]  
    []

end 



to harvest_SG
 
  set co2_growth 0                              ;clear previous year's growth from short-term memory variabl
  set co2_growth co2_growth + (SG_planted_ton  * Net_co2_per_tonne ) ;adds current farmers sequestration to the running total variable "co2growth" for all farmer
  
  set Myco2_growth SG_planted_ton * Net_co2_per_tonne  ;adds current farmers sequestration to the running total variable "co2growth" for all farmer

  set SG_harvArea My_area_planted * random-normal 0.8 0.1 ;; surface acres harvested with rate loss
  set SG_harvested SG_harvArea * SG_yield ;; ton harvested with rate of loss

  set collRev? TRUE
  set area_to_plant? FALSE
  
  set TotHarvest sum [SG_planted_ton] of be_farmers    ;calculates that year's total switchgrass harvest
    
  recolor
        Collect_revenues
       ; transport
        Transp_Scen

end


to transport 
  set co2_delivery 0
 ;  set co2delivery (co2delivery + (trade * co2pertonnemile * disttoe)) ;using the distance to the electric plant, calculate the transportation CO2 emissions and add them to the running total for co2delivery

  set co2_delivery ( co2_delivery + (trade * co2_pertonne_km * Distance_to_refinery)) ;using the distance to the fuel plant, calculate the transportation CO2 emissions and add them to the running total for co2delivery 
 set Myco2_delivery SG_harvested  * co2_pertonne_km * Distance_to_refinery
  calculate_SGEnerg_production_use  
end 


to Transp_Scen  
 set co2_delivery 0
 
 if Transp_Scenarios = "FieldtoRefinery"
 [
  set co2_delivery co2_delivery + (SG_harvested  * co2_pertonne_km * DistFieldToRefinery)   
  set TransCost FieldToRefineryCost * SG_harvested * DistFieldToRefinery
  
  set Myco2_delivery SG_harvested  * co2_pertonne_km * DistFieldToRefinery 
  
  set usingStorage? false
  ]
  
  if Transp_Scenarios = "FieldtoStorageandRefinery"
  [
   set co2_delivery co2_delivery + (SG_harvested  * co2_pertonne_km * (DistFieldToStorage + DistStorageToRefinery))
   set TransCost (FieldToStorageCost + StorageToRefineryCost) * SG_harvested * Distance_to_refinery
   
   set Myco2_delivery SG_harvested  * co2_pertonne_km * DistFieldToStorage + DistStorageToRefinery
   
   set usingStorage? true
   ]
 set Myco2_delivery SG_harvested  * co2_pertonne_km * (DistFieldToStorage + DistStorageToRefinery)
 calculate_SGEnerg_production_use 
end 


to Collect_revenues
  set SG_revenues SG_harvested * price_of_SG ;; in dollars
  set SG_profit precision (SG_revenues - (Total_cost_peracre * My_area_planted)) 0
  set Rep? TRUE
  ask be_farmers with [Rep? = TRUE] [replant?]
end

to replant?
  ifelse SG_profit > 0 
        [set happy? TRUE]
        [set happy? FALSE]
end

to learn_from_neighbors

  ask be_farmers with [Plant_SG? != true]
  
      [ 
        set On_the_fence? TRUE
        if count be_farmers in-radius influence_radius with [happy? = TRUE] > count be_farmers in-radius influence_radius with [happy? = FALSE]
        [
            Plant_SG; set size 2; print who print "I have changed to" print breed
            set mindchanged? TRUE
           
        ]
      ]
     
end

to recolor
  ifelse area_to_plant? = TRUE 
        [set pcolor 53 + random 5]
       [set pcolor 43 + random 6]
end



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;  script for producing fuel and electricity from the delivered switchgrass  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to calculate_SGEnerg_production_use                                                    ;
   
  set co2_fuel_gen 0                                              ;clear the previous year's running total of co2 from fuel generation from memeory
  set market_fuel_supply 0                                        ;clear the previous year's running total of fuel supplied to the market from memory
  set co2_electric_gen 0                                          ;clear the previous year's running totatl of co2 from electricity generation from memory
  set market_MWh_supply 0                                         ;clear the previous year's running total of electricity supplied to the market from memory
  
  set year_fuel_produced  (Total_Harvested_ton *  liters_per_tonne)       ;calculate the liters of fuel that will be produced this year based on the amount of switchgrass on hand
  set market_fuel_supply (market_fuel_supply + year_fuel_produced)  ;add that plant's annual output to the running total for the entire fuel market
  set year_fuel_transfo_co2 (net_co2_per_liter *  year_fuel_produced)       ;calcuate the co2 produced for that particular plant during fuel production
  set co2_fuel_gen (co2_fuel_gen + year_fuel_transfo_co2)                 ;add that plant's co2 emissions to the running total for all fuel plants
                            
  set year_MWh_produced (Total_Harvested_ton / tonnes_per_MWh )          ;calculate the MWh that will be produced this year based on the amout of switchgrass on hand
  set market_MWh_supply (market_MWh_supply + year_MWh_produced)     ;add that particular plant's electricty generation to the running total for the entire electric market
  set year_eplant_co2 (net_co2_per_MWh * year_MWh_produced)          ;calculate the co2 produced from that particular plant while generating electricity from switchgrass
  set co2_electric_gen (co2_electric_gen + year_eplant_co2)         ;add that plant's co2 emissions to the running total for all electric plants
  
  set co2_fuel_burn (market_fuel_supply * co2_per_liter_burn) ;calculate the emissions from fuel combustion based on the amount of fuel produced from fuel plants. Note this assumes that all fuel produced in a year is burned in that same year.

;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;  

 set Myyear_fuel_transfo_co2 (net_co2_per_liter *  year_fuel_produced)       ;calcuate the co2 produced fo 
 set Myco2_fuel_gen Myyear_fuel_transfo_co2                 ;add that plant's co2 emissions to the running total for all fuel plants
 
 set Myyear_eplant_co2 (net_co2_per_MWh * year_MWh_produced)          ;calculate the co2 produced from that particular plant while generating electricity from switchgrass
 set Myco2_electric_gen Myyear_eplant_co2        ;add that plant's co2 emissions to the running total for all electric plants
 
 set Myco2_fuel_burn (year_MWh_produced * co2_per_liter_burn) ;calculate the emissions from fuel combustion based on the amount of fuel produced from fuel plants. Note this assumes that all fuel produced in a year is burned in that same year.

 
;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;;;MY;;   
end

to calculate_ffuel_production_use
   set MWh_per_tonne_coal (heat_content_coal * 2.326) / (1000 * heat_rate) ;1 btu/lb = 2.326 MJ/tonne 
   set MWh_per_tonne_sg (heat_content_sg / (1000 * heat_rate))
   set tonnes_per_MWh (1 /  MWh_per_tonne_sg)  
end



;script to compare the emissions from fuel and electricity produced in that year from switchgrass to an equvalent amount of fuel and elesctricity produced by other means. 
  
  ;;;;;;;;;;;;;;;;;;;; Note: as written, this doesn't calculate the difference in impact associated with switching from conventional fuels to switchgrass. This just compares the co2 associated with equal amounts of energy produced
  ;;;;;;;;;;;;;;;;;;;; from different fuel sources. For example: if the model showed that 1000 liters of fuel were produced and 500 mWh of electricity were produced from switchgrass, this script will calculate the co2 impact from 
  ;;;;;;;;;;;;;;;;;;;; producing conventional fuel (gasoline) with equivalent energy content to that in 1000 liters of switchgrass fuel, and also the co2 associated with producing 500 MWh of electricity from conventional sources (coal, ng, etc).
  ;;;;;;;;;;;;;;;;;;;; To figure out the co2 impact from utilizing switchgrass, the user will need to define a total market demand for fuel and electricity. Then this calculation section can be modified to calculate the emissions when switchgrass
  ;;;;;;;;;;;;;;;;;;;; provides x% of the total fuel demand, and y% of the total electricity demand (with conventional sources providing (100-x)% of the fuel and (100-y)% of the electricity demand).
  
 
to-report Total_Harvested_ton
   report sum [SG_harvested] of turtles
end

to-report Total_HarvArea_acres
   report sum [SG_harvArea] of turtles
end

to-report Total_planted_acres ;;acres
  report sum [My_area_planted] of turtles
end

to-report Total_planted_ton ;;ton
  report sum [SG_planted_ton] of turtles
end

to-report Total_SG_revenues
  report sum [SG_revenues] of turtles
end

to-report Mean_SG_revenues
  report mean [SG_revenues] of turtles
end
  
to-report Mean_age
  report mean [age_of_farmer] of turtles
end

to-report Mean_Interest_score 
  report mean [Interest_score] of turtles
end  
to-report Mean_risk_aversion 
  report mean [risk_aversion] of turtles
end  

to-report Mean_familiarity_with_SG
  report mean [familiarity_with_SG] of turtles
end  

to-report Mean_My_area_planted
  report mean [My_area_planted] of turtles
end  

to-report Co2_total_from_SG
  report co2_growth + co2_delivery + co2_fuel_gen + co2_electric_gen + co2_fuel_burn
end

to-report Co2delivery
  report co2_delivery
end

to-report Co2_from_gas_and_coal
  report (market_MWH_supply * co2_coal_TFC) + (market_fuel_supply * Lgas_per_Letoh * co2_gasoline_TFC)
end

to-report Co2_from_gas_and-natgas
 report (market_MWH_supply * co2_natgas_TFC) + (market_fuel_supply * Lgas_per_Letoh * co2_gasoline_TFC)
end

to-report Price_of_baseBS
 report Price_of_base
end

to-report Price_of_SGBS
 report Price_of_SG
end

to-report Mean_my_percent_increase
  report mean [my_percent_increase] of turtles
end 

to-report Mean_SG_yield
  report mean [SG_yield] of turtles
end 

to-report Mean_percent_of_planting
  report mean [percent_of_planting] of turtles
end 

to-report Mean_base_yield
  report mean [base_yield] of turtles
end 




to-report Mean_DistFieldToRefinery
  report mean [DistFieldToRefinery] of turtles
end 
to-report Mean_DistFieldToStorage
  report mean [DistFieldToStorage] of turtles
end 
to-report Mean_DistFieldToStoragetoRefinery
  report mean [DistFieldToStorage + DistStorageToRefinery] of turtles
end 


to-report TOTDistFieldToRefinery
  report sum [DistFieldToRefinery] of turtles
end 
to-report TOTDistFieldToStorage
  report sum [DistFieldToStorage] of turtles
end 
to-report TOTDistFieldToStoragetoRefinery
  report sum [DistFieldToStorage + DistStorageToRefinery] of turtles
end 



to-report MeanAcOwned
  report mean [acres_owned] of turtles
end 

to-report MeanPotRev
  report mean [Potential_revenues] of turtles
end 

to-report MeanTotCostPerAcre
  report mean [Total_cost_peracre] of turtles
end 

to-report MeanTotCost
  report mean [Total_cost] of turtles
end 

to-report CountRepl
  report count turtles with [Rep? = TRUE]
end 


to-report MeanEducation
  report mean [education] of turtles
end 

to-report CountComputeruse
  report count turtles with [computer_use? = TRUE]
end 


to-report CountSuccessor
  report count turtles with [successor? = TRUE]
end 

to-report MeanPotProfit
  report mean [Potential_profit] of turtles
end 

to-report CountUserStorage
  report count turtles with [usingStorage? = true]
end 

to-report MeanTransCost
  report mean [TransCost] of turtles
end 

to-report totDistance_to_refinery
  report sum [Distance_to_refinery] of turtles
end 

;###################################################################################################
;###################################################################################################

to-report MeanMyco2_growth 
  report mean [Myco2_growth ] of turtles
end 

to-report MeanMyco2_delivery
  report mean [Myco2_delivery] of turtles
end 

to-report MeanMyco2_electric_gen
  report mean [Myco2_electric_gen] of turtles
end 

to-report MeanMyco2_fuel_gen  
  report mean [Myco2_fuel_gen ] of turtles
end 

to-report MeanMyco2_fuel_burn 
  report mean [Myco2_fuel_burn ] of turtles
end 

to-report MeanMyyear_fuel_transfo_co2
  report mean [Myyear_fuel_transfo_co2] of turtles
end 

to-report MeanMyyear_eplant_co2  
  report mean [Myyear_eplant_co2] of turtles
end 
                  


to-report TOTMyco2_delivery
  report sum [Myco2_delivery] of turtles
end 


;###################################################################################################
;###################################################################################################

;
;###################################################################################################
;###################################################################################################
; for beahavior space to add
;###################################################################################################
;###################################################################################################

to-report highra
  report random-normal max [risk_aversion] of turtles 0 
  end 

to-report medra
  report random-normal mean [risk_aversion] of turtles 0 
  end 
to-report lowra
  report random-normal min [risk_aversion] of turtles 0
  end 


to-report highfa
  report random-normal max [familiarity_with_SG] of turtles 0 
  end 

to-report medfa
  report random-normal mean [familiarity_with_SG] of turtles 0 
  end 
to-report lowfa
  report random-normal min [familiarity_with_SG] of turtles 0
  end 

to-report highis
  report random-normal max [interest_score] of turtles 0 
  end 

to-report medis
  report random-normal mean [interest_score] of turtles 0 
  end 
to-report lowis
  report random-normal min [interest_score] of turtles 0
  end 
;###################################################################################################
;###################################################################################################

;###################################################################################################
;###################################################################################################
; for beahavior space to add
;###################################################################################################
;###################################################################################################

;###################################################################################################
;###################################################################################################

;;education

to-report highEd
  report random-normal max [education] of turtles 0 
  end 

to-report medEd
  report random-normal mean [education] of turtles 0 
  end 
to-report lowEd
  report random-normal min [education] of turtles 0
  end 

;###################################################################################################
;###################################################################################################

;; ECONOMIC

to-report highPotProf
  report random-normal max [Potential_profit] of turtles 0 
  end 

to-report medPotProf
  report random-normal mean [Potential_profit] of turtles 0 
  end 
to-report lowPotProf
  report random-normal min [Potential_profit] of turtles 0
  end 
;###########################################################

to-report highPriceSG
  report random-normal max [Price_of_SG] of turtles 0 
  end 

to-report medPriceSG
  report random-normal mean [Price_of_SG] of turtles 0 
  end 
to-report lowPriceSG
  report random-normal min [Price_of_SG] of turtles 0
  end 

;###########################################################


to-report highCost
  report random-normal max [Total_cost] of turtles 0 
  end 

to-report medCost
    report random-normal mean [Total_cost] of turtles 0 
  end 

to-report lowCost
  report random-normal min [Total_cost] of turtles 0
  end 

;###################################################################################################
;###################################################################################################




to CountPlantbySGprice
  
 ask be_farmers
     [   
    ifelse plant_SG? = TRUE [
     if plant_SG? != FALSE [
       
 ifelse (Price_of_SG > mean SGPriceMem) 
    and (Price_of_SG <=  max SGPriceMem)
     [set MaxSGPrice? TRUE] 
     [set MaxSGPrice? FALSE]

 ifelse (Price_of_SG > min SGPriceMem) 
    and (Price_of_SG <=  mean SGPriceMem)
     [set MeanSGPrice? TRUE] 
     [set MeanSGPrice? FALSE]

ifelse (MaxSGPrice?  != TRUE) and (MeanSGPrice? != TRUE) 
   [set MinSGPrice? TRUE] 
   [set MinSGPrice? FALSE]
     
       ]
     ]
   []
  ]

end




 
;###################################################################################################
;###################################################################################################

to defineeffect 
  ask be_farmers
 ;  with [Plant_SG? = TRUE]
    [
    
    ifelse plant_SG? = TRUE [
     if plant_SG? != FALSE [
    
    ifelse (risk_aversion > medra) 
    and (risk_aversion <= highra)
     [set highra? TRUE] 
     [set highra? FALSE]
     
    ifelse (risk_aversion > lowra) 
   and (risk_aversion < medra)
     [set medra? TRUE]
     [set medra? FALSE]
    
     ifelse (highra? != TRUE) and (medra? != TRUE) 
     [set lowra? TRUE]
     [set lowra? FALSE]
;###################################################################################################     
       ifelse (familiarity_with_SG > medfa) 
    and (familiarity_with_SG <= highfa)
     [set highfa? TRUE] 
     [set highfa? FALSE]
     
    ifelse (familiarity_with_SG > lowfa) 
   and (familiarity_with_SG < medfa)
     [set medfa? TRUE]
     [set medfa? FALSE]
    

     ifelse (highfa? != TRUE) and (medfa? != TRUE) 
     [set lowfa? TRUE]
     [set lowfa? FALSE]
     
;###################################################################################################     
    ifelse (Interest_score > medis) 
    and (Interest_score <= highis)
     [set highis? TRUE] 
     [set highis? FALSE]
     
    ifelse (Interest_score > lowis) 
   and (Interest_score < medis)
     [set medis? TRUE]
     [set medis? FALSE]
      
   ifelse (highis? != TRUE) and (medis? != TRUE) 
     [set lowis? TRUE]
     [set lowis? FALSE]
     
;###################################################################################################    
     
   ifelse (education > medEd) 
    and (education <= highEd)
     [set highEd? TRUE] 
     [set highEd? FALSE]
     
    ifelse (education > lowEd) 
   and (education < medEd)
     [set medEd? TRUE]
     [set medEd? FALSE]
      
   ifelse (highEd? != TRUE) and (medEd? != TRUE) 
     [set lowEd? TRUE]
     [set lowEd? FALSE]
;###################################################################################################     
     
      ifelse (Potential_profit > medPotProf) 
    and (Potential_profit <= highPotProf)
     [set highPotProf? TRUE] 
     [set highPotProf? FALSE]
     
    ifelse (Potential_profit > lowPotProf) 
   and (Potential_profit < medPotProf)
     [set medPotProf? TRUE]
     [set medPotProf? FALSE]
      
   ifelse (highPotProf? != TRUE) and (medPotProf? != TRUE) 
     [set lowPotProf? TRUE]
     [set lowPotProf? FALSE]  
     
 ;###################################################################################################    
    ifelse (Price_of_SG > medPriceSG) 
    and (Price_of_SG <= highPriceSG)
     [set highPriceSG? TRUE] 
     [set highPriceSG? FALSE]
     
    ifelse (Price_of_SG > lowPriceSG) 
   and (Price_of_SG < medPriceSG)
     [set medPriceSG? TRUE]
     [set medPriceSG? FALSE]
      
   ifelse (highPriceSG != TRUE) and (medPriceSG? != TRUE) 
     [set lowPriceSG? TRUE]
     [set lowPriceSG? FALSE]  
     
    
;###################################################################################################  
ifelse (Total_cost > medCost) 
    and (Total_cost <= highCost)
     [set highCost? TRUE] 
     [set highCost? FALSE]
     
    ifelse (Total_cost > lowCost) 
   and (Total_cost < medCost)
     [set medCost? TRUE]
     [set medCost? FALSE]
      
   ifelse (highCost? != TRUE) and (medCost? != TRUE) 
     [set lowCost? TRUE]
     [set lowCost? FALSE]   
     
    ]
  ]
    []
; ask be_farmers [
; if (highra? = TRUE) and (Plant_SG? = TRUE)
 ;[set PHighra? TRUE]
 
 
 
  ]
  ;  ]
   
  end 



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; UPDATES ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to update-attributes
  ask turtles
   [
    ;;; the Following goes up with time ;;;;;;;;;;;
    set age_of_farmer precision (age_of_farmer + 1) 0
    set age_mem lput age_of_farmer age_mem

    set memory_planted lput My_SGplant memory_planted ;; agentset
    set memory_lot_planted lput portion_of_planting memory_lot_planted  
    
    ifelse happy? = TRUE
      [
        ifelse SG_profit < mean [SG_profit] of turtles   
          [set my_percent_increase 1 + random-float .5 ;set low? TRUE 
            set Percent_of_planting initial_Percent_of_planting * my_percent_increase]
          [set my_percent_increase 2 + random-float .5; set low? FALSE
            set Percent_of_planting initial_Percent_of_planting * my_percent_increase]
      ]
      [set Percent_of_planting initial_Percent_of_planting]
      
;;;; ;; death at 75 - if have a successor all attributes stay same except age, if no successor, all change

 if ( age_of_farmer > ( ageofdeath * random-normal 1 0.2 ) ) and ( successor? = TRUE ) [ set age_of_farmer 45 ] 
 if ( age_of_farmer > ( ageofdeath * random-normal 1 0.2 ) ) and ( successor? = FALSE ) 
     [ 

        set age_of_farmer precision (random-normal average_age 10) 0
        set risk_aversion (age_of_farmer + random-normal 0.9 0.3) / 100
        (if (age_of_farmer < average_age) [set risk_aversion risk_aversion - 0.1])
        
       ;  if (computer_use? = TRUE) [    
        set familiarity_with_SG (age_of_farmer + random-normal 4 2 + 2) / 10
        ;]
        (if (age_of_farmer < average_age) [set familiarity_with_SG familiarity_with_SG + 2])
        
        set education random-normal average_education 3
        
        ifelse ( random-float 1 + 0.00001 ) > PropWithSuccessor
                [set successor? FALSE ] 
                [set successor? TRUE ] 
        
        set number_of_fields_owned count patches with [ owned-by = myself ]
        set my_farm patches with [ owned-by = myself]
        ask my_farm [set pcolor [parcels_col] of myself]
        set acres_owned number_of_fields_owned * 10 ;; 6 acres per patch
        
        set variable_cost_peracre random-normal 250 100 ;;V
        set Total_variable_cost variable_cost_peracre * acres_owned 
        
        set fixed_cost_peracre  random-normal 100 50 ;;;F;; per acre
        set total_fixed_cost  fixed_cost_peracre * acres_owned
        
        set Total_cost_peracre precision (fixed_cost_peracre + variable_cost_peracre) 0
        
        set Total_cost precision (total_fixed_cost + Total_variable_cost) 0
        
        ;SG;;;;
        set Sales_price_SG_peracre  price_of_SG;;S;; formula BEunit= F/(S-V);; $ BEdollars=BEunit*S 
        set Potential_revenues SG_yield * acres_owned * price_of_SG
        set Potential_profit Potential_revenues - Total_cost
        
        ;;Base;;;
        set Sales_price_Base_peracre  price_of_base;;S;; formula BEunit= F/(S-V);; $ BEdollars=BEunit*S 
        set current_revenues base_yield * acres_owned * price_of_base  
        set Current_profit current_revenues - Total_cost
        
        ;;be;;  
        set BE Potential_profit - Current_profit
        
        set initial_Percent_of_planting random-float 0.4
        set my_percent_increase 1 + random-float .3  
        
       ; set Distance_to_refinery random-normal 60 40
    
  
         ]
   ]
   
end

to update_effect
  ask be_farmers
 ;  with [Plant_SG? = TRUE]
    [
    
    ifelse plant_SG? = TRUE [
     if plant_SG? != FALSE [
    
    ifelse (risk_aversion > medra) 
    and (risk_aversion <= highra)
     [set highra? TRUE] 
     [set highra? FALSE]
     
    ifelse (risk_aversion > lowra) 
   and (risk_aversion < medra)
     [set medra? TRUE]
     [set medra? FALSE]
    
     ifelse (highra? != TRUE) and (medra? != TRUE) 
     [set lowra? TRUE]
     [set lowra? FALSE]
;###################################################################################################     
       ifelse (familiarity_with_SG > medfa) 
    and (familiarity_with_SG <= highfa)
     [set highfa? TRUE] 
     [set highfa? FALSE]
     
    ifelse (familiarity_with_SG > lowfa) 
   and (familiarity_with_SG < medfa)
     [set medfa? TRUE]
     [set medfa? FALSE]
    

     ifelse (highfa? != TRUE) and (medfa? != TRUE) 
     [set lowfa? TRUE]
     [set lowfa? FALSE]
     
;###################################################################################################     
    ifelse (Interest_score > medis) 
    and (Interest_score <= highis)
     [set highis? TRUE] 
     [set highis? FALSE]
     
    ifelse (Interest_score > lowis) 
   and (Interest_score < medis)
     [set medis? TRUE]
     [set medis? FALSE]
      
   ifelse (highis? != TRUE) and (medis? != TRUE) 
     [set lowis? TRUE]
     [set lowis? FALSE]
     
;###################################################################################################    
     
   ifelse (education > medEd) 
    and (education <= highEd)
     [set highEd? TRUE] 
     [set highEd? FALSE]
     
    ifelse (education > lowEd) 
   and (education < medEd)
     [set medEd? TRUE]
     [set medEd? FALSE]
      
   ifelse (highEd? != TRUE) and (medEd? != TRUE) 
     [set lowEd? TRUE]
     [set lowEd? FALSE]
;###################################################################################################     
     
      ifelse (Potential_profit > medPotProf) 
    and (Potential_profit <= highPotProf)
     [set highPotProf? TRUE] 
     [set highPotProf? FALSE]
     
    ifelse (Potential_profit > lowPotProf) 
   and (Potential_profit < medPotProf)
     [set medPotProf? TRUE]
     [set medPotProf? FALSE]
      
   ifelse (highPotProf? != TRUE) and (medPotProf? != TRUE) 
     [set lowPotProf? TRUE]
     [set lowPotProf? FALSE]  
     
 ;###################################################################################################    
    ifelse (Price_of_SG > medPriceSG) 
    and (Price_of_SG <= highPriceSG)
     [set highPriceSG? TRUE] 
     [set highPriceSG? FALSE]
     
    ifelse (Price_of_SG > lowPriceSG) 
   and (Price_of_SG < medPriceSG)
     [set medPriceSG? TRUE]
     [set medPriceSG? FALSE]
      
   ifelse (highPriceSG != TRUE) and (medPriceSG? != TRUE) 
     [set lowPriceSG? TRUE]
     [set lowPriceSG? FALSE]  
     
    
;###################################################################################################  
ifelse (Total_cost > medCost) 
    and (Total_cost <= highCost)
     [set highCost? TRUE] 
     [set highCost? FALSE]
     
    ifelse (Total_cost > lowCost) 
   and (Total_cost < medCost)
     [set medCost? TRUE]
     [set medCost? FALSE]
      
   ifelse (highCost? != TRUE) and (medCost? != TRUE) 
     [set lowCost? TRUE]
     [set lowCost? FALSE]   
     
     
     ;;;;;;;;;;;;;;;;
 
     
    ]
  ]
    []
; ask be_farmers [
; if (highra? = TRUE) and (Plant_SG? = TRUE)
 ;[set PHighra? TRUE]
 
 
 
  ]
  ;  ]
end
  
to update_patches
 ask patches 
    [  
   set SG_yield 2.5 ;; ton per acre
   set base_yield random-normal 2 0.5
   set area_to_plant? FALSE
    ]
end

to update_global
 set Price_of_SG precision random-normal 350 100 0
 set SGPriceMem lput Price_of_SG SGPriceMem
 
 

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;SHOCKS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
to shock_price
  if ticks = Price_shock_at_step
   [
 ; Set Price_of_SG Price_of_SG  *  (1.2 + random-float 0.6)
  Set Price_of_SG Price_of_SG  * (0.2 + random-float 2)
  set new_sgprice Price_of_SG
  ]
end

to commodity_shock
  if ticks = Price_shock_at_step [
  Set Total_cost_peracre Total_cost_peracre  * (0.2 + random-float 2)
  set new_basecost Total_cost_peracre
]
end


;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;                                         Turtles log for individual analysis with output file  
to exportview

if file-exists? "TESTcombineIMAGES.eps"
     [ file-delete "TESTcombineIMAGES.eps"]
file-open "TESTcombineIMAGES.eps"
;if ticks mod 10 = 0 (
;file-write 
;(task [export-view (word "View-on-tick-" ticks ".png")])
;)

file-close 
  end

to export-data
     ;; If the file already exists, we begin by deleting it, otherwise
    ;; new data would be appended to the old contents.
  if file-exists? "AgentResult.csv"
      [ file-delete "AgentResult.csv"]
   if ticks = 1 [create-files] 

end

to create-files
;; create the file and give the first row column headings
let spacer ","
file-open "AgentResult.csv"
file-print  (list 
  "BSRunNum" spacer
  "ticks" spacer 
  "Who" spacer 
  "Breed" spacer         
  "TotalCostPeracre" spacer   
  "TotalCost" spacer  
  "SalesPriceSGPeracre" spacer
  "SalesPriceBasePperacre"  spacer
  "CurrentRevenues" spacer
  "CurrentProfit" spacer
  "PotentialRevenues" spacer       
  "PotentialProfit"  spacer                
  "SGHarvested" spacer              
  "SGRevenues" spacer
  "SGProfit" spacer
  "ageOfFarmer" spacer
  "riskAversion" spacer
  "FamiliarityWithSG"  spacer     
  "highra" spacer
  "medra" spacer
  "lowra" spacer
  "highfa" spacer
  "medfa" spacer
  "lowfa" spacer
  "highis" spacer
  "medis" spacer
  "lowis" spacer
  "OnTheFence" spacer
  "mindchanged" spacer
  "InterestScore" spacer          
  "Happy" spacer                        
  "Rep" spacer
  "NumberOfFieldsOwned" spacer                                
  "AcresOwned" spacer              
  "NumbeOfFieldPlanted" spacer
  "PlantSG" spacer
  "InitialPercentOfPlanting" spacer
  "MyPercentIncrease" spacer      
  "PercentOfPlanting" spacer        
  "SGHarvArea" spacer
  "MyAreaPlanted" spacer
  "InfRadius" spacer
  "ComShock"  spacer
  "learn"     spacer
   "Priceshock" spacer
   "education" spacer
   "computer_use" spacer
   "successor"                      
        


 )
;file-newline 
 
file-close
export-files
end

to export-files
;; write the information to the file
let spacer ","
file-open "AgentResult.csv"
ask turtles [file-print
  
 (list 
   behaviorspace-run-number spacer
  ticks spacer 
 who spacer 
 breed spacer                 
  Total_cost_peracre spacer   
  Total_cost spacer  
  Sales_price_SG_peracre spacer
  Sales_price_Base_peracre  spacer
  Current_revenues spacer
  Current_profit spacer
  Potential_revenues spacer       
  Potential_profit  spacer           
  SG_harvested spacer              
  SG_revenues spacer
  SG_profit spacer
  age_of_farmer spacer
  risk_aversion spacer
  Familiarity_with_SG  spacer     
  highra? spacer
  medra? spacer
  lowra? spacer
  highfa? spacer
  medfa? spacer
  lowfa? spacer
  highis? spacer
  medis? spacer
  lowis? spacer
  On_the_fence? spacer
  mindchanged? spacer
  Interest_score spacer          
  Happy? spacer                        
  Rep? spacer
  Number_of_fields_owned spacer                                  
  Acres_owned spacer              
  number_of_field_planted spacer
  Plant_SG? spacer
  Initial_Percent_of_planting spacer
  My_percent_increase spacer      
  Percent_of_planting spacer        
  SG_harvArea spacer
  My_area_planted spacer
  influence_radius spacer
  commodity_shock? spacer
  learn? spacer
  Price_shock? spacer
  education spacer
  computer_use? spacer
  successor?                                 
                 

)
   
   
   ] 
file-close
end 



;;;;==============================================================================================;;;
;;;;========================================= SHORT =====================================================;;;
;;;;==============================================================================================;;;
;                                         Turtles log for individual analysis with output file  


to export-dataShort
     ;; If the file already exists, we begin by deleting it, otherwise
    ;; new data would be appended to the old contents.
  ;if file-exists? "IndiAna7.csv"
    ;  [ file-delete "IndiAna7.csv"]
    if ticks = 1 [create-filesShort] 

end

to create-filesShort
;; create the file and give the first row column headings
let spacer ","
file-open "Indi.2runsSHORT.csv"
file-print  (list 
  "BSRunNum" spacer
  "ticks" spacer 
  "Who" spacer 
  "Breed" spacer         
  "TotalCostPeracre" spacer   
  
  "SalesPriceSGPeracre" spacer
  "SalesPriceBasePperacre"  spacer
  
 
  "PotentialRevenues" spacer       
                
  "SGHarvested" spacer              
  "SGRevenues" spacer
  
  "ageOfFarmer" spacer
  "riskAversion" spacer
  "FamiliarityWithSG"  spacer     
  
  "OnTheFence" spacer
  "mindchanged" spacer
  "InterestScore" spacer          
  "Happy" spacer                        
  "Rep" spacer
                                
               
  
  "PlantSG" spacer
  "InitialPercentOfPlanting" spacer
  "MyPercentIncrease" spacer      
  "PercentOfPlanting" spacer        
  
  "MyAreaPlanted" spacer
  "InfRadius" spacer
  "ComShock"  spacer
  "learn"     spacer
   "Priceshock" spacer
   "education" spacer
   "computer_use" spacer
   "successor"                      
        


 )
;file-newline 
 
file-close
export-filesShort
end

to export-filesShort
;; write the information to the file
let spacer ","
file-open "Indi.2runsSHORT.csv"
ask turtles [file-print
  
 (list 
   behaviorspace-run-number spacer
  ticks spacer 
 who spacer 
 breed spacer                 
  Total_cost_peracre spacer   
  
  Sales_price_SG_peracre spacer
  Sales_price_Base_peracre  spacer
 
  Potential_revenues spacer       
          
  SG_harvested spacer              
  SG_revenues spacer
 
  age_of_farmer spacer
  risk_aversion spacer
  Familiarity_with_SG  spacer     
  
  On_the_fence? spacer
  mindchanged? spacer
  Interest_score spacer          
  Happy? spacer                        
  Rep? spacer
            
  
  Plant_SG? spacer
  Initial_Percent_of_planting spacer
  My_percent_increase spacer      
  Percent_of_planting spacer        
 
  My_area_planted spacer
  influence_radius spacer
  commodity_shock? spacer
  learn? spacer
  Price_shock? spacer
  education spacer
  computer_use? spacer
  successor?                                 
                 

)
   
   
   ] 
file-close
end 


;; makes a movie of the model; stops when there are 3000 turtles
;; and exports movie to a file
to make-movie

  ;; prompt user for movie location
  user-message "First, save your new movie file (choose a name ending with .mov)"
  let path user-new-file
  if not is-string? path [ stop ]  ;; stop if user canceled

  ;; run the model
  setup
  movie-start path
  movie-grab-view
  while [ count turtles < 3000 ]
    [ go
      movie-grab-view ]

  ;; export the movie
  movie-close
  user-message (word "Exported movie to " path)
end





to update-movie
  ifelse movie-status = "No movie."
  [let filename (word "insert-file-name-here.mov")
    movie-start filename]
  [ifelse capture-node = "entire interface"
    [movie-grab-interface]
    [movie-grab-view]]
end