Straw for ethanol production - impact of market dynamics

Straw for ethanol production - impact of market dynamics preview image

1 collaborator

Default-person Henrik Sontag (Author)

Tags

(This model has yet to be categorized with any tags)
Visible to everyone | Changeable by the author
Model was written in NetLogo 6.2.2 • Viewed 79 times • Downloaded 7 times • Run 0 times
Download the 'Straw for ethanol production - impact of market dynamics' 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

;-----------------------------------------------------------------------------------;
extensions [ ]

; Agents and/or objects in the model
breed [ farmers farmer  ]
breed [ localUsers localUser ]
breed [ EtOHPlantOperators EtOHPlantOperator ]

;Links in the model

;undirected-link-breed
undirected-link-breed [ contracts contract ]
undirected-link-breed [ relationships relationship ]

;directed-link-breed [ ]
directed-link-breed [ requests request ]
directed-link-breed [ offers offer ]

; Specifying global variables in the model
globals
[
  ;;model region setup
  scale                              ;; 1 pixellength = 5 km  ; 20x20 pixel = 100x100km area = 10 000 km2
  aggregationFactor                  ;; factor by which farmers are grouped together

  shareArableFarms
  shareMixedFarms
  shareMixedLivestockFarms
  shareGrazingLivestockFarms

  shareFarms5to10ha
  shareFarms10to20ha
  shareFarms20to50ha
  shareFarms50to100ha
  shareFarms100to200ha
  shareFarms200ha+

  shareLandUseFarms5to10ha
  shareLandUseFarms10to20ha
  shareLandUseFarms20to50ha
  shareLandUseFarms50to100ha
  shareLandUseFarms100to200ha
  shareLandUseFarms200ha+

  shareLandUseArableFarms
  shareLandUseMixedFarms
  shareLandUseMixedLivestockFarms
  shareLandUseGrazingLivestockFarms

  ;; straw harvest
  globalWheatYield
  grainStrawRatio

  ;; regulations, policies
  humusBalanceCrossCompliance

  ;; humus coefficients for supply and demand
  humusDemandWheat                             ;; [t humus-C/ ha] ,  -0.28 t humus-C/ha
  reproductionCoefficientStraw                 ;; [t humus-C/t] = 0.1 t humus-C/t of straw
  reproductionCoefficientLiquidManurePig       ;; [t humus-C/t of substrat] , most conservative value, assuming lowest % values dm content


  ;technical parameters
  heatValueEtOH

  ;; market prices
  priceLiquidManureCattle

  ;compostMarketPrice                ;; not included yet
  ;nitrogenPrice                      ;; not included yet... same for following
  ;phosphorPrice
  ;potassiumPrice
  ;sulfurPrice
  ;magnesiumPrice
  ;humusPrice                          ;; calculation method?? (LWK Niedersachsen: 0,04 €/kg 2015)

]

; Specifying agents properties
farmers-own
[
  marketAgentType               ;; "seller" "no seller" or "buyer"

  ;; farmer attributes
  ;farmerType                   ;; risk averse / profit oriented
  ;businessMotivation           ;; (1) profit/market driven, (2) Sustainable farming
  yieldAlert                    ;; true/false depending on deviation of yield from other
  turnover                      ;; [€/a]
  profit                        ;; [€/a]
  moneyBalance                  ;; [€]
  strawMates                    ;; customers in neighborhood farmer trust




  ;; farm attributes
  farmType                      ;; (1) arable farm (2) mixed farm (livestock and arable farming)
  acreageWheat                  ;; [ha] , land use for cereal production
  farmSystem                    ;; conventional / integrated / biodynamic
  livestock                     ;; true / false



  ;; farming attributes
  cropRotation                  ;; determines overall humus balance
  humusSoilBalance              ;; [kg humus C/ha]
  estimatedhumusSoilBalance      ;; [kg humus C/ha]
  humusDemandPerHa
  soilQuality                   ;; [0...100] , qualitative value to illustrate negative impact from negative humus balance on soils
  strawHarvestFactor            ;; Weiser et al. 2014
  strawHumusValue
  humusBalanceMinimum
  liquidManureUse



  ;; farmer estimations straw potentials and straw use
  wheatYieldExpectation
  estimatedStrawYield           ;; [t] estimated straw yield for upcoming season
  estimatedStrawPotential
  estimatedNonHarvestableStraw
  estimatedStrawForLivestock
  estimatedStrawForSoil
  strawSold                 ;;

  ;; actual straw potentials and straw uses
  actualWheatYield                             ;; [t/ha] , Model region showed wheat yields between 7 and 9 t/ha over the last 15 years (www.regionalstatistik.de)
  actualStrawYield                             ;; [t] actual straw yield at harvest
  theoreticalStrawPotential                    ;; [t] theoretical straw potential (omniscient perspective)
  actualStrawPotential                         ;; [t] actual straw potential available at harvest
  actualNonHarvestableStraw
  technicalStrawPotential                      ;; [t] technical straw potential (theoretical straw potential (omniscient perspective) - assumptions on technical limitations in harvest)
  strawForSoil
  strawForLivestock

  ;; review need


  ;; live straw account farmer
  strawAccount                        ;; [t] live account of straw availability of farmer


  ;;straw trade variables
  potentialStrawForSale               ;; [t] straw estimated by farmer to be available for potential sale
  strawAvailabilityBidding            ;; [t]

  biddingStatus                       ;; "out of stock" , "no matches at current asking price", ...
  numberRequestsEtOH                  ;; [unit]
  numberRequestsLocalUsers            ;; [unit]
  averageTransportDistanceRoundBales
  mySellingPriceRoundBales
  mySellingPriceOffField
  mySellingQuantityRoundBales
  mySellingQuantityOffField


  ;; straw prices
  markup                              ;; [€/t]
  askingPriceStrawOffField            ;; [€/t]
  reservePriceStrawOffField           ;; [€/t]
  askingPriceRoundBales5km            ;; [€/t]
  reservePriceRoundBales5km           ;; [€/t]
  askingPriceRoundBales               ;; [€/t]
  reservePriceRoundBales              ;; [€/t]





  ;;straw costs
  costsPressingRoundBales            ;; [€/t], 14,4 - 17,7 €/t (100% - 50% capacity utilisation) LWK NS
  costsPressingSquaredBales          ;; [€/t], 17,0 - 22,1 €/t (100% - 50% capacity utilisation) LWK NS
  costsPressingHDBales               ;; [€/t], 27,2 - 31,7 €/t (100% - 50% capacity utilisation) LWK NS
  costsHandlingRoundBales            ;; [€/t], 10,8 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
  costsHandlingSquaredBales          ;; [€/t], 10,2 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
  costsHandlingHDBales               ;; [€/t], 17,3 - 21,7 €/t (100% - 50% capacity utilisation) LWK NS
  costsTransportFixedRoundBales      ;; [€/t], 10,3 - 12,4 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
  costsTransportFixedSquaredBales    ;; [€/t], 8,0 - 10,0 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
  costsTransportFixedHDBales         ;; [€/t], 7,5 - 9,2 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
  costsTransportVariableRoundBales   ;; [€/tkm], 0,36 - 0,48 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
  costsTransportVariableSquaredBales ;; [€/tkm], 0,29 - 0,38 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
  costsTransportVariableHDBales      ;; [€/tkm], 0,50 - 0,68 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
]

localUsers-own
[
  ;; agent attributes
  marketAgentType               ;; "seller" or "buyer"
  moneyBalance                  ;; [€]
  feedstockDemand               ;; [t]
  sourcingRadius                ;; [km]
  farmerMates                   ;; farmers within 5 km with established trade relationships

  ;; bidding variables
  reservePrice                  ;; [€/t]
  averageStrawBuyingPrice
  storedFeedstockBidding
  requiredFeedstockBidding
  biddingStatus                 ;; bidding status of local users?
]

EtOHPlantOperators-own
[
  ;; agent attributes
  marketAgentType              ;; "seller" or "buyer"
  moneyBalance                 ;; [€]
  profit                       ;; [€/year]
  feedstockDemand              ;; [t/year]
  sourcingRadius               ;; [km]

  ;production variables
  capacity                     ;; [MW]
  efficiency
  operatingHours               ;; [hours]
  yieldEtOH                    ;; [t,EtOH/t,straw]
  productionCostsEtOH          ;; [€/tonne EtOH]
  markup                       ;; [€/t]

  ;; bidding variables
  expectingSalesPriceEtOH                  ;; [€/tonne EtOH]
  reservePrice                             ;; [€/t], maximum acceptable price per ton of straw
  priceOffer                               ;; [€/t], starting price offer in yearly straw procurement process
  priceOfferBidding                        ;; [€/t], price offer during straw procurement process
  averageStrawBuyingPrice
  averageStrawProcurementCosts
  storedFeedstockBidding                   ;; [t]
  requiredFeedstockBidding                 ;; [t]
  biddingStatus

    ;;straw procurement costs
  costsTransportFixedSquaredBales          ;; [€/t], 8,0 - 10,0 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
  costsTransportVariableSquaredBales       ;; [€/tkm], 0,29 - 0,38 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
  costsPressingSquaredBales            ;; [€/t], 17,0 - 22,1 €/t (100% - 50% capacity utilisation) LWK NS
  costsHandlingSquaredBales            ;; [€/t], 10,2 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
  costsTransportFixedSquaredBales      ;; [€/t], 8,0 - 10,0 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
  costsTransportVariableSquaredBales   ;; [€/tkm], 0,29 - 0,38 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS


]


; Specifying links properties

requests-own
[
  demandType                 ;; "off field" / "round bales" / "squared bales" / "HD bales"
  priceTon                   ;; [€/t]
  priceTotal                 ;; [€]
  quantity                   ;; [t]
]

offers-own
[
  demandType                  ;; "loose/ off field" / "round bales" / "squared bales" / "HD bales"
  priceTon                   ;; [€/t]
  priceTotal                 ;; [€]
  quantity                   ;; [t]
]

contracts-own
[
  demandType                  ;; "off field" / "round bales" / "squared bales" / "HD bales"
  contractNumber             ;; [number]
  quantity                   ;; [t]
  priceTotal                 ;; [€]
  priceTon                   ;; [€/t]
  transportCostsPerTon       ;; [€/t]
  totalCostsBuyer            ;; [€]
  contractLength             ;; [years]
]

relationships-own
[
  trust
]

; Including functions (reports) and procedures to use in the script
__includes
[
  ;setup
  ;;"setup-globals.nls"
  ;"setup-farmers.nls"
  ;"setup-local-users.nls"
  ;"setup-etoh-plant.nls"
  ;"setup-patches.nls"
  ;"setup-local-relationships.nls"

  ;go

  ;updates / new year
  ;"new-year.nls"
  ;"humus-soil-balance.nls"
  ;"update-market-prices.nls"
  ;"farmers-net-humus-balance-from-land-use.nls"

  ;buyer preparations
  ;"checking-contracts.nls"
  ;"update-feedstock-demand.nls"
  ;"update-procurement-variables.nls"

  ;farmer preparations
  ;"estimating-straw-yield.nls"
  ;"estimating-straw-potential.nls"
  ;"farmer-humus-calculation.nls"
  ;"determining-humus-supply.nls"

  ;negotiations/straw trade
  ;"straw-procurement.nls"


  ;harvest, transport
  ;"harvest.nls"

  ;season evaluation
  ;"etoh-profit-calculation.nls"
  ;"market-reactions-of-agents.nls"
  ;"season-reactions.nls"

]

to setup

  clear-all

  ; Create world

  ;setup-globals

  set scale 5                                          ;; 1 pixellength = 5 km  ; 20x20 pixel = 100x100km area = 10 000 km2 (why 10 000 km2, if model region equals to approx 4700 km?...scale = 3.5 adds up to area of 4900 km2...)
  set aggregationFactor 10

  ;;; constants ;;;

  ; wheat properties
  set grainStrawRatio 0.8                              ;; (Weiser et al., 2014)
  set humusDemandWheat 0.28                            ;; [t humus-C / ha]

  ; humus production coefficients
  set reproductionCoefficientStraw 0.1                 ;; [t humus C/t] (Weiser et al., 2014)
  set reproductionCoefficientLiquidManurePig 0.004     ;; [t humus-C/t of substrat] , most conservative value, assuming lowest % values dm content

    ;technical parameters
  set heatValueEtOH 7.42                               ;; [MWh/t]

  ;;; world ;;;

  ; market variables
  set strawNutrientValue 11.4                          ;; [€/t] ]composed of N, P, K, Mg, S
  set bioethanolMarketPrice 820                        ;; [€/t]  .... 31 €/GJ or 650 €/m^3 or 822 €/t ... assumption from Zech et al. (2016)
  ;set priceOfferEtOH strawNutrientValue + strawHumusValueConventional
  ;set priceLiquidManurePig -5
  set priceLiquidManureCattle -5

  ;; rules and regulations
  set humusBalanceCrossCompliance -0.075               ;; [t humus-C/ha]



  ; Create agents

  ;;setup-farmers
    ;; based on distribution of farm types in model region in 2007 and latest total number of farms
  ;; acreage equals average area per farm type based on share of land per farm type category of total land

  ;;setup model region
  setup-model-region-parameters

  ;; create farmer agents
  create-farmers ceiling (numberOfFarms / aggregationFactor)
  [
    setxy random-xcor random-ycor
    set shape "house"
    set size 0.3
  ]

  ;; assigning farm types in model region
  ask farmers
  [
    set farmType farm-type-distribution
  ]

  ;; assigning farm systems run by farmers in model region
  ask farmers
  [
    set farmSystem size-independent-farm-system-attribution
  ]

  ;; farming parameters
  ask farmers
  [
    set acreageWheat acreage-per-farm-size farmType
    set acreageWheat precision acreageWheat 0
    set cropRotation one-of [1 ];2 3 4 5 6 ]; 7 8]     Assuming all farmers have same crop rotation of beet root, wheat, barley and residues of beet root and barley is incorporated into soil
    set wheatYieldExpectation 8
    set strawHarvestFactor 0.66                          ;; Weiser et al. 2014
    set soilQuality 1
    set yieldAlert false
    if farmSystem = "integrated"
    [
      set humusBalanceMinimum 0.1
    ]
    if farmSystem = "biodynamic"
    [
      set humusBalanceMinimum 0.5
    ]
    ifelse farmType = "mixed farm"
    [
      set liveStock true
    ]
    [
      set liveStock false
    ]
    ;; straw production cost variables
    ;; pressing and handling
    set costsPressingRoundBales            17.7 ;; [€/t], 14,4 - 17,7 €/t (100% - 50% capacity utilisation) LWK NS
    set costsPressingSquaredBales          22.1 ;; [€/t], 17,0 - 22,1 €/t (100% - 50% capacity utilisation) LWK NS
    set costsPressingHDBales               31.7 ;; [€/t], 27,2 - 31,7 €/t (100% - 50% capacity utilisation) LWK NS
    set costsHandlingRoundBales            12.3 ;; [€/t], 10,8 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
    set costsHandlingSquaredBales          12.3 ;; [€/t], 10,2 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
    set costsHandlingHDBales               21.7 ;; [€/t], 17,3 - 21,7 €/t (100% - 50% capacity utilisation) LWK NS

    ;; transport costs
    set costsTransportFixedRoundBales      12.4 ;; [€/t], 10,3 - 12,4 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportFixedSquaredBales    10.0 ;; [€/t], 8,0 - 10,0 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportFixedHDBales         9.2  ;; [€/t], 7,5 - 9,2 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportVariableRoundBales   0.48 ;; [€/tkm], 0,36 - 0,48 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportVariableSquaredBales 0.38 ;; [€/tkm], 0,29 - 0,38 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportVariableHDBales      0.68 ;; [€/tkm], 0,50 - 0,68 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS
  ]

  ;; straw prices
  ask farmers
  [
    if farmSystem = "conventional"
    [
      set strawHumusValue strawHumusValueConventional
      let farmer-straw-value strawHumusValue + strawNutrientValue
      set markup 0.5 * farmer-straw-value
      set askingPriceStrawOffField farmer-straw-value + markup + random 5
      set reservePriceStrawOffField farmer-straw-value + 0.5 * markup
      set askingPriceRoundBales5km farmer-straw-value + markup + random 5 + costsPressingRoundBales + costsHandlingRoundBales + costsTransportFixedRoundBales
      set reservePriceRoundBales5km farmer-straw-value + 0.5 * markup + costsPressingRoundBales + costsHandlingRoundBales + costsTransportFixedRoundBales
      set mySellingPriceRoundBales reservePriceRoundBales5km
      set mySellingPriceOffField reservePriceStrawOffField
    ]
    if farmSystem = "integrated"
    [
      set strawHumusValue strawHumusValueIntegrated
      let farmer-straw-value strawHumusValue + strawNutrientValue
      set markup 0.5 * farmer-straw-value
      set askingPriceStrawOffField farmer-straw-value + markup + random 5
      set reservePriceStrawOffField farmer-straw-value + 0.5 * markup
      set askingPriceRoundBales5km farmer-straw-value + markup + random 5 + costsPressingRoundBales + costsHandlingRoundBales + costsTransportFixedRoundBales
      set reservePriceRoundBales5km farmer-straw-value + 0.5 * markup + costsPressingRoundBales + costsHandlingRoundBales + costsTransportFixedRoundBales
      set mySellingPriceRoundBales reservePriceRoundBales5km
      set mySellingPriceOffField reservePriceStrawOffField
    ]
    if farmSystem = "biodynamic"
    [
      set strawHumusValue strawHumusValueBiodynamic
      let farmer-straw-value strawHumusValue + strawNutrientValue
      set markup 0.5 * farmer-straw-value
      set askingPriceStrawOffField farmer-straw-value + markup + random 5
      set reservePriceStrawOffField farmer-straw-value + 0.5 * markup
      set askingPriceRoundBales5km farmer-straw-value + markup + random 5 + costsPressingRoundBales + costsHandlingRoundBales + costsTransportFixedRoundBales
      set reservePriceRoundBales5km farmer-straw-value + 0.5 * markup + costsPressingRoundBales + costsHandlingRoundBales + costsTransportFixedRoundBales
      set mySellingPriceRoundBales reservePriceRoundBales5km
      set mySellingPriceOffField reservePriceStrawOffField
    ]
  ]



  ;; setup-local-users


    create-localUsers numberTraditionalAgents
  [
    setxy random-xcor random-ycor
    set shape "person"
    set size 0.5
    set color 95
    set marketAgentType "buyer"
    set farmerMates nobody
    set feedstockDemand totalDemandTraditionalUsers / numberTraditionalAgents
    set requiredFeedstockBidding feedstockDemand
    set sourcingRadius ( 15 / scale)                                  ;; assumption sourcing radius of 15 km
    ;set priceOffer 40 + random 20                                    ;; Own assumption
    set reservePrice 150                                              ;; Own assumption
  ]


  ; Create links

  ;;setup-local-relationships

    ask farmers with [farmType = "arable farm" or farmType = "mixed farm"]
  [
    create-relationships-with localUsers in-radius (5 / scale)        ;; 5 km radius
    [
      set color blue
      set trust random 3
    ]

    set strawMates [other-end] of my-relationships               ;; lists of straw mates
  ]

  ask localUsers
  [
    if any? my-relationships
    [
      set farmerMates [other-end] of my-relationships            ;; lists of farmer mates
    ]
  ]

  ; Create patches
    ask patches
  [
    set pcolor white
  ]

  reset-ticks
end 

;;;;;;; setup sub-procedures ;;;;;;;;;;;

to-report farm-type-distribution

  ;; only arable or mixed farms are considered

  let output ""

  let a random-float (shareArableFarms + shareMixedFarms)

  ifelse a <= shareArableFarms
  [
    set output "arable farm"
  ]
  [
    set output "mixed farm"
  ]

  report output
end 

to-report acreage-per-farm-size [farm-type]

  let land-use-farms 0
  let number-of-farms 0

  if farm-type = "arable farm"
  [
    set land-use-farms landUseWheat * (shareLandUseArableFarms / (shareLandUseArableFarms + shareLandUseMixedFarms))
    set number-of-farms count farmers with [farmType = "arable farm"]
  ]
  if farm-type = "mixed farm"
  [
    set land-use-farms landUseWheat * (shareLandUseMixedFarms / (shareLandUseArableFarms + shareLandUseMixedFarms))
    set number-of-farms count farmers with [farmType = "mixed farm"]
  ]

  let average-land-per-farm-agent 0

  ;; number farms per size category
  let farms-5to10 round number-of-farms * shareFarms5to10ha
  let farms-10to20 round number-of-farms * shareFarms10to20ha
  let farms-20to50 round number-of-farms * shareFarms20to50ha
  let farms-50to100 round number-of-farms * shareFarms50to100ha
  let farms-100to200 round number-of-farms * shareFarms100to200ha
  let farms-200+ round number-of-farms * shareFarms200ha+

  ;; average land per size category
  let land-5to10 land-use-farms * shareLandUseFarms5to10ha
  let land-10to20 land-use-farms * shareLandUseFarms10to20ha
  let land-20to50 land-use-farms * shareLandUseFarms20to50ha
  let land-50to100 land-use-farms * shareLandUseFarms50to100ha
  let land-100to200 land-use-farms * shareLandUseFarms100to200ha
  let land-200+ land-use-farms * shareLandUseFarms200ha+

  let a random-float (0.17 + 0.22 + 0.27 + 0.21 + 0.07 + 0.01)         ;; values = shareFarms... parameters

  ifelse a <= 0.17
  [
    set average-land-per-farm-agent (land-5to10 / farms-5to10 )
  ]
  [
    ifelse a > 0.17 and a <= (0.17 + 0.22)
    [
      set average-land-per-farm-agent (land-10to20 / farms-10to20 )
    ]
    [
      ifelse a > (0.17 + 0.22) and a <= (0.17 + 0.22 + 0.27)
      [
        set average-land-per-farm-agent (land-20to50 / farms-20to50 )
      ]
      [
        ifelse a > (0.17 + 0.22 + 0.27)  and a <= (0.17 + 0.22 + 0.27 + 0.21)
        [
          set average-land-per-farm-agent (land-50to100 / farms-50to100 )
        ]
        [
          ifelse a > (0.17 + 0.22 + 0.27 + 0.21)  and a <= (0.17 + 0.22 + 0.27 + 0.21 + 0.07)
          [
            set average-land-per-farm-agent (land-100to200 / farms-100to200 )
          ]
          [
            if a <= (0.17 + 0.22 + 0.27 + 0.21 + 0.07 + 0.01)
            [

              set average-land-per-farm-agent (land-200+ / farms-200+ )
            ]
          ]
        ]
      ]
    ]
  ]

  report average-land-per-farm-agent
end 

to setup-model-region-parameters

;  set numberOfFarms 5455
;  set landUseWheat 50000

  ;; 2007 regional data collection
  set shareArableFarms 27
  set shareMixedFarms 20
  set shareMixedLivestockFarms 6
  set shareGrazingLivestockFarms 35

  ;; 2007 regional data colelction, share of total arable land
  set shareLandUseArableFarms 0.29
  set shareLandUseMixedFarms 0.26
  set shareLandUseMixedLivestockFarms 0.07
  set shareLandUseGrazingLivestockFarms 0.26

  ;; 2010 regional data collection
  set shareFarms5to10ha 0.17
  set shareFarms10to20ha 0.22
  set shareFarms20to50ha 0.27
  set shareFarms50to100ha 0.21
  set shareFarms100to200ha 0.07
  set shareFarms200ha+ 0.01

  set shareLandUseFarms5to10ha 0.03
  set shareLandUseFarms10to20ha 0.08
  set shareLandUseFarms20to50ha 0.21
  set shareLandUseFarms50to100ha 0.34
  set shareLandUseFarms100to200ha 0.23
  set shareLandUseFarms200ha+ 0.11
end 

to-report size-independent-farm-system-attribution

  let farm-system ""

  let a random-float 1

  ifelse a <= (shareMulchFarmers / 100)
  [
    set farm-system "biodynamic"
    set color green
  ]
  [
    ifelse a > (shareMulchFarmers / 100) and a <= ((shareMulchFarmers / 100) + (shareIntegratedFarmers / 100))
    [
      set farm-system "integrated"
      set color orange
    ]
    [
      set farm-system "conventional"
      set color brown
    ]
  ]

  report farm-system
end 


;;;;;;;;;;;; ONE YEAR ;;;;;;;;;;;

to go-once

  If ticks = 15 [stop]                             ;;  ( 1 tick = 1 year)

  tick

  ;updates / new year

  ;new-year-procedure
    ask farmers
  [
    set turnover 0
    set profit 0
    set numberRequestsEtOH 0
    set numberRequestsLocalUsers 0
    set liquidManureUse 0
    set estimatedStrawForSoil 0
    set strawSold 0
    set strawForSoil 0
    set strawForLivestock 0
  ]


  ;update-market-prices-procedure
  if ticks > yearEtOHEntry
  [
    if EtOHMarketPriceScenario = "stable"
    [
      set bioethanolMarketPrice bioethanolMarketPrice    ;; [€/t]  .... 31 €/GJ or 650 €/m^3 or 822 €/t ... assumption from Zech et al. (2016)
    ]
    if EtOHMarketPriceScenario = "increasing"
    [
      set bioethanolMarketPrice bioethanolMarketPrice * 1.02
    ]
    if EtOHMarketPriceScenario = "decreasing"
    [
      set bioethanolMArketPrice bioethanolMarketPrice * 0.98
    ]

    set bioethanolMArketPrice precision bioethanolMArketPrice 0
  ]


  ;farmers-net-humus-balance-from-land-use-procedure
  ask farmers
  [
    ifelse manualHumusBalanceSetting = false
    [
      set humusSoilBalance humusSoilBalance + net-humus-balance-per-ha-and-year-from cropRotation

    ]
    [
      set humusSoilBalance humusBalanceFromCropRotation
    ]
;
;    print "humus soil balance new year"
;    show humusSoilBalance
  ]



    if ticks = yearEtOHEntry                                       ;; energy producers enters the market in year 5 (tick = 5), if scenario is chosen
  [
    if EtOHPlantScenario = true
    [
      create-EtOHPlantOperators EtOHplantsNumber
  [
    setxy random-xcor random-ycor
    set shape "wheel"
    set size 1.5
    set color green
    set marketAgentType "buyer"
    set moneyBalance 0

    ;;production variables
    set capacity capacityEtOHPlant                                                                          ;; [MW]
    set operatingHours 7500                                                                                 ;; [h]
    set efficiency 0.24                                                                                     ;; conversion efficiency (Weiser et al. 2014)
    set yieldEtOH  0.25                                                                                     ;; [t,EtOH/t,straw]   Weiser et al.  yield = 0,135 according to own calculations
    set productionCostsEtOH precision (uniform-distribution-floating 450 550) 0                                           ;; [€/tonne EtOH] ... Estimation based on Inbicon / Zech et al., (2016)
    set markup productionCostsEtOH * 0.3                                                                    ;; [€/t]     markup of 30%
    set feedstockDemand ( capacity * operatingHours * efficiency / heatValueEtOH ) * (1 / yieldEtOH)        ;; [t]  required straw
    set feedstockDemand feedstockDemand * 0.5
    set feedstockDemand precision feedstockDemand 0


    ;; straw procurement costs
    set costsPressingSquaredBales 20                 ;; [€/t], 17,0 - 22,1 €/t (100% - 50% capacity utilisation) LWK NS
    set costsHandlingSquaredBales 11                 ;; [€/t], 10,2 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
    set costsTransportFixedSquaredBales 9            ;; [€/t], 8,0 - 10,0 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportVariableSquaredBales 0.3       ;; [€/tkm], 0,29 - 0,38 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS

    ;; straw procurement variables
    set sourcingRadius (50 / scale)                                                                         ;; [km] (Weiser et al., 2014)
    set priceOffer priceOfferEtOH
    set expectingSalesPriceEtOH bioethanolMarketPrice           ;; operator calculates with market price from last year
    let average-transport-cost-assumption precision (costsTransportFixedSquaredBales + (50 / scale) * costsTransportVariableSquaredBales) 0       ;; assuming transport distance of 50 km
    set reservePrice precision (expectingSalesPriceEtOH - productionCostsEtOH - markup - average-transport-cost-assumption) 0

  ]
    ]
  ]

  ;buyer preparations

  ;checking-contracts procedure
    ask contracts
  [
    ifelse contractLength <= 1
    [
      die
    ]
    [
      set contractLength contractLength - 1
    ]
  ]

  ;update-feedstock-demand procedure
    ask EtOHplantOperators
  [
    let maximum-feedstock-demand ( capacity * operatingHours * efficiency / heatValueEtOH ) * (1 / yieldEtOH)

    set feedstockDemand feedstockDemand * 1.2
    if feedstockDemand >= maximum-feedstock-demand
    [
      set feedstockDemand maximum-feedstock-demand
    ]

    print "EtOH feedstockDemand"
    show feedstockDemand
  ]

  ;update-procurement-variables proceudre
  ask etohplantoperators
  [
    set expectingSalesPriceEtOH bioethanolMarketPrice
    let average-transport-cost-assumption precision (costsTransportFixedSquaredBales + (50 / scale) * costsTransportVariableSquaredBales) 0
    set reservePrice precision (expectingSalesPriceEtOH - productionCostsEtOH - markup - average-transport-cost-assumption) 0
    if reservePrice <= 0
    [
      set reservePrice 0
    ]

    if priceOffer > reservePrice
    [
      set priceOffer reservePrice
    ]
  ]

  ;farmer preparations

  ;estimating-straw-yield procedure
  ask farmers
  [
    set estimatedStrawYield (wheatYieldExpectation * grainStrawRatio)
    set estimatedNonHarvestableStraw  estimatedStrawYield * (1 - strawHarvestFactor)
    set estimatedStrawPotential (estimatedStrawYield - estimatedNonHarvestableStraw) * acreageWheat
  ]


  ;;farmer-humus-calculation
  ask farmers
  [
    set estimatedhumusSoilBalance humusSoilBalance
;    print "estimatedhumusSoilBalance"
;    show estimatedhumusSoilBalance

    set estimatedhumusSoilBalance estimatedhumusSoilBalance + humus-supply-from-straw estimatedNonHarvestableStraw
;    print "estimatedhumusSoilBalance after considering non harvestable straw"
;    show estimatedhumusSoilBalance

    set humusDemandPerHa humus-demand-calculation-per-ha farmSystem estimatedhumusSoilBalance                         ;; [t humus-C / ha]

;    print "farmSystem"
;    show farmSystem
;    print "humusDemandPerHa after humus balance calculation"
;    show humusDemandPerHa
  ]


  ;determining-humus-supply procedure
  ask farmers
[
    if humusDemandPerHa > 0
    ;; if farmer has humus deficit
    ;; farmer determines most cost-beneficial option for humus supply
    [
      let total-humus-demand acreageWheat * humusDemandPerHa
;            print "total humus demand"
;            show total-humus-demand

      ;;;;;;;;;;;;;; MIXED FARMS ;;;;;;;;;;;;;

      if liveStock = true
      ;; options are to use straw
      ;; or use land in humus beneficial way (intertillage, leave as uncultivated land, perennial field forage)
      ;; or use organic material available from livestock
      ;; or purchase other organic material, i.e. compost low in nutrients
      [
        if farmSystem = "conventional" or farmSystem = "integrated"
        [
          ;; conventional farms with high livestock intensity will maximize use of liquid manure and are willing to give up straw (nutrient pressure)

          ;; quantity needed
          let liquid-manure-use-from-pigs-per-ha liquid-manure-for-humus-demand "pig" humusDemandPerHa
          ;; DüngV (max N supply per year = 170 kg N/ha)
          let N-supply-from-pig-liquid-manure-per-ha N-supply-from "pig" liquid-manure-use-from-pigs-per-ha
          ;; if manure supply surpasses 170 kg/ha boundary
          let complementary-straw-need-per-ha-pig-option 0
          let remaining-humus-demand-per-ha-pig-option 0
          if N-supply-from-pig-liquid-manure-per-ha > 170
          [
            set liquid-manure-use-from-pigs-per-ha allowable-liquid-manure-per-ha "pig"
            set remaining-humus-demand-per-ha-pig-option humusDemandPerHa - (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig)
;                    print "remaining-humus-demand-per-ha-pig-option"
;                    show remaining-humus-demand-per-ha-pig-option
            set complementary-straw-need-per-ha-pig-option remaining-humus-demand-per-ha-pig-option / reproductionCoefficientStraw
;                    print "complementary-straw-need-per-ha-pig-option"
;                    show complementary-straw-need-per-ha-pig-option
          ]

          let total-liquid-pig-manure-use liquid-manure-use-from-pigs-per-ha * acreageWheat
          let total-complementary-straw-use-pig-option complementary-straw-need-per-ha-pig-option * acreageWheat
          set estimatedstrawForSoil total-complementary-straw-use-pig-option
;          print "estimatedstrawForSoil after animal manure consideration for mixed farm"
;          show estimatedstrawForSoil

          set liquidManureUse total-liquid-pig-manure-use
;          print "liquidManureUse after animal manure consideration for mixed farm"
;          show liquidManureUse

          let straw-for-soil-per-ha estimatedstrawForSoil / acreageWheat

          set estimatedhumusSoilBalance estimatedhumusSoilBalance + (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig) + humus-supply-from-straw complementary-straw-need-per-ha-pig-option
;          print "estimatedhumusSoilBalance after animal manure consideration for mixed farm"
;          show estimatedhumusSoilBalance
        ]

        if farmSystem = "biodynamic"
        ;; probably use solid manure  from satbles for fields...
        [
          let straw-for-soil-per-ha humusDemandPerHa / reproductionCoefficientStraw
          set estimatedStrawForSoil straw-for-soil-per-ha * acreageWheat

        ]
      ]


      ;;;;;;;;;;;;;;; ARABLE FARMS ;;;;;;;;;;;;;

      if farmType = "arable farm"
      ;; options are to use straw,
      ;; (or use land in humus beneficial way (intertillage, leave as uncultivated land, perennial field forage))
      ;; or purchase organic material, most likely liquiid manure
      [
        ;; OPTION: STRAW
        ;; quantity needed
        let straw-required-straw-option straw-for-humus-demand total-humus-demand
        ;; costs of straw use
        let costs-straw-use straw-opportunity-cost-calculation straw-required-straw-option

        ;; OPTION: PURCHASE LIQUID MANURE PIGS
        ;; quantity needed
        let liquid-manure-use-from-pigs-per-ha liquid-manure-for-humus-demand "pig" humusDemandPerHa
        ;; DüngV (max N supply per year = 170 kg N/ha)
        let N-supply-from-pig-liquid-manure-per-ha N-supply-from "pig" liquid-manure-use-from-pigs-per-ha
        ;; if manure supply surpasses 170 kg/ha boundary
        let complementary-straw-need-per-ha-pig-option 0
        let remaining-humus-demand-per-ha-pig-option 0
        if N-supply-from-pig-liquid-manure-per-ha > 170
        [
          set liquid-manure-use-from-pigs-per-ha allowable-liquid-manure-per-ha "pig"
          set remaining-humus-demand-per-ha-pig-option humusDemandPerHa - (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig)
;                  print "remaining-humus-demand-per-ha-pig-option"
;                  show remaining-humus-demand-per-ha-pig-option
          set complementary-straw-need-per-ha-pig-option (remaining-humus-demand-per-ha-pig-option / reproductionCoefficientStraw)
;                  print "complementary-straw-need-per-ha-pig-option"
;                  show complementary-straw-need-per-ha-pig-option

        ]

        let total-liquid-pig-manure-use liquid-manure-use-from-pigs-per-ha * acreageWheat
        let total-complementary-straw-use-pig-option complementary-straw-need-per-ha-pig-option * acreageWheat

        ;; costs of pig manure use
        let costs-pig-manure-use liquid-manure-cost-calculation "pig" total-liquid-pig-manure-use

        ;        ;; OPTION: PURCHASE LIQUID MANURE CATTLE
        ;        ;; quantity needed
        ;        let liquid-manure-required-cattle liquid-manure-for-humus-demand "cattle" humus-demand
        ;        ;; ?? restrictions on quantity?? (phosphor, nitrate,...)
        ;        ;; costs of cattle manure use
        ;        let costs-cattle-manure-use liquid-manure-cost-calculation "cattle" liquid-manure-required-cattle


        ;; CHOOSING OPTION WITH HIGHEST COST-BENEFIT

        let my-choice min (list costs-straw-use costs-pig-manure-use) ; costs-cattle-manure-use)

        ;; based on humus supply plan determination of potential straw for sale
        if my-choice = costs-straw-use
        [
          set estimatedStrawForSoil straw-required-straw-option
;          print "estimatedStrawForSoil after choosing straw for humus supply by arable farm"
;          show estimatedStrawForSoil

          set estimatedhumusSoilBalance estimatedhumusSoilBalance + humus-supply-from-straw estimatedStrawForSoil
;          print "estimatedhumusSoilBalance after choosing straw as humus supply by arable farm"
;          show estimatedhumusSoilBalance

        ]

        if my-choice = costs-pig-manure-use
        [
          set liquidManureUse total-liquid-pig-manure-use
;          print "liquidManureUse after choosing liquid manure use to substitute straw by arable farmer"
;          show liquidManureUse
          set estimatedStrawForSoil total-complementary-straw-use-pig-option
;          print "estimatedStrawForSoil after choosing liquid manure use to substitute straw by arable farmer"
;          show estimatedStrawForSoil
          let straw-for-soil-per-ha estimatedStrawForSoil / acreageWheat
          ;set profit profit - costs-pig-manure-use
;          print "profit"
;          show profit
          set estimatedhumusSoilBalance estimatedhumusSoilBalance + (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig) + humus-supply-from-straw straw-for-soil-per-ha
;          print "estimatedhumusSoilBalance after choosing liquid manure use to substitute straw by arable farmer"
;          show estimatedhumusSoilBalance
        ]
      ]
    ]
  ]


  ;estimating-straw-potential
  ask farmers
  [
    ;; straw for livestock
    if livestock = TRUE
    [
      ;; farms with livestock

      ;; (This is where I can incorporate if straw price passes threshold that makes it more cost-beneficial to use alternative source!)

      if farmSystem = "conventional"
      [
        ;; assumption 15% straw need for animal husbandry assuming stables are mostly not litter based
        set estimatedStrawForLivestock estimatedStrawPotential * shareStrawForLivestockConventionalFarm
      ]

      if farmSystem = "integrated"
      ;; assuming integrated and biodynamic farms have more straw based stable systems and therefore use more straw for own purposes
      [
        set estimatedStrawForLivestock estimatedStrawPotential * shareStrawForLiveStockIntegratedFarm
      ]

      ;; ecofarms that grow wheat and have livestock are assumed to keep all straw for on farm purposes
      if farmSystem = "biodynamic"
      [
        set estimatedStrawForLivestock estimatedStrawPotential * shareStrawForLiveStockBiodynamicFarm
      ]
    ]

    ;; straw for soil (determined in previous procedure)

    ;; straw for sale

    ifelse farmSystem = "biodynamic"
    [
      set potentialStrawForSale 0
    ]
    [
      ifelse askingPriceRoundBales5km > beddingSubstitutionPrice
      [
        let risk-margin 0.1
        set potentialStrawForSale ((1 - risk-margin) * estimatedStrawPotential) - estimatedStrawForSoil - estimatedStrawForLivestock * 0.2
        if potentialStrawForSale < 0
        [
          set potentialStrawForSale 0
        ]
      ]
      [
        let risk-margin 0.1
        set potentialStrawForSale ((1 - risk-margin) * estimatedStrawPotential) - estimatedStrawForSoil - estimatedStrawForLivestock
        if potentialStrawForSale < 0
        [
          set potentialStrawForSale 0
        ]
      ]
    ]
  ]

  ;negotiations/straw trade
  ;straw-procurement procedure
  ;; local users are price takers
  ;; etoh plant makes price offers

  ;; buyers in the market
  let buyers turtles with [marketAgentType = "buyer" and feedstockDemand > 0]

  ;; buyers feedstock demand
  ask buyers
  [
    let my-list initialisation-bidding-mechanism-buyers feedstockDemand

    set storedFeedstockBidding item 0 my-list
    set requiredFeedstockBidding item 1 my-list
    ;show my-list

    set biddingStatus "feedstock demand"
  ]

  ;; etoh plant starting price offer
  ask etohPlantOperators
  [
    set priceOfferBidding priceOffer
  ]

  ;; straw available to market from farmers

   ;; potential sellers in the market
  let potential-sellers farmers with [potentialStrawForSale > 0]

  ask potential-sellers
  [
    set strawAvailabilityBidding potentialStrawForSale

  ]

  ;;loop
  while
  [
    any? potential-sellers with [ strawAvailabilityBidding > 0 ] and
    any? buyers with [ requiredFeedstockBidding > 0 ] and
    ;not any? etohplantoperators with [priceOfferBidding > reservePrice] and
    any? buyers with [biddingStatus != "switch to alternative" ]
  ]

  [
    ;;;; Buyer requests/offers ;;;;
    reset-timer

    ask localUsers
    [
      if requiredFeedstockBidding > 0 and biddingStatus != "switch to alternative"
      [
        local-users-requests
        farmers
      ]
    ]

    ask etohPlantOperators
    [
      if requiredFeedstockBidding > 0
      [
        etoh-requests
        farmers
        requiredFeedstockBidding
        storedFeedstockBidding
      ]
    ]

    ;;;; Farmer responses ;;;;
    ask farmers
    [
      ;reset-timer
      friend-offers
      response-to-other-offers
      ;show timer
    ]

    ;;;; Buyer responses ;;;;

    ask buyers
    [
      ;reset-timer
      accept/refuse-offers
      ;show timer
    ]

    ;show timer
  ]

  ;; after straw negotiations are finished

;  ask farmers
;  [
;    print "straw account after straw procurement procedure"
;    show strawAccount
;  ]


  ;harvest, transport
  ;harvest
  ;;wheat-yield
  ;; global wheat yield area
  set globalWheatYield random-normal 8.5 0.5              ;; [t/ha] , Model region showed wheat yields between 7 and 9 t/ha over the last 15 years (www.regionalstatistik.de)

  ;; individual wheat yield farmer
  ;; in current model setup, soil quality has direct impact on wheat yield
  ask farmers
  [
    set actualWheatYield globalWheatYield * soilQuality
    set wheatYieldExpectation actualWheatYield
  ]


  ;;straw-yield
    ask farmers
  [
    set theoreticalStrawPotential (acreageWheat * actualWheatYield * grainStrawRatio)
    set actualStrawYield (actualWheatYield * grainStrawRatio)                                         ;; grain straw ratio varies for instance due to weather or different crop types, machinery used...
    set actualStrawPotential actualStrawYield * strawHarvestFactor * acreageWheat
    set actualNonHarvestableStraw actualStrawYield * (1 - strawHarvestFactor)
  ]

  ;;straw-accounting
  ask farmers
  [
    set strawSold sum [quantity] of my-contracts

    set strawAccount strawAccount + actualStrawPotential
;    print "strawAccount after contract fullfillment"
;    show strawAccount
    set strawAccount strawAccount - estimatedStrawForSoil - estimatedStrawForLivestock

    set strawForSoil  estimatedStrawForSoil + actualNonHarvestableStraw

    ifelse askingPriceRoundBales5km > beddingSubstitutionPrice
    [
      ifelse strawAvailabilityBidding > estimatedStrawForLivestock
      [
        set strawForLivestock estimatedStrawForLivestock
      ]
      [
        set strawForLivestock estimatedStrawForLivestock * 0.2 + strawAvailabilityBidding
      ]
    ]
    [
      set strawForLivestock estimatedStrawForLivestock
    ]
  ]

  ;;humus-supply
  ask farmers
  [
    ; humus supply from non harvestable straw
    set humusSoilBalance humusSoilBalance + humus-supply-from-straw actualNonHarvestableStraw

;    print "humus balance after considering actual non harvestable straw"
;    show humusSoilBalance

    ;;humus from dedicated straw
    set humusSoilBalance humusSoilBalance + (estimatedStrawForSoil / acreageWheat) * reproductionCoefficientStraw

;    print "humus balance after considering dedicated straw for soil"
;    show humusSoilBalance

    ;; humus from manure
    set humusSoilBalance humussoilBalance + (liquidManureUse / acreageWheat) * reproductionCoefficientLiquidManurePig

;    print "humusSoilBalance after considering humus from liquid manure"
;    show humusSoilBalance
  ]
  ;season evaluation
  ;humus-soil-balance-procedure
    ask farmers
  [
    ifelse humusSoilBalance < 0
    ; negative humus balance has impact on soil quality, which has impact on yields.
    ;
    [
      set soilQuality soilQuality * soilImpactFactor                 ;; simple model assumption: negative humus balance has direct negative impact on soil quality
    ]
    [
      set soilQuality soilQuality * soilRecoveryFactor                 ;; simple model assumption: positive humus balance has direct positive impact on soil qualtiy
    ]

    if soilQuality >= 1
    [
      set soilQuality 1
    ]
  ]
  ;etoh-profit-calculation proc
    ask ETOHPlantOperators
  [
    ;let actual-operating-hours operatingHours
    ;let actual-efficiency efficiency
    ;let conversion-mwh-t 7.42                    ;;[MWh/t]

    let feedstockAvailability storedFeedstockBidding
    let output feedstockAvailability / yieldEtOH
    let my-turnover output * bioethanolMarketPrice
    set moneyBalance moneyBalance + my-turnover
    set moneyBalance precision moneyBalance 0

    let my-expenses sum [totalCostsBuyer] of my-contracts

    set profit my-turnover - my-expenses
    set profit precision profit 0
    ;print "profit"
    ;show profit

  ]
  ;market-reactions-of-agents proc
    ;;local-user-market-reactions
    ask localUsers
  [
    if any? my-contracts
    [
      set averageStrawBuyingPrice precision (mean [priceTon] of my-contracts) 0
    ]
  ]

  ;;etoh-plant-market-reactions
  ask EtOHPlantOperators
  [
    if any? my-contracts
    [
      set averageStrawBuyingPrice precision (mean [priceTon] of my-contracts) 1
      set averageStrawProcurementCosts precision (mean [(totalCostsBuyer / quantity)] of my-contracts) 1
    ]

    ifelse feedstockDemand - storedFeedstockBidding > 0
    [
      set priceOffer priceOffer * 1.2
      if priceOffer >= reservePrice
      [
        set priceOffer reservePrice
      ]
    ]
    [
      set priceOffer priceOffer * 0.9
    ]

    set priceOffer precision priceOffer 1
  ]

  ;;farmer-market-reactions
  ask farmers
  [
    ifelse any? my-contracts
    [
      ;; inventory selling prices and quantities at tend of year
      if any? my-contracts with [demandType = "round bales"]
      [
        set mySellingPriceRoundBales precision (mean [priceTon] of my-contracts with [demandType = "round bales"]) 1
        set mySellingQuantityRoundBales precision (sum [quantity] of my-contracts with [demandType = "round bales"]) 1
        set averageTransportDistanceRoundBales precision (mean [link-length * 5] of my-contracts with [demandType = "round bales"]) 1
      ]

      if any? my-contracts with [demandType = "off field"]
      [
        set mySellingPriceOffField precision (mean [priceTon] of my-contracts with [demandType = "off field"]) 1
        set mySellingQuantityOffField precision (sum [quantity] of my-contracts with [demandType = "off field"]) 1
      ]

      ifelse strawAvailabilityBidding <= 0
      [
        set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 1.1) 1
        set askingPriceStrawOffField precision (askingPriceStrawOffField * 1.1) 1
      ]
      [
        ifelse strawAvailabilityBidding > 0.5 * potentialStrawForSale
        [
          set askingPriceRoundBales5km askingPriceRoundBales5km * 0.7
          set askingPriceStrawOffField askingPriceStrawOffField * 0.7

          if askingPriceRoundBales5km <= reservePriceRoundBales5km
          [
            set askingPriceRoundBales5km reservePriceRoundBales5km
          ]

          if askingPriceStrawOffField <= reservePriceStrawOffField
          [
            set askingPriceStrawOffField reservePriceStrawOffField
          ]

        ]
        [
          ifelse strawAvailabilityBidding > 0.3 * potentialStrawForSale
          [
            set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 0.8) 1
            set askingPriceStrawOffField precision (askingPriceStrawOffField * 0.8) 1

            if askingPriceRoundBales5km <= reservePriceRoundBales5km
            [
              set askingPriceRoundBales5km reservePriceRoundBales5km
            ]

            if askingPriceStrawOffField <= reservePriceStrawOffField
            [
              set askingPriceStrawOffField reservePriceStrawOffField
            ]
          ]
          [
            if strawAvailabilityBidding > 0.15 * potentialStrawForSale
            [
              set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 0.9) 1
              set askingPriceStrawOffField precision (askingPriceStrawOffField * 0.9) 1
              if askingPriceRoundBales5km <= reservePriceRoundBales5km
              [
                set askingPriceRoundBales5km reservePriceRoundBales5km
              ]

              if askingPriceStrawOffField <= reservePriceStrawOffField
              [
                set askingPriceStrawOffField reservePriceStrawOffField
              ]
            ]
          ]
        ]
      ]
    ]
    [
      set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 0.7) 1
      set askingPriceStrawOffField precision (askingPriceStrawOffField * 0.7) 1
      if askingPriceRoundBales5km <= reservePriceRoundBales5km
      [
        set askingPriceRoundBales5km reservePriceRoundBales5km
      ]

      if askingPriceStrawOffField <= reservePriceStrawOffField
      [
        set askingPriceStrawOffField reservePriceStrawOffField
      ]
    ]
  ]
  ;;season-reactions procedure

  ask farmers
  [
    if actualWheatYield < globalWheatYield * 0.85
    [
      set yieldAlert true
    ]

    if actualWheatYield >= globalWheatYield * 0.95 and soilQuality >= 1
    [
      set yieldAlert false
    ]
  ]
end 

;;;;;;;;;;; sub-procedures ;;;;;;;;;;;

to local-users-requests

  [
    potential-sellers
  ]

  ;; potential sellers in area
  let my-potential-sellers potential-sellers in-radius sourcingRadius

  ;; only farmers with whom I do not have a contract with yet
  set my-potential-sellers my-potential-sellers with [ contract-with myself = nobody ]

  ; Make sure there are farmers
  ifelse any? my-potential-sellers
  [
    let my-buyer self

    ask my-potential-sellers
    [
      ; Identify themselves
      let my-seller self

      ask my-buyer
        [
          let request-volume requiredFeedstockBidding                                               ;; [t]

          ; Create link "REQUEST" to my-seller
          create-request-to my-seller
          [
            set demandType "round bales"
            set quantity request-volume
            ;show quantity
          ]
      ]
    ]
  ]

  ; else not any? my-feedstock-producers
  [
    set biddingStatus "No straw suppliers in area"
    set sourcingRadius sourcingRadius + 5 / scale                           ;; buyers increase sourcing radius by 5 km
  ]
end 

to etoh-requests
  [
    potential-sellers                    ; [farmers]
    required-feedstock-bidding           ; [t]
    stored-feedstock-bidding             ; [t]
  ]

  ;; potential sellers in area
  let my-potential-sellers potential-sellers in-radius sourcingRadius

  ;; only farmers with whom I do not have a contract with yet
  set my-potential-sellers my-potential-sellers with [ contract-with myself = nobody ]

  set my-potential-sellers my-potential-sellers with [ strawAvailabilityBidding > 0 ]

  ; Make sure there are farmers
  ifelse any? my-potential-sellers
    [
      let my-buyer self

      ask my-potential-sellers
      [
        ; Identify themselves
        let my-seller self

        ask my-buyer
          [
            ;; determination price --> price offer independent from transport costs or anything. Pre-determined. Has to have adaptation rule from year to year.
            let price-bidding priceOfferBidding

            ; Create link "REQUEST" to my-seller
            create-request-to my-seller
            [
              set demandType "off field"
              set priceTon price-bidding
              set quantity required-feedstock-bidding
            ]
        ]
      ]
  ]

  ; else not any? my-feedstock-producers
  [
    set biddingStatus "No straw suppliers in area"
    set sourcingRadius sourcingRadius + 5 / scale                           ;; buyers increase sourcing radius by 5 km
  ]
end 

to friend-offers

  ;; offers to straw mates if requests from friends in network and straw availability
  let my-straw-mates localUsers with [relationship-with myself != nobody ]

  if any? my-straw-mates
  [
    set my-straw-mates localUsers with [relationship-with myself != nobody ]

    let my-friend-requests my-in-requests with [member? other-end my-straw-mates]
    set numberRequestsLocalUsers numberRequestsLocalUsers + count my-friend-requests

    if any? my-friend-requests
    [
      if strawAvailabilityBidding > 0
      [
        let straw-for-friends strawAvailabilityBidding

        while
        [
          any? my-friend-requests and
          straw-for-friends > 0
        ]

        [
          let my-friend-buyers my-straw-mates with [request-with myself != nobody]
          ;print "my-friend-buyers"
          ;show my-friend-buyers

          let my-buyer-relationships my-relationships with [member? other-end my-friend-buyers]
          ;print "my-buyer-relationships"
          ;show my-buyer-relationships

          let my-best-buyer-relationship max-one-of my-buyer-relationships [trust]
          let my-best-buyer [other-end] of my-best-buyer-relationship
          let request-best-buyer in-request-from my-best-buyer

          ;print "my-best-buyer"
          ;show [who] of my-best-buyer

          ;print "request-best-buyer"
          ;show request-best-buyer

          ;; determining size of offer
          let volume-offer 0
          let straw-demand-best-buyer [quantity] of request-best-buyer
          let straw-availability straw-for-friends

          ifelse straw-demand-best-buyer > straw-availability
          [
            set volume-offer straw-availability
          ]
          [
            set volume-offer straw-demand-best-buyer
          ]

          let price-ton askingPriceRoundBales5km

          create-offer-to my-best-buyer
          [
            set demandType [demandType] of request-best-buyer
            set quantity volume-offer
            set priceTon price-ton
            set priceTotal quantity * priceTon
          ]

          let my-offer out-offer-to my-best-buyer
          ;print "my-offer"
          ;show my-offer

          set straw-for-friends straw-for-friends - [quantity] of my-offer

          ask request-best-buyer
          [
            die
          ]
        ]
      ]
    ]
  ]
end 

to response-to-other-offers

  ;reset-timer

  if strawAvailabilityBidding > 0
  [
    if any? my-in-requests
    [
      let my-requests my-in-requests

      ;;;; profit calculation etoh request ;;;;

      let total-profit-from-etoh-request 0

      if any? my-requests with [demandType = "off field"]
      [
        let my-off-field-requests my-in-requests with [demandType = "off field"]               ;; request from etoh plant (=1)
        let my-request max-one-of my-off-field-requests [priceTon]
        let my-etoh-buyer [other-end] of my-request
        ;; calculating profit from etoh request
        let profit-from-etoh-request 0
        let price-offer [priceTon] of my-request             ;; [€/t]

        let my-costs reservePriceStrawOffField                                                 ;; [€/t]

        set profit-from-etoh-request price-offer - my-costs                     ;; [€/t]


        let quantity-etoh-request [quantity] of my-request

        let straw-volume 0

        ifelse quantity-etoh-request >= strawAvailabilityBidding
        [
          set straw-volume strawAvailabilityBidding
        ]
        [
          set straw-volume quantity-etoh-request
        ]

        set straw-volume precision straw-volume 0
        set profit-from-etoh-request precision profit-from-etoh-request 0

;        print "straw-volume"
;        show straw-volume
;
;        print "profit-from-etoh-request"
;        show profit-from-etoh-request

        set total-profit-from-etoh-request straw-volume * profit-from-etoh-request
      ]

      ;;;; expected profit from local user requests

      let expected-total-profit-from-local-requests 0

      if any? my-requests with [demandType = "round bales"]
      [
        let my-round-bales-requests my-requests with [demandType = "round bales"]           ;; requests from all local users

        ;; calculating profit from local user requests
        let expected-profit askingPriceRoundBales5km - reservePriceRoundBales5km       ;; [€/t] , at the moment local users only make requests with straw quantity but not own price offers.

        let total-straw-volume-local-requests sum [quantity] of my-round-bales-requests
        ;print "total-straw-volume-local-requests"
        ;show total-straw-volume-local-requests

        ifelse total-straw-volume-local-requests >= strawAvailabilityBidding ;potentialStrawForSale
        [
          set expected-total-profit-from-local-requests strawAvailabilityBidding * expected-profit  ;potentialStrawForSale
        ]
        [
          set expected-total-profit-from-local-requests total-straw-volume-local-requests * expected-profit
        ]
      ]

      ;;;; selecting distribution channel with highest profit expectations


        ifelse expected-total-profit-from-local-requests >=  total-profit-from-etoh-request
        [
          make-local-user-offers
        ]
        [
          make-etoh-offers
        ]
      ]
    ]


  ;show timer
end 

to make-local-user-offers

  ifelse strawAvailabilityBidding > 0
  [
    if any? my-in-requests with [demandType = "round bales"]
    [

      let my-requests-straw-round-bales my-in-requests with [demandType = "round bales"]
      set numberRequestsLocalUsers numberRequestsLocalUsers +  count my-requests-straw-round-bales

      while
      [
        any? my-requests-straw-round-bales
      ]

      [
        let my-request one-of my-requests-straw-round-bales
        let my-potential-buyer nobody

        let distance-buyer 0

        ask my-request
        [
          set my-potential-buyer other-end
          set distance-buyer link-length
        ]

        set distance-buyer distance-buyer * scale

        let my-price-offer 0

        ifelse distance-buyer > 5
        [
          set my-price-offer askingPriceRoundBales5km + distance-buyer * costsTransportVariableRoundBales
        ]
        [
          set my-price-offer askingPriceRoundBales5km
        ]

        create-offer-to my-potential-buyer
        [
          set demandType "round bales"
          ;; price
          set priceTon my-price-offer                                           ; [€/t]
                                                                                ; determine the quantity of the offer
          ifelse [ quantity ] of my-request > [ strawAvailabilityBidding ] of myself
          [
            set quantity [ strawAvailabilityBidding ] of myself                      ; [t]
          ]
          [
            set quantity [ quantity ] of my-request                              ; [t]
          ]
          ;; price total
          set priceTotal priceTon * quantity                                ; [€]
        ]

        ask my-request
        [
          die
        ]
      ]
    ]
  ]
  [
    ask my-in-requests
    [
      die
    ]
  ]
end 

to make-etoh-offers

  ifelse strawAvailabilityBidding > 0
  [
    if any? my-in-requests with [demandType = "off field"]
    [
      let my-requests-straw-off-field my-in-requests with [demandType = "off field"]
      set numberRequestsEtOH numberRequestsEtOH + count my-requests-straw-off-field

      let off-field-asking-price askingPriceStrawOffField

      if any? my-requests-straw-off-field with [ priceTon >= off-field-asking-price ]
        [
          let my-matching-requests-straw-off-field my-requests-straw-off-field with [ priceTon >= off-field-asking-price ]

          while
          [
            any? my-matching-requests-straw-off-field
          ]

          [
            let my-request one-of my-matching-requests-straw-off-field
            let my-potential-buyer nobody

            ask my-request
            [
              set my-potential-buyer other-end
            ]

            let my-price-offer [priceTon] of my-request

            create-offer-to my-potential-buyer
            [
              set demandType [demandType] of my-request

              ;; price
              set priceTon my-price-offer                                                    ;; [€/t]
                                                                                             ;; determine the quantity of the offer
              ifelse [ quantity ] of my-request > [ strawAvailabilityBidding ] of myself
              [
                set quantity [ strawAvailabilityBidding ] of myself                           ;; [t]
              ]
              [
                set quantity [ quantity ] of my-request                                    ;; [t]
              ]
              ;; price total
              set priceTotal priceTon * quantity                                           ;; [€]
            ]

            ask my-request
            [
              die
            ]
          ]
      ]
    ]
  ]
  [
    ask my-in-requests
    [
      die
    ]
  ]
end 

;to make-offers [straw-availability]
;
;  ifelse any? my-in-requests
;    [
;      ;; if still straw available
;      ifelse strawAvailabilitybidding > 0
;      [
;        let my-seller self
;
;        let my-requests-straw-off-field my-in-requests with [demandType = "off field"]
;        let off-field-asking-price askingPriceStrawOffField
;
;        ;;;;;;;;;;;;;; straw off field ;;;;;;;;;;;;;;;;;
;        ifelse any? my-requests-straw-off-field with [ priceTon >= off-field-asking-price ]
;        [
;          let my-matching-requests-straw-off-field my-requests-straw-off-field with [ priceTon >= off-field-asking-price ]
;
;          ;;loop
;          while
;          [
;            any? my-matching-requests-straw-off-field
;          ]
;
;          [
;            let my-request one-of my-matching-requests-straw-off-field
;            let my-potential-buyer nobody
;
;            ask my-request
;            [
;              set my-potential-buyer other-end
;            ]
;
;            let my-price-offer [priceTon] of my-request
;
;            create-offer-to my-potential-buyer
;            [
;              set demandType [demandType] of my-request
;
;              ;; price
;              set priceTon my-price-offer                                                    ;; [€/t]
;                                                                                             ;; determine the quantity of the offer
;              ifelse [ quantity ] of my-request > [ strawAvailabilityBidding ] of my-seller
;              [
;                set quantity [ strawAvailabilityBidding ] of my-seller                           ;; [t]
;              ]
;              [
;                set quantity [ quantity ] of my-request                                    ;; [t]
;              ]
;              ;; price total
;              set priceTotal priceTon * quantity                                           ;; [€]
;            ]
;
;            ask my-request
;            [
;              die
;            ]
;          ]
;        ]
;        ;; if price offer for straw off field is below asking price
;        [
;          while
;          [
;            any? my-requests-straw-off-field
;          ]
;
;          [
;            let my-request one-of my-requests-straw-off-field
;            let my-potential-buyer nobody
;            let my-price-offer askingPriceStrawOffField
;
;            ask my-request
;            [
;              set my-potential-buyer other-end
;            ]
;
;            create-offer-to my-potential-buyer
;            [
;              set demandType [demandType] of my-request
;              ;; price
;              set priceTon my-price-offer                                           ; [€/t]
;                                                                                    ; determine the quantity of the offer
;              ifelse [ quantity ] of my-request > [ strawAvailabilityBidding ] of my-seller
;              [
;                set quantity [ strawAvailabilityBidding ] of my-seller                       ; [t]
;              ]
;              [
;                set quantity [ quantity ] of my-request                              ; [t]
;              ]
;              ;; price total
;              set priceTotal priceTon * quantity                                ; [€]
;            ]
;
;            ask my-request
;            [
;              die
;            ]
;          ]
;        ]
;
;
;        ;;;;;;;;;;;;;;;;;;; round bales ;;;;;;;;;;;;;;;;;
;
;        let my-requests-straw-round-bales my-in-requests with [demandType = "round bales"]
;
;        while [ any? my-requests-straw-round-bales ]
;
;        [
;          let my-request one-of my-requests-straw-round-bales
;          let my-potential-buyer nobody
;
;          let distance-buyer 0
;
;          ask my-request
;          [
;            set my-potential-buyer other-end
;            set distance-buyer link-length
;          ]
;
;          set distance-buyer distance-buyer * scale
;
;          let my-price-offer 0
;
;          ifelse distance-buyer > 5
;          [
;            set my-price-offer askingPriceRoundBales5km + distance-buyer * costsTransportVariableRoundBales
;          ]
;          [
;            set my-price-offer askingPriceRoundBales5km
;          ]
;
;          create-offer-to my-potential-buyer
;          [
;            set demandType "round bales"
;            ;; price
;            set priceTon my-price-offer                                           ; [€/t]
;                                                                                  ; determine the quantity of the offer
;            ifelse [ quantity ] of my-request > [ strawAvailabilityBidding ] of my-seller
;            [
;              set quantity [ strawAvailabilityBidding ] of my-seller                       ; [t]
;            ]
;            [
;              set quantity [ quantity ] of my-request                              ; [t]
;            ]
;            ;; price total
;            set priceTotal priceTon * quantity                                ; [€]
;          ]
;
;          ask my-request
;          [
;            die
;          ]
;        ]
;      ]
;      [
;        set biddingStatus "out of stock"
;
;        ask my-in-requests
;        [
;          die
;        ]
;      ]
;  ]
;
;  [
;    set biddingStatus "no requests"
;  ]
;
;end

;; request procedures




;; buyer reaction procedure(s)

to accept/refuse-offers

  let my-buyer self

  ifelse requiredFeedstockBidding > 0
  [
    ifelse any? my-in-offers
    [
      ifelse any? my-in-offers with [ priceTon < [reservePrice] of myself]
      [
        ;; select offers that are below reserve price
        let my-acceptable-offers my-in-offers with [ priceTon < [reservePrice] of myself]

        ;;select best offer
        let my-best-offer nobody

        ifelse [breed] of my-buyer = localUsers
        [
          set my-best-offer min-one-of my-acceptable-offers [ priceTon ]
        ]
        [
          set my-best-offer min-one-of my-acceptable-offers [ priceTon + link-length ]
        ]

        ;; identify seller
        let my-seller nobody

        ask my-best-offer
        [
          set my-seller other-end
        ]

        ;; transport cost calculaton
        let transport-costs-fixed 0
        let transport-costs-variable 0

        if [demandType] of my-best-offer = "off field"
        [
          set transport-costs-fixed costsTransportFixedSquaredBales
          set transport-costs-variable costsTransportVariableSquaredBales
        ]

        ;;create contract with my-seller
        ifelse [strawAvailabilityBidding] of my-seller > 0
        [

          let a count my-contracts
          let revenue-seller 0
          let profit-seller 0
          let costs-buyer 0

          create-contract-with my-seller
          [
            set color red
            set demandType [demandType] of my-best-offer

            ifelse [strawAvailabilityBidding] of my-seller >= [ quantity ] of my-best-offer
            [
              set quantity [quantity] of my-best-offer
            ]
            [
              set quantity [strawAvailabilityBidding] of my-seller
            ]
            set priceTon [priceTon] of my-best-offer

            set priceTotal priceTon * quantity

            ifelse [breed] of my-buyer = etohPLantOperators
            [
              set transportCostsPerTon (link-length * scale * ([costsTransportVariableSquaredBales] of my-buyer) + [costsTransportFixedSquaredBales] of my-buyer )
              set totalCostsBuyer priceTotal + (transportCostsPerTon + [costsPressingSquaredBales + costsHandlingSquaredBales] of my-buyer) * quantity
              set contractLength 1
            ]
            [
              set totalCostsBuyer priceTotal
              set contractLength 1
            ]

            set contractNumber a + 1
            set revenue-seller priceTotal
            set costs-buyer totalCostsBuyer
          ]

          let my-contract contract-with my-seller

          ;update buyer feedstock status variables and money balance
          set storedFeedstockBidding storedFeedstockBidding + [quantity] of my-contract
          set requiredFeedstockBidding requiredFeedstockBidding - [quantity] of my-contract
          if storedFeedstockBidding >= feedstockDemand
          [
            set requiredFeedstockBidding 0
            set biddingStatus "feedstock demand met"
          ]

          set moneyBalance moneyBalance - costs-buyer

          ;update seller monetary status and feedstock status
          ask my-seller
          [
            set moneyBalance moneyBalance + revenue-seller
            set turnover turnover + revenue-seller


            let contract-costs-seller 0
            let production-costs-round-bales costsPressingRoundBales + costsHandlingRoundBales + strawHumusValue + strawNutrientValue + costsTransportFixedRoundBales
            let production-costs-off-field strawHumusValue + strawNutrientValue
            if [demandType] of my-contract = "off field"
            [
              set contract-costs-seller ([quantity] of my-contract) *  production-costs-off-field
            ]

            if [demandType] of my-contract = "round bales"
            [
              ifelse [link-length] of my-contract > 5 / scale
              [
                let production-costs costsPressingRoundBales + costsHandlingRoundBales + strawHumusValue + strawNutrientValue + costsTransportFixedRoundBales
                set contract-costs-seller ([quantity] of my-contract) * (production-costs + costsTransportVariableRoundBales * ([link-length] of my-contract - ( 5 / scale)))
              ]
              [
                set contract-costs-seller ([quantity] of my-contract) * (production-costs-round-bales)
              ]
            ]

            set profit-seller revenue-seller - contract-costs-seller

;            print "revenue-seller"
;            show revenue-seller
;            print "contract-costs-seller"
;            show contract-costs-seller

            set profit profit + profit-seller

            set strawAvailabilityBidding strawAvailabilityBidding - [ quantity ] of my-contract
;            set potentialStrawForSale potentialStrawForSale - [quantity] of my-contract
            set strawAccount strawAccount - [ quantity ] of my-contract

            if strawAvailabilityBidding <= 0
            [
              set biddingStatus "out of stock"
            ]
          ]

          ;; Buyer retires all requests (Due to conceptual setup (loops). Agents need to recalculate/update feedstock demand.
          ask my-out-requests
          [
            die
          ]

          ;; Buyer cancels all other in-offers ( (Due to conceptual setup (loops). Agents need to recalculate/update feedstock demand.
          ask my-in-offers
          [
            die
          ]
        ]

        ;; else is farmer has no straw availability anymore
        [
          ask my-best-offer
          [
            die
          ]

          ;; Buyer retires all requests (Due to conceptual setup (loops). Agents need to recalculate/update feedstock demand.
          ask my-out-requests
          [
            die
          ]

          ;; Buyer cancels all other in-offers ( (Due to conceptual setup (loops). Agents need to recalculate/update feedstock demand.
          ask my-in-offers
          [
            die
          ]
        ]
      ]
      ;;; else no offers below reserve price
      [
        ask my-in-offers
        [
          die
        ]

        set biddingStatus "switch to alternative"
        set requiredFeedstockBidding 0
      ]
    ]
    ;else: not any? in offers
    [
      if requiredFeedstockBidding > 0 and biddingStatus != "switch to alternative"
      [
        ask my-out-requests
        [
          die
        ]
        ;;ETOH Plant reaction to not being able to source any straw
        if [breed] of my-buyer = EtOHPlantOperators
        [
          set sourcingRadius sourcingRadius + 5 / scale                   ;; 5 km increase of sourcing radius
          set priceOfferBidding priceOfferBidding * 1.1                    ;; increase of bid offer of 10% if no positive response on requests come back
          if priceOfferBidding >= reservePrice
          [
            set biddingStatus "too high feedstock costs for plant operation"
            set requiredFeedstockBidding 0
            set priceOfferBidding reservePrice
          ]
        ]
        ;; Local user reaction to no straw available below reserve price
        if [breed] of my-buyer = localUsers
        [
          set sourcingRadius sourcingRadius + 5 / scale
        ]
      ]
    ]
  ]

  ;; if buyers feedstock demand not > 0:
  [
    set biddingStatus "feedstock demand met"
    ask my-in-offers
    [
      die
    ]
  ]
end 

to-report initialisation-bidding-mechanism-buyers [ feedstock-demand ]

  let stored-feedstock-bidding 0
  let required-feedstock-bidding feedstock-demand

  report (list stored-feedstock-bidding required-feedstock-bidding)
end 

to-report allowable-liquid-manure-per-ha [ animal-type ]

  let a 0

  if animal-type = "pig"
  [
    let share-dm-content 3
    if share-dm-content = 3
    [
      set a 170 / 4.3
    ]
  ]

  report a
end 

to-report N-supply-from [ animal-type quantity-manure ]

  let a 0

  let share-dm-content 3            ;; %-dm-content

  if animal-type = "pig"
  [
    if share-dm-content = 3
    [
      set a quantity-manure * 4.3         ;;  N supply from pigs (3% dm) in [kg/m^3]
    ]
  ]

  report a
end 

to-report liquid-manure-cost-calculation [ animal-type quantity-manure]

  let a 0

  if animal-type = "pig"
  [
    set a priceLiquidManurePig * quantity-manure
  ]
  if animal-type = "cattle"
  [
    set a priceLiquidManureCattle * quantity-manure
  ]

  report a
end 

to-report liquid-manure-for-humus-demand [ animal-type humus-demand-per-ha ]

  let a 0

  if animal-type = "pig"
  [
    set a humus-demand-per-ha / reproductionCoefficientLiquidManurePig
  ]

  report a
end 

to-report straw-for-humus-demand [humus-demand-per-ha]

  report (humus-demand-per-ha / reproductionCoefficientStraw)
end 

to-report straw-opportunity-cost-calculation [straw-quantity]

  let lost-profit-local-user-sale 0
  let lost-profit-etoh-sale 0

  ifelse (mySellingQuantityRoundBales + mySellingQuantityOffField) >= (0.8 * potentialStrawForSale)
  ;; demand expected for straw in market
  [
    let expected-revenue-local-user-sale straw-quantity * mySellingPriceRoundBales
    let expected-revenue-etoh-sale straw-quantity * mySellingPriceOffField
;    print "expected-revenue-local-user-sale"
;    show expected-revenue-local-user-sale

    let average-transport-costs costsTransportVariableRoundBales * (averageTransportDistanceRoundBales)
;    print "average-transport-costs"
;    show average-transport-costs

    let expected-costs-local-user-sale straw-quantity * (reservePriceRoundBales5km + average-transport-costs)
;    print "expected-costs-local-user-sale"
;    show expected-costs-local-user-sale

    let expected-costs-etoh-sale straw-quantity * reservePriceStrawOffField

    set lost-profit-local-user-sale expected-revenue-local-user-sale - expected-costs-local-user-sale
;    print "lost-profit-local-user-sale"
;    show lost-profit-local-user-sale
    set lost-profit-etoh-sale expected-revenue-etoh-sale - expected-costs-etoh-sale
  ]
  ;; no demand expected for straw in market
  [
    set lost-profit-local-user-sale 0
    set lost-profit-etoh-sale 0
  ]

  report max list lost-profit-local-user-sale lost-profit-etoh-sale
end 

to-report humus-supply-from-straw [straw-volume]

  report straw-volume * reproductionCoefficientStraw
end 

to-report  humus-demand-calculation-per-ha [farm-system humus-soil-balance-value]

  let humus-demand-ha 0

  ifelse farm-system = "conventional"
  [
    ifelse ignoringSoilQuality = TRUE
    [
      set humus-demand-ha 0
    ]

    [
      ifelse farmersComplyToEUCCPolicy = TRUE
      [
        ifelse yieldAlert = TRUE
        [
          ifelse humus-soil-balance-value < 0.1
          [
            set humus-demand-ha (0.1 - humus-soil-balance-value)
          ]
          [
            set humus-demand-ha 0
          ]
        ]
        [
          ifelse humus-soil-balance-value > humusBalanceCrossCompliance
          [
            set humus-demand-ha 0
          ]
          [
            set humus-demand-ha (humus-soil-balance-value - humusBalanceCrossCompliance) * (-1)
          ]
        ]
      ]
      [
        ifelse yieldAlert = TRUE
        [
          ifelse humus-soil-balance-value < 0.1
          [
            set humus-demand-ha (0.1 - humus-soil-balance-value)
          ]
          [
            set humus-demand-ha 0
          ]
        ]
        [
          set humus-demand-ha 0
        ]
      ]
    ]
  ]
  [
    ifelse humus-soil-balance-value > humusBalanceMinimum
    [
      set humus-demand-ha 0
    ]
    [
      set humus-demand-ha (humusBalanceMinimum - humus-soil-balance-value)
    ]
  ]

  report humus-demand-ha
end 

to-report net-humus-balance-per-ha-and-year-from [crop-rotation]

  ;; based on examples presented in article in wochenblatt lippe
  ;; if no further notice all crops are assumed to use 33% of land each)
  let output 0

  if crop-rotation = 1       ;; wheat (50% of total land use) (straw removed), potato (25%), beet root (25%)
  [
    set output -0.422
  ]

  if cropRotation = 2        ;; beet root, wheat (straw removed), barley (straw removed)
  [
    set output -0.31
  ]

  if cropRotation = 3        ;; beet root, wheat (straw removed), barley
  [
    set output -0.123
  ]

  if cropRotation = 4        ;; beet root, wheat (straw removed), barley, catch crop
  [
    set output -0.003
  ]

  if cropRotation = 5        ;; potato, wheat (straw removed), barley, catch crop
  [
    set output -0.133
  ]

  if cropRotation = 6        ;; rapeseed, wheat (straw removed), barley (straw removed)
  [
    set output -0.25
  ]

  if cropRotation = 7          ;; rapseed, wheat (straw removed), barley
  [
    set output 0.162
  ]

  if cropRotation = 8          ;; cc corn, wheat (straw removed), barley
  [
    set output 0.117
  ]

  report output
end 

to-report uniform-distribution-floating [#min #max]

  report #min + random-float(#max - #min)
end 

;;;;;;;;;;; COMPLETE SIMULATION RUN ;;;;;;;;;;;;;

to go

   If ticks = 15 [stop]                             ;;  ( 1 tick = 1 year)

  tick

  ;updates / new year
  ;new-year-procedure
    ask farmers
  [
    set turnover 0
    set profit 0
    set numberRequestsEtOH 0
    set numberRequestsLocalUsers 0
    set liquidManureUse 0
    set estimatedStrawForSoil 0
    set strawSold 0
    set strawForSoil 0
    set strawForLivestock 0
  ]
  ;update-market-prices-procedure
  if ticks > yearEtOHEntry
  [
    if EtOHMarketPriceScenario = "stable"
    [
      set bioethanolMarketPrice bioethanolMarketPrice    ;; [€/t]  .... 31 €/GJ or 650 €/m^3 or 822 €/t ... assumption from Zech et al. (2016)
    ]
    if EtOHMarketPriceScenario = "increasing"
    [
      set bioethanolMarketPrice bioethanolMarketPrice * 1.02
    ]
    if EtOHMarketPriceScenario = "decreasing"
    [
      set bioethanolMArketPrice bioethanolMarketPrice * 0.98
    ]

    set bioethanolMArketPrice precision bioethanolMArketPrice 0
  ]
  ;;farmers-net-humus-balance-from-land-use-procedure
  ask farmers
  [
    ifelse manualHumusBalanceSetting = false
    [
      set humusSoilBalance humusSoilBalance + net-humus-balance-per-ha-and-year-from cropRotation

    ]
    [
      set humusSoilBalance humusBalanceFromCropRotation
    ]
;
;    print "humus soil balance new year"
;    show humusSoilBalance
  ]


  if ticks = 5                                       ;; energy producers enters the market in year 5 (tick = 5), if scenario is chosen
  [
    if EtOHPlantScenario = true
    [
        create-EtOHPlantOperators EtOHplantsNumber
  [
    setxy random-xcor random-ycor
    set shape "wheel"
    set size 1.5
    set color green
    set marketAgentType "buyer"
    set moneyBalance 0

    ;;production variables
    set capacity capacityEtOHPlant                                                                          ;; [MW]
    set operatingHours 7500                                                                                 ;; [h]
    set efficiency 0.24                                                                                     ;; conversion efficiency (Weiser et al. 2014)
    set yieldEtOH  0.25                                                                                     ;; [t,EtOH/t,straw]   Weiser et al.  yield = 0,135 according to own calculations
    set productionCostsEtOH precision (uniform-distribution-floating 450 550) 0                                           ;; [€/tonne EtOH] ... Estimation based on Inbicon / Zech et al., (2016)
    set markup productionCostsEtOH * 0.3                                                                    ;; [€/t]     markup of 30%
    set feedstockDemand ( capacity * operatingHours * efficiency / heatValueEtOH ) * (1 / yieldEtOH)        ;; [t]  required straw
    set feedstockDemand feedstockDemand * 0.5
    set feedstockDemand precision feedstockDemand 0


    ;; straw procurement costs
    set costsPressingSquaredBales 20                 ;; [€/t], 17,0 - 22,1 €/t (100% - 50% capacity utilisation) LWK NS
    set costsHandlingSquaredBales 11                 ;; [€/t], 10,2 - 12,3 €/t (100% - 50% capacity utilisation) LWK NS
    set costsTransportFixedSquaredBales 9            ;; [€/t], 8,0 - 10,0 €/t incl. 5 km (100% - 50% capacity utilisation) LWK NS
    set costsTransportVariableSquaredBales 0.3       ;; [€/tkm], 0,29 - 0,38 , 5 to 10 km (100% - 50% capacity utilisation) LWK NS

    ;; straw procurement variables
    set sourcingRadius (50 / scale)                                                                         ;; [km] (Weiser et al., 2014)
    set priceOffer priceOfferEtOH
    set expectingSalesPriceEtOH bioethanolMarketPrice           ;; operator calculates with market price from last year
    let average-transport-cost-assumption precision (costsTransportFixedSquaredBales + (50 / scale) * costsTransportVariableSquaredBales) 0       ;; assuming transport distance of 50 km
    set reservePrice precision (expectingSalesPriceEtOH - productionCostsEtOH - markup - average-transport-cost-assumption) 0

  ]
    ]
  ]

  ;buyer preparations
  ;checking-contracts procedure
    ask contracts
  [
    ifelse contractLength <= 1
    [
      die
    ]
    [
      set contractLength contractLength - 1
    ]
  ]
  ;update-feedstock-demand-procedure
    ask EtOHplantOperators
  [
    let maximum-feedstock-demand ( capacity * operatingHours * efficiency / heatValueEtOH ) * (1 / yieldEtOH)

    set feedstockDemand feedstockDemand * 1.2
    if feedstockDemand >= maximum-feedstock-demand
    [
      set feedstockDemand maximum-feedstock-demand
    ]

    print "EtOH feedstockDemand"
    show feedstockDemand
  ]
  ; update-procurement-variables procedure

  ask etohplantoperators
  [
    set expectingSalesPriceEtOH bioethanolMarketPrice
    let average-transport-cost-assumption precision (costsTransportFixedSquaredBales + (50 / scale) * costsTransportVariableSquaredBales) 0
    set reservePrice precision (expectingSalesPriceEtOH - productionCostsEtOH - markup - average-transport-cost-assumption) 0
    if reservePrice <= 0
    [
      set reservePrice 0
    ]

    if priceOffer > reservePrice
    [
      set priceOffer reservePrice
    ]
  ]

  ;farmer preparations
  ;estimating-straw-yield

  ask farmers
  [
    set estimatedStrawYield (wheatYieldExpectation * grainStrawRatio)
    set estimatedNonHarvestableStraw  estimatedStrawYield * (1 - strawHarvestFactor)
    set estimatedStrawPotential (estimatedStrawYield - estimatedNonHarvestableStraw) * acreageWheat
  ]
  ;;farmer-humus-calculation
  ask farmers
  [
    set estimatedhumusSoilBalance humusSoilBalance
;    print "estimatedhumusSoilBalance"
;    show estimatedhumusSoilBalance

    set estimatedhumusSoilBalance estimatedhumusSoilBalance + humus-supply-from-straw estimatedNonHarvestableStraw
;    print "estimatedhumusSoilBalance after considering non harvestable straw"
;    show estimatedhumusSoilBalance

    set humusDemandPerHa humus-demand-calculation-per-ha farmSystem estimatedhumusSoilBalance                         ;; [t humus-C / ha]

;    print "farmSystem"
;    show farmSystem
;    print "humusDemandPerHa after humus balance calculation"
;    show humusDemandPerHa
  ]
  ;determining-humus-supply procedure
  ask farmers
[
    if humusDemandPerHa > 0
    ;; if farmer has humus deficit
    ;; farmer determines most cost-beneficial option for humus supply
    [
      let total-humus-demand acreageWheat * humusDemandPerHa
;            print "total humus demand"
;            show total-humus-demand

      ;;;;;;;;;;;;;; MIXED FARMS ;;;;;;;;;;;;;

      if liveStock = true
      ;; options are to use straw
      ;; or use land in humus beneficial way (intertillage, leave as uncultivated land, perennial field forage)
      ;; or use organic material available from livestock
      ;; or purchase other organic material, i.e. compost low in nutrients
      [
        if farmSystem = "conventional" or farmSystem = "integrated"
        [
          ;; conventional farms with high livestock intensity will maximize use of liquid manure and are willing to give up straw (nutrient pressure)

          ;; quantity needed
          let liquid-manure-use-from-pigs-per-ha liquid-manure-for-humus-demand "pig" humusDemandPerHa
          ;; DüngV (max N supply per year = 170 kg N/ha)
          let N-supply-from-pig-liquid-manure-per-ha N-supply-from "pig" liquid-manure-use-from-pigs-per-ha
          ;; if manure supply surpasses 170 kg/ha boundary
          let complementary-straw-need-per-ha-pig-option 0
          let remaining-humus-demand-per-ha-pig-option 0
          if N-supply-from-pig-liquid-manure-per-ha > 170
          [
            set liquid-manure-use-from-pigs-per-ha allowable-liquid-manure-per-ha "pig"
            set remaining-humus-demand-per-ha-pig-option humusDemandPerHa - (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig)
;                    print "remaining-humus-demand-per-ha-pig-option"
;                    show remaining-humus-demand-per-ha-pig-option
            set complementary-straw-need-per-ha-pig-option remaining-humus-demand-per-ha-pig-option / reproductionCoefficientStraw
;                    print "complementary-straw-need-per-ha-pig-option"
;                    show complementary-straw-need-per-ha-pig-option
          ]

          let total-liquid-pig-manure-use liquid-manure-use-from-pigs-per-ha * acreageWheat
          let total-complementary-straw-use-pig-option complementary-straw-need-per-ha-pig-option * acreageWheat
          set estimatedstrawForSoil total-complementary-straw-use-pig-option
;          print "estimatedstrawForSoil after animal manure consideration for mixed farm"
;          show estimatedstrawForSoil

          set liquidManureUse total-liquid-pig-manure-use
;          print "liquidManureUse after animal manure consideration for mixed farm"
;          show liquidManureUse

          let straw-for-soil-per-ha estimatedstrawForSoil / acreageWheat

          set estimatedhumusSoilBalance estimatedhumusSoilBalance + (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig) + humus-supply-from-straw complementary-straw-need-per-ha-pig-option
;          print "estimatedhumusSoilBalance after animal manure consideration for mixed farm"
;          show estimatedhumusSoilBalance
        ]

        if farmSystem = "biodynamic"
        ;; probably use solid manure  from satbles for fields...
        [
          let straw-for-soil-per-ha humusDemandPerHa / reproductionCoefficientStraw
          set estimatedStrawForSoil straw-for-soil-per-ha * acreageWheat

        ]
      ]


      ;;;;;;;;;;;;;;; ARABLE FARMS ;;;;;;;;;;;;;

      if farmType = "arable farm"
      ;; options are to use straw,
      ;; (or use land in humus beneficial way (intertillage, leave as uncultivated land, perennial field forage))
      ;; or purchase organic material, most likely liquiid manure
      [
        ;; OPTION: STRAW
        ;; quantity needed
        let straw-required-straw-option straw-for-humus-demand total-humus-demand
        ;; costs of straw use
        let costs-straw-use straw-opportunity-cost-calculation straw-required-straw-option

        ;; OPTION: PURCHASE LIQUID MANURE PIGS
        ;; quantity needed
        let liquid-manure-use-from-pigs-per-ha liquid-manure-for-humus-demand "pig" humusDemandPerHa
        ;; DüngV (max N supply per year = 170 kg N/ha)
        let N-supply-from-pig-liquid-manure-per-ha N-supply-from "pig" liquid-manure-use-from-pigs-per-ha
        ;; if manure supply surpasses 170 kg/ha boundary
        let complementary-straw-need-per-ha-pig-option 0
        let remaining-humus-demand-per-ha-pig-option 0
        if N-supply-from-pig-liquid-manure-per-ha > 170
        [
          set liquid-manure-use-from-pigs-per-ha allowable-liquid-manure-per-ha "pig"
          set remaining-humus-demand-per-ha-pig-option humusDemandPerHa - (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig)
;                  print "remaining-humus-demand-per-ha-pig-option"
;                  show remaining-humus-demand-per-ha-pig-option
          set complementary-straw-need-per-ha-pig-option (remaining-humus-demand-per-ha-pig-option / reproductionCoefficientStraw)
;                  print "complementary-straw-need-per-ha-pig-option"
;                  show complementary-straw-need-per-ha-pig-option

        ]

        let total-liquid-pig-manure-use liquid-manure-use-from-pigs-per-ha * acreageWheat
        let total-complementary-straw-use-pig-option complementary-straw-need-per-ha-pig-option * acreageWheat

        ;; costs of pig manure use
        let costs-pig-manure-use liquid-manure-cost-calculation "pig" total-liquid-pig-manure-use

        ;        ;; OPTION: PURCHASE LIQUID MANURE CATTLE
        ;        ;; quantity needed
        ;        let liquid-manure-required-cattle liquid-manure-for-humus-demand "cattle" humus-demand
        ;        ;; ?? restrictions on quantity?? (phosphor, nitrate,...)
        ;        ;; costs of cattle manure use
        ;        let costs-cattle-manure-use liquid-manure-cost-calculation "cattle" liquid-manure-required-cattle


        ;; CHOOSING OPTION WITH HIGHEST COST-BENEFIT

        let my-choice min (list costs-straw-use costs-pig-manure-use) ; costs-cattle-manure-use)

        ;; based on humus supply plan determination of potential straw for sale
        if my-choice = costs-straw-use
        [
          set estimatedStrawForSoil straw-required-straw-option
;          print "estimatedStrawForSoil after choosing straw for humus supply by arable farm"
;          show estimatedStrawForSoil

          set estimatedhumusSoilBalance estimatedhumusSoilBalance + humus-supply-from-straw estimatedStrawForSoil
;          print "estimatedhumusSoilBalance after choosing straw as humus supply by arable farm"
;          show estimatedhumusSoilBalance

        ]

        if my-choice = costs-pig-manure-use
        [
          set liquidManureUse total-liquid-pig-manure-use
;          print "liquidManureUse after choosing liquid manure use to substitute straw by arable farmer"
;          show liquidManureUse
          set estimatedStrawForSoil total-complementary-straw-use-pig-option
;          print "estimatedStrawForSoil after choosing liquid manure use to substitute straw by arable farmer"
;          show estimatedStrawForSoil
          let straw-for-soil-per-ha estimatedStrawForSoil / acreageWheat
          ;set profit profit - costs-pig-manure-use
;          print "profit"
;          show profit
          set estimatedhumusSoilBalance estimatedhumusSoilBalance + (liquid-manure-use-from-pigs-per-ha * reproductionCoefficientLiquidManurePig) + humus-supply-from-straw straw-for-soil-per-ha
;          print "estimatedhumusSoilBalance after choosing liquid manure use to substitute straw by arable farmer"
;          show estimatedhumusSoilBalance
        ]

      ]
    ]
  ]
  ;estimating-straw-potential
  ask farmers
  [
    ;; straw for livestock
    if livestock = TRUE
    [
      ;; farms with livestock

      ;; (This is where I can incorporate if straw price passes threshold that makes it more cost-beneficial to use alternative source!)

      if farmSystem = "conventional"
      [
        ;; assumption 15% straw need for animal husbandry assuming stables are mostly not litter based
        set estimatedStrawForLivestock estimatedStrawPotential * shareStrawForLivestockConventionalFarm
      ]

      if farmSystem = "integrated"
      ;; assuming integrated and biodynamic farms have more straw based stable systems and therefore use more straw for own purposes
      [
        set estimatedStrawForLivestock estimatedStrawPotential * shareStrawForLiveStockIntegratedFarm
      ]

      ;; ecofarms that grow wheat and have livestock are assumed to keep all straw for on farm purposes
      if farmSystem = "biodynamic"
      [
        set estimatedStrawForLivestock estimatedStrawPotential * shareStrawForLiveStockBiodynamicFarm
      ]
    ]

    ;; straw for soil (determined in previous procedure)


    ;; straw for sale

    ifelse farmSystem = "biodynamic"
    [
      set potentialStrawForSale 0
    ]
    [
      ifelse askingPriceRoundBales5km > beddingSubstitutionPrice
      [
        let risk-margin 0.1
        set potentialStrawForSale ((1 - risk-margin) * estimatedStrawPotential) - estimatedStrawForSoil - estimatedStrawForLivestock * 0.2
        if potentialStrawForSale < 0
        [
          set potentialStrawForSale 0
        ]
      ]
      [
        let risk-margin 0.1
        set potentialStrawForSale ((1 - risk-margin) * estimatedStrawPotential) - estimatedStrawForSoil - estimatedStrawForLivestock
        if potentialStrawForSale < 0
        [
          set potentialStrawForSale 0
        ]
      ]
    ]
  ]


  ;negotiations/straw trade
  ;straw-procurement procedure
  ;; local users are price takers
  ;; etoh plant makes price offers

  ;; buyers in the market
  let buyers turtles with [marketAgentType = "buyer" and feedstockDemand > 0]

  ;; buyers feedstock demand
  ask buyers
  [
    let my-list initialisation-bidding-mechanism-buyers feedstockDemand

    set storedFeedstockBidding item 0 my-list
    set requiredFeedstockBidding item 1 my-list
    ;show my-list

    set biddingStatus "feedstock demand"
  ]

  ;; etoh plant starting price offer
  ask etohPlantOperators
  [
    set priceOfferBidding priceOffer
  ]

  ;; straw available to market from farmers

   ;; potential sellers in the market
  let potential-sellers farmers with [potentialStrawForSale > 0]

  ask potential-sellers
  [
    set strawAvailabilityBidding potentialStrawForSale

  ]

  ;;loop
  while
  [
    any? potential-sellers with [ strawAvailabilityBidding > 0 ] and
    any? buyers with [ requiredFeedstockBidding > 0 ] and
    ;not any? etohplantoperators with [priceOfferBidding > reservePrice] and
    any? buyers with [biddingStatus != "switch to alternative" ]
  ]

  [
    ;;;; Buyer requests/offers ;;;;
    reset-timer

    ask localUsers
    [
      if requiredFeedstockBidding > 0 and biddingStatus != "switch to alternative"
      [
        local-users-requests
        farmers
      ]
    ]

    ask etohPlantOperators
    [
      if requiredFeedstockBidding > 0
      [
        etoh-requests
        farmers
        requiredFeedstockBidding
        storedFeedstockBidding
      ]
    ]

    ;;;; Farmer responses ;;;;
    ask farmers
    [
      ;reset-timer
      friend-offers
      response-to-other-offers
      ;show timer
    ]

    ;;;; Buyer responses ;;;;

    ask buyers
    [
      ;reset-timer
      accept/refuse-offers
      ;show timer
    ]

    ;show timer
  ]

  ;; after straw negotiations are finished

;  ask farmers
;  [
;    print "straw account after straw procurement procedure"
;    show strawAccount
;  ]


  ;harvest, transport
  ;harvest procedure
    ;;wheat-yield
  ;; global wheat yield area
  set globalWheatYield random-normal 8.5 0.5              ;; [t/ha] , Model region showed wheat yields between 7 and 9 t/ha over the last 15 years (www.regionalstatistik.de)

  ;; individual wheat yield farmer
  ;; in current model setup, soil quality has direct impact on wheat yield
  ask farmers
  [
    set actualWheatYield globalWheatYield * soilQuality
    set wheatYieldExpectation actualWheatYield
  ]


  ;;straw-yield
    ask farmers
  [
    set theoreticalStrawPotential (acreageWheat * actualWheatYield * grainStrawRatio)
    set actualStrawYield (actualWheatYield * grainStrawRatio)                                         ;; grain straw ratio varies for instance due to weather or different crop types, machinery used...
    set actualStrawPotential actualStrawYield * strawHarvestFactor * acreageWheat
    set actualNonHarvestableStraw actualStrawYield * (1 - strawHarvestFactor)
  ]

  ;;straw-accounting
  ask farmers
  [
    set strawSold sum [quantity] of my-contracts

    set strawAccount strawAccount + actualStrawPotential
;    print "strawAccount after contract fullfillment"
;    show strawAccount
    set strawAccount strawAccount - estimatedStrawForSoil - estimatedStrawForLivestock

    set strawForSoil  estimatedStrawForSoil + actualNonHarvestableStraw

    ifelse askingPriceRoundBales5km > beddingSubstitutionPrice
    [
      ifelse strawAvailabilityBidding > estimatedStrawForLivestock
      [
        set strawForLivestock estimatedStrawForLivestock
      ]
      [
        set strawForLivestock estimatedStrawForLivestock * 0.2 + strawAvailabilityBidding
      ]
    ]
    [
      set strawForLivestock estimatedStrawForLivestock
    ]
  ]

  ;;humus-supply
  ask farmers
  [
    ; humus supply from non harvestable straw
    set humusSoilBalance humusSoilBalance + humus-supply-from-straw actualNonHarvestableStraw

;    print "humus balance after considering actual non harvestable straw"
;    show humusSoilBalance

    ;;humus from dedicated straw
    set humusSoilBalance humusSoilBalance + (estimatedStrawForSoil / acreageWheat) * reproductionCoefficientStraw

;    print "humus balance after considering dedicated straw for soil"
;    show humusSoilBalance

    ;; humus from manure
    set humusSoilBalance humussoilBalance + (liquidManureUse / acreageWheat) * reproductionCoefficientLiquidManurePig

;    print "humusSoilBalance after considering humus from liquid manure"
;    show humusSoilBalance
  ]

  ;season evaluation
  ;humus-soil-balance-procedure
    ask farmers
  [
    ifelse humusSoilBalance < 0
    ; negative humus balance has impact on soil quality, which has impact on yields.
    ;
    [
      set soilQuality soilQuality * soilImpactFactor                 ;; simple model assumption: negative humus balance has direct negative impact on soil quality
    ]
    [
      set soilQuality soilQuality * soilRecoveryFactor                 ;; simple model assumption: positive humus balance has direct positive impact on soil qualtiy
    ]

    if soilQuality >= 1
    [
      set soilQuality 1
    ]
  ]
  ;etoh-profit-calculation
    ask ETOHPlantOperators
  [
    ;let actual-operating-hours operatingHours
    ;let actual-efficiency efficiency
    ;let conversion-mwh-t 7.42                    ;;[MWh/t]

    let feedstockAvailability storedFeedstockBidding
    let output feedstockAvailability / yieldEtOH
    let my-turnover output * bioethanolMarketPrice
    set moneyBalance moneyBalance + my-turnover
    set moneyBalance precision moneyBalance 0

    let my-expenses sum [totalCostsBuyer] of my-contracts

    set profit my-turnover - my-expenses
    set profit precision profit 0
    ;print "profit"
    ;show profit

  ]
  ;market-reactions-of-agents procedure
    ;;local-user-market-reactions
    ask localUsers
  [
    if any? my-contracts
    [
      set averageStrawBuyingPrice precision (mean [priceTon] of my-contracts) 0
    ]
  ]

  ;;etoh-plant-market-reactions
  ask EtOHPlantOperators
  [
    if any? my-contracts
    [
      set averageStrawBuyingPrice precision (mean [priceTon] of my-contracts) 1
      set averageStrawProcurementCosts precision (mean [(totalCostsBuyer / quantity)] of my-contracts) 1
    ]

    ifelse feedstockDemand - storedFeedstockBidding > 0
    [
      set priceOffer priceOffer * 1.2
      if priceOffer >= reservePrice
      [
        set priceOffer reservePrice
      ]
    ]
    [
      set priceOffer priceOffer * 0.9
    ]

    set priceOffer precision priceOffer 1
  ]

  ;;farmer-market-reactions
  ask farmers
  [
    ifelse any? my-contracts
    [
      ;; inventory selling prices and quantities at tend of year
      if any? my-contracts with [demandType = "round bales"]
      [
        set mySellingPriceRoundBales precision (mean [priceTon] of my-contracts with [demandType = "round bales"]) 1
        set mySellingQuantityRoundBales precision (sum [quantity] of my-contracts with [demandType = "round bales"]) 1
        set averageTransportDistanceRoundBales precision (mean [link-length * 5] of my-contracts with [demandType = "round bales"]) 1
      ]

      if any? my-contracts with [demandType = "off field"]
      [
        set mySellingPriceOffField precision (mean [priceTon] of my-contracts with [demandType = "off field"]) 1
        set mySellingQuantityOffField precision (sum [quantity] of my-contracts with [demandType = "off field"]) 1
      ]

      ifelse strawAvailabilityBidding <= 0
      [
        set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 1.1) 1
        set askingPriceStrawOffField precision (askingPriceStrawOffField * 1.1) 1
      ]
      [
        ifelse strawAvailabilityBidding > 0.5 * potentialStrawForSale
        [
          set askingPriceRoundBales5km askingPriceRoundBales5km * 0.7
          set askingPriceStrawOffField askingPriceStrawOffField * 0.7

          if askingPriceRoundBales5km <= reservePriceRoundBales5km
          [
            set askingPriceRoundBales5km reservePriceRoundBales5km
          ]

          if askingPriceStrawOffField <= reservePriceStrawOffField
          [
            set askingPriceStrawOffField reservePriceStrawOffField
          ]

        ]
        [
          ifelse strawAvailabilityBidding > 0.3 * potentialStrawForSale
          [
            set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 0.8) 1
            set askingPriceStrawOffField precision (askingPriceStrawOffField * 0.8) 1

            if askingPriceRoundBales5km <= reservePriceRoundBales5km
            [
              set askingPriceRoundBales5km reservePriceRoundBales5km
            ]

            if askingPriceStrawOffField <= reservePriceStrawOffField
            [
              set askingPriceStrawOffField reservePriceStrawOffField
            ]
          ]
          [
            if strawAvailabilityBidding > 0.15 * potentialStrawForSale
            [
              set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 0.9) 1
              set askingPriceStrawOffField precision (askingPriceStrawOffField * 0.9) 1
              if askingPriceRoundBales5km <= reservePriceRoundBales5km
              [
                set askingPriceRoundBales5km reservePriceRoundBales5km
              ]

              if askingPriceStrawOffField <= reservePriceStrawOffField
              [
                set askingPriceStrawOffField reservePriceStrawOffField
              ]
            ]
          ]
        ]
      ]
    ]
    [
      set askingPriceRoundBales5km precision (askingPriceRoundBales5km * 0.7) 1
      set askingPriceStrawOffField precision (askingPriceStrawOffField * 0.7) 1
      if askingPriceRoundBales5km <= reservePriceRoundBales5km
      [
        set askingPriceRoundBales5km reservePriceRoundBales5km
      ]

      if askingPriceStrawOffField <= reservePriceStrawOffField
      [
        set askingPriceStrawOffField reservePriceStrawOffField
      ]
    ]
  ]
  ;; season-reactions prdocedure

  ask farmers
  [
    if actualWheatYield < globalWheatYield * 0.85
    [
      set yieldAlert true
    ]

    if actualWheatYield >= globalWheatYield * 0.95 and soilQuality >= 1
    [
      set yieldAlert false
    ]
  ]
end 


;;;;;;;;;;;;;;;;;;;;;;;;;;; REPORTERS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; MARKET PRICES

to-report averagePriceRoundBales

  let a 0
  if any? contracts with [demandType = "round bales"]
  [
    set a mean [priceTon] of contracts with [demandType = "round bales"]
  ]
  set a precision a 0
  report a
end 

to-report averagePriceOffField

  let a 0

  if any? contracts with [demandType = "off field"]
  [
    set a mean [priceTon] of contracts with [demandType = "off field"]
  ]
  set a precision a 0
  report a
end 

to-report averagePriceRoundBalesConventionalFarmers

  report mean [mySellingPriceRoundBales] of farmers with [farmSystem = "conventional"]
end 

to-report averagePriceOffFieldConventionalFarmers

  report mean [mySellingPriceOffField] of farmers with [farmSystem = "conventional"]
end 

to-report averagePriceRoundBalesIntegratedFarmers

  report mean [mySellingPriceRoundBales] of farmers with [farmSystem = "integrated"]
end 

to-report averagePriceOffFieldIntegratedFarmers

  report mean [mySellingPriceOffField] of farmers with [farmSystem = "integrated"]
end 



;; DEMAND

to-report totalDemand
  let total-demand 0
  set total-demand sum [feedstockDemand] of turtles with [marketAgentType = "buyer"]
  set total-demand precision total-demand 0
  report total-demand
end 

to-report totalDemandEtOH
  let a 0
  set a sum [feedstockDemand] of EtOHPlantOperators
  set a precision a 0
  report a
end 

to-report currentDemandEtOH
  let etoh-demand 0
  set etoh-demand sum [requiredFeedstockBidding] of etohplantoperators
  set etoh-demand precision etoh-demand 0
  report etoh-demand
end 

to-report totalDemandLocalUsers
  report sum [feedstockDemand] of localUsers
end 

to-report currentDemandLocalUsers
  let local-demand 0
  set local-demand sum [requiredFeedstockBidding] of localUsers
  set local-demand precision local-demand 0
  report local-demand
end 



;; SUPPLY

to-report sumTheoreticalStrawPotential
  let a 0
  set a sum [theoreticalStrawPotential] of farmers
  set a precision a 0
  report a
end 

to-report sumTheoreticalStrawPotentialConventional
  let a 0
  set a sum [theoreticalStrawPotential] of farmers with [farmSystem = "conventional"]
  set a precision a 0
  report a
end 

to-report sumTheoreticalStrawPotentialIntegrated
  let a 0
  set a sum [theoreticalStrawPotential] of farmers with [farmSystem = "integrated"]
  set a precision a 0
  report a
end 

to-report sumTechnicalStrawPotential
  let a 0
  set a sum [actualStrawPotential] of farmers
  set a precision a 0
  report a
end 

to-report sumTechnicalStrawPotentialConventional
  let a 0
  set a sum [actualStrawPotential] of farmers with [farmsystem = "conventional"]
  set a precision a 0
  report a
end 

to-report sumTechnicalStrawPotentialIntegrated
  let a 0
  set a sum [actualStrawPotential] of farmers with [farmsystem = "integrated"]
  set a precision a 0
  report a
end 

to-report sumPotentialStrawForSale
  let straw-supply 0
  set straw-supply sum [potentialStrawForSale] of farmers
  set straw-supply precision straw-supply 0
  report straw-supply
end 

to-report sumPotentialStrawForSaleConventional
  let straw-supply 0
  set straw-supply sum [potentialStrawForSale] of farmers with [farmSystem = "conventional"]
  set straw-supply precision straw-supply 0
  report straw-supply
end 

to-report sumPotentialStrawForSaleIntegrated
  let straw-supply 0
  set straw-supply sum [potentialStrawForSale] of farmers with [farmSystem = "integrated"]
  set straw-supply precision straw-supply 0
  report straw-supply
end 


;; STRAW USES

to-report sumStrawForSoils
  let straw-supply 0
  set straw-supply sum [strawForSoil] of farmers
  set straw-supply precision straw-supply 0
  report straw-supply
end 

to-report sumStrawForSoilsConventional
  let straw-supply 0
  set straw-supply sum [strawForSoil] of farmers with [farmSystem = "conventional"]
  set straw-supply precision straw-supply 0
  report straw-supply
end 

to-report sumStrawForSoilsIntegrated
  let straw-supply 0
  set straw-supply sum [strawForSoil] of farmers with [farmSystem = "integrated"]
  set straw-supply precision straw-supply 0
  report straw-supply
end 

to-report sumStrawSold
  let a 0
  set a sum [strawSold] of farmers
  set a precision a 0
  report a
end 

to-report sumStrawSoldConventional
  let a 0
  set a sum [strawSold] of farmers with [farmSystem = "conventional"]
  set a precision a 0
  report a
end 

to-report sumStrawSoldIntegrated
  let a 0
  set a sum [strawSold] of farmers with [farmSystem = "integrated"]
  set a precision a 0
  report a
end 

to-report totalStrawSupplyForEtOH
  let a 0
  set a sum [storedFeedstockBidding] of EtohPlantOperators
  set a precision a 0
  report a
end 

to-report totalStrawSupplyForEtOHConventional

  report sum [mySellingQuantityOffField] of farmers with [farmSystem = "conventional"]
end 

to-report totalStrawSupplyForEtOHIntegrated

  report sum [mySellingQuantityOffField] of farmers with [farmSystem = "integrated"]
end 

to-report sumStrawSupplyForLocalUsers
  report sum [storedFeedstockBidding] of localusers
end 

to-report sumStrawSupplyForLocalUsersConventional
  report sum [mySellingQuantityRoundBales] of farmers with [farmSystem = "conventional"]
end 

to-report sumStrawSupplyForLocalUsersIntegrated
  report sum [mySellingQuantityRoundBales] of farmers with [farmSystem = "integrated"]
end 

to-report sumStrawForLivestock
  let a 0
  set a sum [StrawForLivestock] of farmers
  set a precision a 0
  report a
end 

to-report sumStrawForLivestockConventional
  let a 0
  set a sum [StrawForLivestock] of farmers with [farmSystem = "conventional"]
  set a precision a 0
  report a
end 

to-report sumStrawForLivestockIntegrated
  let a 0
  set a sum [StrawForLivestock] of farmers with [farmSystem = "integrated"]
  set a precision a 0
  report a
end 



;; WHEAT YIELD

to-report averageWheatYield
  let a 0
  set a mean [actualWheatYield] of farmers
  set a precision a 3
  report a
end 

to-report wheatYieldConventionalFarmers
  let a 0
  set a mean [actualWheatYield] of farmers with [farmSystem = "conventional"]
  set a precision a 3
  report a
end 

to-report wheatYieldIntegratedFarmers
  let a 0
  set a mean [actualWheatYield] of farmers with [farmSystem = "integrated"]
  set a precision a 3
  report a
end 


;; HUMUS BALANCES

to-report meanHumusBalanceConventionalFarmers
  let a 0
  set a mean [humusSoilBalance] of farmers with [ farmSystem = "conventional" ]
  set a precision a 3
  report a
end 

to-report meanHumusBalanceIntegratedFarmers
  let a 0
  set a mean [humusSoilBalance] of farmers with [ farmSystem = "integrated" ]
  set a precision a 3
  report a
end 

to-report meanHumusBalanceMixedConventionalFarmers
  let output 0
  let mean-humus-per-agent mean [humusSoilBalance] of farmers with [farmType = "mixed farm" and farmSystem = "conventional"]
  set output mean-humus-per-agent
  report output
end 

to-report meanHumusBalanceArableConventionalFarmers
  let output 0
  let mean-humus-per-agent mean [humusSoilBalance] of farmers with [farmType = "arable farm" and farmSystem = "conventional"]
  set output mean-humus-per-agent
  report output
end 

to-report meanHumusBalanceMixedIntegratedFarmers
  let output 0
  let mean-humus-per-agent mean [humusSoilBalance] of farmers with [farmType = "mixed farm" and farmSystem = "integrated"]
  set output mean-humus-per-agent
  report output
end 

to-report meanHumusBalanceArableIntegratedFarmers
  let output 0
  let mean-humus-per-agent mean [humusSoilBalance] of farmers with [farmType = "arable farm" and farmSystem = "integrated"]
  set output mean-humus-per-agent
  report output
end 

to-report meanHumusBalanceAggregate
  let output 0
  let mean-humus-per-agent mean [humusSoilBalance] of farmers
  set output mean-humus-per-agent
  set output precision output 3
  report output
end 


;;; LIQUID MANURE USE

to-report totalLiquidManureUse
  let a 0
  set a sum [liquidManureUse] of farmers
  set a precision a 0
  report a
end 


;;MONETARY FLOWS


;;;;(TURNOVER/YEAR)

to-report avgTurnoverFarmers

  report mean [turnover] of farmers
end 

to-report avgTurnoverConventionalFarmers
  report mean [turnover] of farmers with [farmSystem = "conventional"]
end 

to-report avgTurnoverIntegratedFarmers
  report mean [turnover] of farmers with [farmSystem = "integrated"]
end 


;;;;(PROFIT/YEAR)

to-report totalProfitConventionalFarmers
  report sum [profit / acreageWheat] of farmers with [farmSystem = "conventional"]
end 

to-report totalProfitIntegratedFarmers
  report sum [profit / acreageWheat] of farmers with [farmSystem = "integrated"]
end 

to-report avgProfitFarmers
  report mean [profit / acreageWheat] of farmers with [farmSystem = "conventional" or farmSystem = "integrated"]
end 

to-report avgProfitConventionalFarmers
  report (mean [profit / acreageWheat] of farmers with [farmSystem = "conventional"])
end 

to-report avgProfitIntegratedFarmers
  report (mean [profit / acreageWheat] of farmers with [farmSystem = "integrated"])
end 

There is only one version of this model, created almost 2 years ago by Henrik Sontag.

Attached files

File Type Description Last updated
Straw for ethanol production - impact of market dynamics.png preview Preview for 'Straw for ethanol production - impact of market dynamics' almost 2 years ago, by Henrik Sontag Download

This model does not have any ancestors.

This model does not have any descendants.