In the setup I would create a command that generate a random number of cluster with a random dimension. Each cluster it would be managed by an agent (farmer). Every single patch represent a potential crop that farmer can cultivate with a different type of seeds. It would be worth use the function in-radius? If you need more details ask me.
Thank you very much for your answers, it's exactly what I need! Now I've another question, I implemented the program as you suggest and now I displaying a world like your, but I don't know how to make my agent (the farmer) act on every patch of their farm-size. In my simulation farmer act only on one patch the one they are on. I tried in a different way to extend the action of my agent (function patch-set, ) but everytime I got an error during the running of the procedure.
As suggested in the previous post by Marzy I include the code of my model.
The main problem is to extend the procedure "to cultivate" (at the bottom of the code) to each patches who belongs-to a farmer.
Thank you very much
turtles-own [
profit-from-fuel
profit-from-food
expected-fuel-sell-price
expected-food-sell-price
profit
farm
farm-size
;risk-attitude-food
;risk-attitude-fuel
]
patches-own [
fuel-yeld
food-yeld
land-sustainability
water-level
belongs-to
]
globals [
fuel-sell-price
food-sell-price
governs
]
to setup
clear-all
clear-all-plots
create-farmers
setup-land
reset-ticks
ask turtles
[ set-farm-in-radius farm-size ]
set fuel-sell-price 30 ;+ random 2 + random -2
set food-sell-price 30 ;+ random 2 + random -2
end
to create-farmers
create-turtles 30
[
set shape "person farmer"
setxy random-pxcor random-pycor
set profit-from-fuel 0 ; indicizzazione del profitto iniziale a 0
set profit-from-food 0 ; indicizzazione del profitto iniziale a 0
set farm-size random 5 + 1
set label farm-size
]
end
to setup-land
ask patches [set belongs-to nobody]
ask patches
[
set pcolor 3
set food-yeld 10000
set fuel-yeld 10000
set land-sustainability random 5
set water-level random 3
]
end
to set-farm-in-radius [d]
move-to one-of patches with [not any? other patches in-radius d with [belongs-to != nobody]]
set farm patches in-radius farm-size
ask farm [set belongs-to myself]
let c random 6 + 61
ask farm [set pcolor c]
end
to set-farm-distance [d]
move-to one-of patches with [not any? other patches with [belongs-to != nobody and distance myself < d]]
set farm patches with [distance myself < d]
ask farm [set belongs-to myself]
let c random 6 + 61
ask farm [set pcolor c]
end
to go
tick
ask turtles [
set expected-fuel-sell-price fuel-sell-price + random 5 + random -5
if expected-fuel-sell-price < 0 [set expected-fuel-sell-price 1]
set expected-food-sell-price food-sell-price + random 5 + random -5
if expected-food-sell-price < 0 [set expected-food-sell-price 1]
set profit profit-from-fuel + profit-from-food
if profit = 0 [ set profit 1 ]
]
set fuel-sell-price fuel-sell-price + random 5 + random -5
if fuel-sell-price < 0 or fuel-sell-price = 0 [set fuel-sell-price 1 ]
set food-sell-price food-sell-price + random 5 + random -5
if food-sell-price < 0 or food-sell-price = 0 [set food-sell-price 1]
ask turtles [
cultivate
set profit profit-from-food + profit-from-fuel
;if water-level > 0.95 [ set profit profit - (profit * ( 2 / profit )) ] valutare se inserire anche una failing probability
]
if ticks = Duration [ stop ]
if ticks > Duration [stop]
end
to cultivate
ifelse land-sustainability < 2.1 or water-level = 1
[ set pcolor green set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
]
[
let utility-from-food ((food-yeld * expected-food-sell-price * land-sustainability) ^ risk-attitude ) / risk-attitude
let utility-from-fuel ((food-yeld * expected-fuel-sell-price * land-sustainability) ^ (1 - risk-attitude) ) / ( 1 - risk-attitude)
ifelse utility-from-food < utility-from-fuel
[
set pcolor red
set profit-from-fuel fuel-sell-price * (((fuel-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
]
[
set pcolor green
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
]
]
end
new version_______----
to cultivate
ifelse land-sustainability < 2.1 or water-level = 1
[
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
set food 1
]
[
let utility-from-food ((food-yeld * expected-food-sell-price * land-sustainability) ^ risk-attitude ) / risk-attitude
let utility-from-fuel ((food-yeld * expected-fuel-sell-price * land-sustainability) ^ (1 - risk-attitude) ) / ( 1 - risk-attitude)
ifelse utility-from-food < utility-from-fuel
[
set profit-from-fuel fuel-sell-price * (((fuel-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
set fuel 1
]
[
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
set food 1
]
]
ask farm [
if food = 1 [set pcolor green]
if fuel = 1 [set pcolor red]
]
end
As Seth said its similar to other questions in stackoverflow, here is more related answer:
turtles-own [farm farm-size]
patches-own [belongs-to]
to setup
clear-all
ask patches [set belongs-to nobody]
create-turtles 9
[
set farm-size random 5 + 1
set label farm-size
]
ask turtles
[
set-farm-in-radius farm-size
]
ask patch -8 14 [set plabel "set-farm-in-radius"]
end
to set-farm-in-radius [d]
move-to one-of patches with [not any? other patches in-radius d with [belongs-to != nobody]]
set farm patches in-radius farm-size
ask farm [set belongs-to myself]
let c random 8 + 21
ask farm [set pcolor c]
end
to set-farm-distance [d]
Move-to one-of patches with [not any? other patches with [belongs-to != nobody and distance myself < d]]
set farm patches with [distance myself < d]
ask farm [set belongs-to myself]
let c random 8 + 21
ask farm [set pcolor c]
end
And using distance results in following design, I have set the varibele belongs_to of each patch which shows who owns that patch in plabel so you can see it better.
Update: When you want to make a change on every patch of a farm you should ask farm []
to cultivate
ifelse land-sustainability < 2.1 or water-level = 1
[
ask farm [
set pcolor green
]
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
]
[
let utility-from-food ((food-yeld * expected-food-sell-price * land-sustainability) ^ risk-attitude ) / risk-attitude
let utility-from-fuel ((food-yeld * expected-fuel-sell-price * land-sustainability) ^ (1 - risk-attitude) ) / ( 1 - risk-attitude)
ifelse utility-from-food < utility-from-fuel
[ ask farm [
set pcolor red
]
set profit-from-fuel fuel-sell-price * (((fuel-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
]
[
ask farm [
set pcolor green ]
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
]
]
end
Update:
to cultivate
ifelse land-sustainability < 2.1 or water-level = 1
[
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
ask farm [
set food 1
]
]
[
let utility-from-food ((food-yeld * expected-food-sell-price * land-sustainability) ^ risk-attitude ) / risk-attitude
let utility-from-fuel ((food-yeld * expected-fuel-sell-price * land-sustainability) ^ (1 - risk-attitude) ) / ( 1 - risk-attitude)
ifelse utility-from-food < utility-from-fuel
[
set profit-from-fuel fuel-sell-price * (((fuel-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
ask farm [
set fuel 1
]
]
[
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
ask farm [
set food 1
]
]
]
end
to recolor-farm
if food = 1 [set pcolor green ]
if fuel = 1 [set pcolor red]
end
Add ask farm [recolor-farm] after Cultivate
Your answer for second part:
to cultivate
ifelse land-sustainability < 2.1 or water-level = 1
[
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
ask farm
[
set food 1
]
]
[
let utility-from-food ((food-yeld * expected-food-sell-price * land-sustainability) ^ risk-attitude ) / risk-attitude
let utility-from-fuel ((food-yeld * expected-fuel-sell-price * land-sustainability) ^ (1 - risk-attitude) ) / ( 1 - risk-attitude)
ifelse utility-from-food < utility-from-fuel
[
set profit-from-fuel fuel-sell-price * (((fuel-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
ask farm
[
set fuel 1 ]
]
[
set profit-from-food food-sell-price * (((food-yeld ) ^ (1 - alfa)) * (((water-level) ^ (1 - gamma)) * ((land-sustainability) ^ (gamma)) ^ alfa))
ask farm [
set food 1]
]
]
ask farm [
if food = 1 [set pcolor green]
if fuel = 1 [set pcolor red]
]
end
Related
I will be very grateful if someone could give me any kind of advice about a problem that I have in my code. I am working on a model with four kind of agents. Each type of agents uses a different strategy. These strategies are Prisoner Dilemma variations. Two of these strategies (tit for tat and unforgiving) need to record (in a list) who was the partner of interaction, and depending if that partner defected or not, will be the behave (cooperative or defect) of the agent in the next encounter with the same partner. Agents move randomly through the world. The problem come when agents die or birth according of their resources level. At this point these strategies that require to record who was the previous partner and how was his behave (cooperative or defect) do not work. This is the message that show up.
I am really appreciate any support!!!!.
number of initial turtles is 42, but two ticks later the number is 52
Below is a code that reproduces the error. In order to run it, it is necessary to create the sliders: n-tit-for-tat-com; n-unforgiving-com; inc-ecological-resources; energy-consume-companies:
globals
[
;;Number of companies with each strategy¨
num-tit-for-tat-com
num-unforgiving-com
;;number of interactions by each strategy
num-tit-for-tat-com-games
num-unforgiving-com-games
;; Total score of all companies playing each strategy
tit-for-tat-com-score
unforgiving-com-score
; Total companies en each ticks
num-companies
]
breed [companies company]
;;create companies variables
companies-own [
score-com
score-com-round
strategy-com
defect-now?-com
partner-defected?-com ;;action of the partner
partnered?-com ;;am I partnered?
partner-com ;;WHO of my partner (nobody if not partnered)
partner-history-com ;;a list containing information about past interactions with other turtles (indexed by WHO values)
earnings-tit-for-tat-Com
earnings-unforgiving-Com
earnings-com
tit-for-tat-com-score-round
unforgiving-com-score-round
]
patches-own
[
resources-amount ;; resources amount in each patches
resources-to ;; aux variable to count resources taken
]
;;;Setup Procedures;;;
to setup
clear-all
setup-patches
setup-companies ;;setup the turtles and distribute them randomly
reset-ticks
end
; Setup patches
;===============
to setup-patches
ask patches [set resources-amount random 4] ;; patches represent ecological system. Resources are distributed randomly. [0,1,2 or 3] 0 -> non resources; 3 -> plenty of resources
ask patches [
set pcolor (ifelse-value
resources-amount = 0 [49]
resources-amount = 1 [58]
resources-amount = 2 [67]
resources-amount = 3 [65]
[63] ;; this case never happen. Because 4 means integer number in range [0 to 3]
)]
end
to setup-companies
make-companies ;;create the appropriate number of turtles playing each strategy
setup-common-variables-com ;;sets the variables that all turtles share
end
;;create the appropriate number of turtles playing each strategy
to make-companies
create-companies n-tit-for-tat-com
[ set strategy-com "tit-for-tat-com"
set color 135
set earnings-tit-for-tat-Com random 4 + 1 ;;randomly initial resources in the range [ 1 - 4 ]. It is sum + 1 to enforce never inicial resource = 0
]
create-companies n-unforgiving-com
[ set strategy-com "unforgiving-com"
set color 4
set earnings-unforgiving-Com random 4 + 1 ;;randomly initial resources in the range [ 1 - 4 ]. It is sum + 1 to enforce never inicial resource = 0
]
end
; Setup common variables
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
;;set the variables that all turtles share
to setup-common-variables-com
ask companies [
set shape "pentagon"
set size 1.3
set tit-for-tat-com-score-round 0
set unforgiving-com-score-round 0
set score-com 0
set partnered?-com false
set partner-com nobody
setxy random-xcor random-ycor
]
end
;;;Runtime Procedures;;;
to go
ask companies [birth-die-com]
store-initial-companies-counts ;;record the number of turtles for each strategy
setup-history-lists-com
clear-last-round
ask companies [ partner-up-com ] ;;have turtles try to find a partner
let partnered-com companies with [ partnered?-com ]
ask partnered-com [ select-strategy-com ] ;;all partnered turtles select action
ask partnered-com [ play-a-round-com ]
adjust-patches
tick
end
;Birth-die-com ; According to the level of resources companies can die or birth
;======================
to birth-die-com
(ifelse
strategy-com = "tit-for-tat-com"
[
set earnings-com earnings-tit-for-tat-com
(if earnings-com > 2 * energy-consume-companies [
hatch 1 [set earnings-tit-for-tat-com random 2 + 1 ] ;;randomly initial resources in the range [ 1 - 2 ]. It is sum + 1 to enforce never inicial resource = 0
set earnings-com (earnings-com - energy-consume-companies )])
( if earnings-com < energy-consume-companies [ die ])
]
strategy-com = "unforgiving-com"
[
set earnings-com earnings-unforgiving-com
(if earnings-com > 2 * energy-consume-companies [
hatch 1 [set earnings-unforgiving-com random 2 + 1 ] ;;randomly initial resources in the range [ 1 - 2 ]. It is sum + 1 to enforce never inicial resource = 0
set earnings-com (earnings-com - energy-consume-companies )])
( if earnings-com < energy-consume-companies [ die ])
]
)
end
;;STORE INITIAL COMPANIES¨
;===========================
;;record the number of turtles at the begining of each tick
;;The number of turtles of each strategy is used when calculating average payoffs.
to store-initial-companies-counts
set num-tit-for-tat-com (count companies with [strategy-com = "tit-for-tat-com"])
set num-unforgiving-com (count companies with [strategy-com = "unforgiving-com"])
end
;Setup-History-Lists-com;; initialize PARTNER-HISTORY list in all turtles
;========================
to setup-history-lists-com
set num-companies (count companies)
let default-history-com [] ;;initialize the DEFAULT-HISTORY variable to be a list
;create a list with NUM-TURTLE elements for storing partner histories
repeat (count companies) [ set default-history-com (fput false default-history-com) ]
;give each turtle a copy of this list for tracking partner histories
ask companies [ set partner-history-com default-history-com ]
end
;Clear-last-round
;================
to clear-last-round
let partnered-com companies with [ partnered?-com ]
ask partnered-com [ release-partners-com ]
end
; release partner between companies and turn around
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
to release-partners-com
set partnered?-com false
set partner-com nobody
rt 180
set label ""
end
;;have turtles try to find a partner
;;Since other turtles that have already executed partner-up may have
;;caused the turtle executing partner-up to be partnered,
;;a check is needed to make sure the calling turtle isn't partnered.
;;partner-up. Find partner
;===========================
to partner-up-com ;;turtle procedure
if (not partnered?-com) [ ;;make sure still not partnered
rt (random-float 90 - random-float 90) fd 1 ;;move around randomly
set partner-com one-of other (companies in-radius 1 ) with [ not partnered?-com ]
if partner-com != nobody [ ;;if successful grabbing a partner, partner up
set partnered?-com true
set heading 270 ;;face partner
ask partner-com [
set partnered?-com true
set partner-com myself
set heading 90
]
]
]
end
;Select stratey company
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
;;choose an action based upon the strategy being played
to select-strategy-com ;;turtle procedure
if strategy-com = "tit-for-tat-com" [ tit-for-tat-com ]
if strategy-com = "unforgiving-com" [ unforgiving-com ]
end
;Play a round-companies
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
to play-a-round-com ;;turtle procedure
get-payoff-com ;;calculate the payoff for this round
update-history-com ;;store the results for next time
end
; get-payoff-com
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
;;calculate the payoff for this round and
;;display a label with that payoff.
;; Strategy-companies
;Turtles l l
;Action l C l D
;__________l________ l__________
; C l 3 l -3
;----------l---------l----------
; D l 5 l -2
to get-payoff-com
set partner-defected?-com [defect-now?-com] of partner-com
ifelse partner-defected?-com [
ifelse defect-now?-com
[ set score-com (score-com + 1 ) set label 1 set score-com-round 1 ]
[set score-com (score-com + 0) set label 0 set score-com-round 0]
]
[ifelse defect-now?-com
[set score-com (score-com + 5) set label 5 set score-com-round 5]
[set score-com (score-com + 3) set label 3 set score-com-round 3]
]
end
;Update-history
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨
;;update PARTNER-HISTORY based upon the strategy being played
to update-history-com
if strategy-com = "tit-for-tat-com" [ tit-for-tat-com-history-update ]
if strategy-com = "unforgiving-com" [ unforgiving-com-history-update ]
end
;;;Strategies;;;
; Tit-for-tat-com
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
to tit-for-tat-com
set num-tit-for-tat-com-games num-tit-for-tat-com-games + 1
set partner-defected?-com item ([who] of partner-com) partner-history-com
ifelse (partner-defected?-com)
[set defect-now?-com true]
[set defect-now?-com false]
ask companies in-radius 1 [
ask patches in-radius 1 [set resources-to (resources-amount * 1)]
ask patches in-radius 1 [set resources-amount (resources-amount - resources-to)]
set tit-for-tat-com-score-round ( tit-for-tat-com-score-round + score-com-round )
set earnings-tit-for-tat-com (earnings-tit-for-tat-Com + ((sum [ resources-to ] of patches in-radius 1)/ 2) + tit-for-tat-com-score-round - energy-consume-companies )
ask patches in-radius 1 [set resources-to 0 ]
set tit-for-tat-com-score-round 0
]
end
;Tit-for-tat-com-history-update¨
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
to tit-for-tat-com-history-update
set partner-history-com
(replace-item ([who] of partner-com) partner-history-com partner-defected?-com)
end
;unforgiving-com ; Works similar to tit-for-tat, but once the another defect, always defect
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
to unforgiving-com
set num-unforgiving-com-games num-unforgiving-com-games + 1
set partner-defected?-com item ([who] of partner-com) partner-history-com
ifelse (partner-defected?-com)
[set defect-now?-com true]
[set defect-now?-com false]
ask companies in-radius 1 [
ask patches in-radius 1 [set resources-to (resources-amount * 1)]
ask patches in-radius 1 [set resources-amount (resources-amount - resources-to)]
set unforgiving-com-score-round ( unforgiving-com-score-round + score-com-round )
set earnings-unforgiving-com (earnings-unforgiving-Com + ((sum [ resources-to ] of patches in-radius 1)/ 2) + unforgiving-com-score-round - energy-consume-companies)
ask patches in-radius 1 [set resources-to 0 ]
set unforgiving-com-score-round 0
]
end
;unforgiving-com-history-update
;¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
to unforgiving-com-history-update
if partner-defected?-com [
set partner-history-com
(replace-item ([who] of partner-com) partner-history-com partner-defected?-com)
]
end
;; Adjusting Patches
;; Put limits
to adjust-patches
ask patches [ set resources-amount resources-amount + random-float Inc-Ecological-resources ] ;; Resources are renewable. They grow up again between [0-3). Use Slider
ask patches [ ;; Resources range [0-3)
set resources-amount (ifelse-value
resources-amount < 0 [0] ;;
resources-amount > 3 [3] ;;
[resources-amount]
)
]
;; Patches are colored according their level
ask patches [
set pcolor (ifelse-value
resources-amount < 0 [ black ]
resources-amount = 0 [ 38 ]
resources-amount > 0 and resources-amount <= 0.5 [ 49 ]
resources-amount > 0.5 and resources-amount <= 2 [ 67 ]
resources-amount > 2 and resources-amount <= 3 [ 65 ]
resources-amount > 3 and resources-amount <= 4 [ 63 ]
[ white ])
]
end
I am writing a model and want to add a button of chooser to assess alternative management options. Model was working fine as some variables graphs disappeared as I have added chooser for around all of turtles. I have also tried changing parameters from Turtle-own to global and vice versa and not rectified the error. I couldn't figure out the issus. Problem arise when i add chooser in irrigate procedure. Codes are bit longer, please bear with me. I will be grateful for the solution. Please help me to get out of difficult situation.
I have also shared before and after image of interface.
Before
and after
Thanks
Globals [farmlocations farmers-list water eva IWR-perday ASW maxgwater usedflow wdemand wtdmean wtdsd av-wdischarge wdischarge wd totannual-wdischarge current-demand wtd canal-wdischarge water-right alpha beta]
Breed [Farmers farmer]
farmers-own [ irrigation-turn season1-profit swh season2-profit yield myflow DWT total-gw-cost watercosts total-sw-cost raqba sw benefits evapotrans totaldemand swcost gwateruse wneed logging gwcost salinity aw totalcosts dws resources irrigation-turn gw AGW mywaterloss] ;swh= surface water height aw= old surface water height
Patches-own [gw-level]
links-own [flow]
to setup
clear-all
setup-farmers
import-data
reset-ticks
end
to setup-farmers
create-farmers 5 [ set irrigation-turn [0]
ask farmer 0 [ setxy min-pxcor + 1 2 set irrigation-turn 1]
ask farmer 1 [ setxy min-pxcor + 1 0 set irrigation-turn 2]
ask farmer 2 [ setxy min-pxcor + 1 4 set irrigation-turn 2]
ask farmer 3 [ setxy min-pxcor + 3 2 set irrigation-turn 3]
ask farmer 4 [ setxy min-pxcor + 3 0 set irrigation-turn 3]
]
set farmers-list sort turtles
set eva 0.3
ask farmers [set label who + 1
set size 1
set myflow 0
If land = "small farmers" [ set raqba random 5 + 3 ]
If land = "small and large farmers" [ ifelse random 3 = 1 [set raqba 10 + random 20 ] [ set raqba 5 + random 5]]
set total-sw-cost 500 * raqba
Set resources 1
set DWS 5 + 1 * (who)
set evapotrans 5 + 1 * (who)
set water-right 4.5 * raqba
Set logging 500 / DWS
Set salinity DWS / 5
set maxgwater 200
set wtdmean 10
set wtdSD 5
set sw 0
set swh 0
set aw 0
set gw-level 100 / dws
set gw 50000 + random 1000
Depth-to-Water-Table
ground-water-travel
water-losses
set alpha 1
set beta 0.7
]
set av-wdischarge 4.5
end
to Depth-to-Water-Table
set DWT Water-Table-Depth + DWS / 10
end
to ground-water-travel
set gw gw + 10 / (random-float 1 + DWT) * DWS
set AGW gw + (sum [gw-level] of patches in-radius 2)
set pcolor scale-color blue AGW 1 max [gw-level] of patches in-radius 2
end
to water-losses
Set mywaterloss waterloss + 5 * DWS ; 5 + 1* who
end
to go
tick
if ticks = 630 [ stop ]
calculate-sw
evaporate
irrigate
ask turtles [set color scale-color blue swh 30 3]
calculate-profits
update-output
end
to
calculate-sw
let list-element floor ticks / 5
ask item (ticks mod 5) farmers-list [
set canal-wdischarge item list-element totannual-wdischarge
set wdischarge canal-wdischarge - (canal-wdischarge * discharge-reduction)]
end
to evaporate
let list-element floor ticks / 5
ask item (ticks mod 5) farmers-list [
set current-demand item list-element IWR-perday
set Aw swh
if aw >= current-demand [set wneed 0]
set wneed 0
set wneed wneed + current-demand - aw
ask farmers [ set totaldemand current-demand * raqba + evapotrans]
if wneed < 0 [set wneed 0]
set swh swh - swh * eva
if swh < 0 [set swh 0]
]
end
to irrigate
If water-use-mangement = "Business as usual" [
ask turtles with [irrigation-turn = (ticks mod count farmers)]
[ set color red
set shape "person"
set pcolor brown + who
set ASW (Wdischarge - myWaterloss)* raqba
if ASW < 0 [set ASW 0]
set myflow ASW
ifelse wneed > 0 [
set swh myflow / raqba + aw
ifelse swh > current-demand [set swh current-demand ] [use-gw]
ifelse swh > aw [set usedflow (swh - aw) * raqba
if usedflow < 0 [ set usedflow 0]
set ASW ASW - usedflow
if ASW < 0 [ set ASW 0]
update-gw-use ]
[set usedflow 0]] [
set myflow 0
set swh aw + ((myflow ) / raqba)
if swh > current-demand [set swh current-demand ]]]]
end
to use-gw
Ask farmers [ let excess-demand (current-demand - swh) * raqba
if AGW > excess-demand [ ;set excess-demand AGW
set gwateruse agw - excess-demand
set dwt dwt + (0.2 + who / 20)
Ifelse DWT > 8 [ set gwcost excess-demand * 17.5] [set gwcost excess-demand * 5]
set agw agw - excess-demand
If AGW < 0 [ set AGW 0]
Ifelse excess-demand > 0.5 * current-demand [ifelse random 4 = 1 [ set salinity salinity + 0.1
set logging logging - 0.05]
[set salinity salinity + .05
set logging logging + 0.05 ]] [set salinity salinity - 0.05
set logging logging + 0.1]]]
set gw gw - 1
end
to update-gw-use
set salinity salinity + .04
set logging logging + 0.01
set gw gw - 1
set total-gw-cost total-gw-cost + gwcost
end
to calculate-profits
ask farmers [ if ticks mod 630 = 252 [ set total-sw-cost raqba * 500
set watercosts total-gw-cost + total-sw-cost
;update-yield
calculate-season1-profit
]]
ask farmers [ if ticks mod 630 = 0 [ set total-sw-cost raqba * 500
set watercosts total-gw-cost + total-sw-cost
calculate-season2-profit]]
end
to calculate-season1-profit
ask farmers [ set yield yield + ((usedflow / totaldemand ) * alpha + ( gwateruse / totaldemand)* beta) * 55 - 0.1 * (55 * salinity / 12) - 0.1 *(55 * logging / 12) ; 55mon/acre market price
let price 1350 ; price/ maund
set season1-profit yield * price - watercosts
]
end
to calculate-season2-profit
ask Farmers[ set yield yield + ((usedflow / totaldemand ) * alpha + (gwateruse / totaldemand)* beta ) * 100 - 0.1 * (100 * salinity / 18) - 0.1 * (100 * logging / 18) ; 100 mauns/acre market price
let price 2500 ; price/ maund
set season2-profit yield * price - watercosts]
end
to update-output
set-current-plot "Available-surface-water"
set-current-plot-pen _clarify-duplicate-plot-pen-name "Farmer 1" ifelse ticks > 0 [plot [swh] of turtle 0] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 2" ifelse ticks > 0 [plot [swh] of turtle 1] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 3" ifelse ticks > 0 [plot [swh] of turtle 2] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 4" ifelse ticks > 0 [plot [swh] of turtle 3] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 5" ifelse ticks > 0 [plot [swh] of turtle 4] [plot 0]
set-current-plot "Logging"
set-current-plot-pen _clarify-duplicate-plot-pen-name "Farmer 1" ifelse ticks > 0 [plot [logging] of turtle 0] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 2" ifelse ticks > 0 [plot [logging] of turtle 1] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 3" ifelse ticks > 0 [plot [logging] of turtle 2] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 4" ifelse ticks > 0 [plot [logging] of turtle 3] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 5" ifelse ticks > 0 [plot [logging] of turtle 4] [plot 0]
set-current-plot "Salinity"
set-current-plot-pen _clarify-duplicate-plot-pen-name "Farmer 1" ifelse ticks > 0 [plot [salinity] of turtle 0] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 2" ifelse ticks > 0 [plot [salinity] of turtle 1] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 3" ifelse ticks > 0 [plot [salinity] of turtle 2] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 4" ifelse ticks > 0 [plot [salinity] of turtle 3] [plot 0]
set-current-plot-pen _clarify-duplicate-plot-pen-name "farmer 5" ifelse ticks > 0 [plot [salinity] of turtle 4] [plot 0]
end
to import-data
ifelse ( file-exists? "totannual-wdischarge.txt" )
[
set totannual-wdischarge []
file-open "totannual-wdischarge.txt"
while [ not file-at-end? ]
[
set totannual-wdischarge sentence totannual-wdischarge (list file-read)
]
file-close
]
[ user-message "There is no totannual-wdischarge.txt file in current directory!" ]
;; Import water demand
ifelse ( file-exists? "IWR-perday.txt" )
[
set IWR-perday []
file-open "IWR-perday.txt"
while [ not file-at-end? ]
[
set IWR-perday sentence IWR-perday (list file-read)
]
file-close
]
[ user-message "There is no IWR-perday.txt file in current directory!" ]
end
to-report _clarify-duplicate-plot-pen-name [ name ]
let name-map [["Min" "Min"] ["MIn" "MIn_1"]]
let replacement filter [ rename -> first rename = name] name-map
let reported-name name
if not empty? replacement [
set reported-name item 1 replacement
]
report reported-name
end
The plots are working, it's just that they are showing 0. My best guess is that the text you have inside the chooser for the options is different than the text you are testing in your if statement, so the if statement is always false.
Try something like this:
ifelse water-use-mangement = "Business as usual"
[ ; all your irrigation code that you already have
]
[ print "ERROR: Management case not found"
]
This will print an error message if the text doesn't match.
I am simulating a classroom to find the total energy consumption from appliances of a classroom. Now I want to run the simulation in BehaviorSpace so that I get the energy consumption (energy-calculation) by varying the number of students in the classroom.
globals[
temp1 simulation-timer number-of-seats number-of-lights
number-of-fans number-of-acs gap row col x-cor y-cor half half2
student-no t-light t-fan t-ac t-energy
]
breed [seats seat]
breed [seat-teachers seat-teacher]
breed [lights light]
breed [fans fan]
breed [acs ac ]
breed [students student ]
seats-own [
seat-color
occupied?
]
seat-teachers-own [
seat-color
]
students-own [
entry-time
found-seat
]
lights-own [
l-energy
]
fans-own [
f-energy
]
acs-own [
a-energy
]
to setup
clear-all
ask patches [ set pcolor 9 ]
set gap floor ((max-pxcor) / (no-of-row-or-col) )
set half ceiling (gap / 2)
set half2 floor (gap / 2)
place-seat-teachers
place-seats-students
place-lights
place-fans
place-acs
ask patches with [ pxcor = 3 * gap + half2 ] [ set pcolor 4 ]
ask patches with [ pxcor = 6 * gap + half2 ] [ set pcolor 4 ]
create-students-classroom
reset-ticks
reset-timer
end
to place-seat-teachers
create-seat-teachers 1 [
setxy ((max-pxcor - min-pxcor) / 2) 1
set shape "square"
set size 3
set color red
]
end
to place-seats-students
set row gap
set col gap
set x-cor 0
set y-cor 0
while [ x-cor <= gap * no-of-row ]
[
ifelse (x-cor = row)[
set col gap
set y-cor 0
while [ y-cor <= gap * no-of-row-or-col ]
[
ifelse (y-cor = col)[
create-seats 1 [
set shape "square"
set size 1.5
set color blue
setxy col row
set label who
set number-of-seats number-of-seats + 1
show (word row ", " col )
]
set col col + gap
set y-cor y-cor + 1
]
[set y-cor y-cor + 1]
]
set row row + gap
set x-cor x-cor + 1
]
[set x-cor x-cor + 1]
]
end
to place-lights
set row gap + half2
set col gap + half
set x-cor 0
set y-cor 0
while [ x-cor <= gap * no-of-row-or-col ]
[
ifelse (x-cor = row)[
set col gap + half
set y-cor 0
while [ y-cor <= gap * no-of-row ]
[
ifelse (y-cor = col)[
create-lights 1 [
set shape "pentagon"
set size 1
set color red
setxy row col
set number-of-lights number-of-lights + 1
show (word row "," col )
]
set col col + ( gap * 2)
set y-cor y-cor + 1
]
[set y-cor y-cor + 1]
]
set row row + ( gap * 2)
set x-cor x-cor + 1
]
[set x-cor x-cor + 1]
]
end
to place-fans
set row ( gap * 2 ) + half2
set col gap + half
set x-cor 0
set y-cor 0
while [ x-cor <= ( gap * no-of-row-or-col ) ]
[
ifelse (x-cor = row)[
set col gap + half
set y-cor 0
while [ y-cor <= ( gap * no-of-row ) ]
[
ifelse (y-cor = col)[
create-fans 1 [
set shape "x" ;; x shape
set size 1
set color red
setxy row col
set number-of-fans number-of-fans + 1
show (word row "," col )
]
set col col + ( gap * 2)
set y-cor y-cor + 1
]
[set y-cor y-cor + 1]
]
set row row + ( gap * 2)
set x-cor x-cor + 1
]
[set x-cor x-cor + 1]
]
end
to place-acs
set row 3
set col 13
set x-cor 0
set y-cor 0
while [ y-cor <= 45 ]
[
ifelse (y-cor = col)[
create-acs 1 [
set shape "star" ;; star shape
set size 1
set color red
setxy row col
set number-of-acs number-of-acs + 1
show (word row "," col )
]
set col col + 10
set y-cor y-cor + 1
]
[set y-cor y-cor + 1]
]
end
to go
set simulation-timer 0
output-show (word "timer = "simulation-timer )
tick
move-students
while [simulation-timer < time ] [
set simulation-timer simulation-timer + 1
output-show (word "timer = "simulation-timer )
]
end
to create-students-classroom
create-students number-of-students [
set entry-time random threshold + 1
let stu-no sort-on [who] students
foreach stu-no [x -> ask x [ show (word x " -> " entry-time ) ]
]
set shape "person"
set color 3
]
end
to move-students
let s sort [who] of seats
let a first s
let l length s
while [ l > (number-of-seats - number-of-students )] [
set temp1 simulation-timer
tick
tick
ask students [ if ( entry-time = temp1 )
[
move-to seat a ; If it does the student moves to a seat
set color red
appliance-on
energy-calculation
show (word temp1 "," l "," a)
set s remove a s
set a a + 1
set l length s
]
]
set simulation-timer simulation-timer + 1
output-show (word "timer = "simulation-timer )
]
end
to appliance-on
ask students [ ask lights in-radius 4
[ set color green ]]
ask students [ ask fans in-radius 4
[ set color green ]]
ask students [ ask acs in-radius 9
[ set color green ]]
stop
end
to energy-calculation
ask lights [ ifelse ( color = green ) [ set l-energy ( light-
wattage * (time - temp1 )) ] [ set l-energy 0 ] ]
ask fans [ ifelse ( color = green ) [ set f-energy ( fan-wattage
* ( time - temp1 )) ] [ set f-energy 0 ] ]
ask acs [ ifelse ( color = green ) [ set a-energy (ac-wattage *
(time - temp1 ))] [ set a-energy 0 ] ]
let light-e sum [l-energy] of lights
let fan-e sum [f-energy] of fans
let ac-e sum [a-energy] of acs
set t-light ( light-e / 60 )
set t-fan (fan-e / 60 )
set t-ac (ac-e / 60 )
show (word "total-ac-time = " t-ac )
set t-energy ( t-light + t-fan + t-ac )
end
In the BehaviorSpace: measure runs using these reporters I am putting energy-calculation but in the spreadsheet everything is showing zero. Why is this happening? When I am seeing the energy-calculation in a monitor it shows a value. What I want to do is run this code several times with different student numbers and get the varied energy-calculation each time. Or should I use file save in .csv for this situation?
You have written energy-calculation as a command that sets the global variable t-energy rather than as a reported that reports t-energy to the caller. I suspect that in your monitor you have used the t-energy variable which is reset each time energy-calculation is called. But in BehaviorSpace, the reporter by which runs are measured must actually be a reporter. It must return a value to BehaviorSpace. This is easily done by rewriting energy-calculation as
to-report energy-calculation
ask lights [ ifelse ( color = green ) [ set l-energy ( light-
wattage * (time - temp1 )) ] [ set l-energy 0 ] ]
ask fans [ ifelse ( color = green ) [ set f-energy ( fan-wattage
* ( time - temp1 )) ] [ set f-energy 0 ] ]
ask acs [ ifelse ( color = green ) [ set a-energy (ac-wattage *
(time - temp1 ))] [ set a-energy 0 ] ]
let light-e sum [l-energy] of lights
let fan-e sum [f-energy] of fans
let ac-e sum [a-energy] of acs
set t-light ( light-e / 60 )
set t-fan (fan-e / 60 )
set t-ac (ac-e / 60 )
show (word "total-ac-time = " t-ac )
set t-energy ( t-light + t-fan + t-ac )
report t-energy
end
Whether or not you still need the global t-energy or can simply replace it with the reporter that reports its value, would depend on how else t-energy is used in the code.
But, I am actually surprised that the BehaviorSpace experiment tries to run at all. BehaviorSpace should catch that energy-calculation is not a reporter and throw an error.
I'm trying to create an own ecosystem and have already written about 100 lines of code. But I'm currently getting an annoying error message [Title] I cannot get rid of unless I delete the line with the «Tick» command.
That's how the Interface looks like at the moment
That's how the Interface looked like after the latest successful simulation
That's the defective Code:
turtles-own [saturation age gender]
breed [sheep a-sheep]
sheep-own [love-cooldown-sheep-f love-cooldown-sheep-m age%-sheep]
globals [tick-stopper]
patches-own [Next-to]
to setup
clear-all
setup-patches
setup-sheep
set tick-stopper 0
reset-ticks
end
to setup-patches
ask patches [ set pcolor green ]
end
to setup-sheep
create-sheep number_of_sheep [set saturation max-saturation-sheep set gender random 2 set shape "sheep" set age 0]
if setup-sheep-random-age? [
ask turtles with [shape = "sheep"] [set age random life-exp.-sheep]
]
ask turtles with [shape = "sheep"] [
setxy random-xcor random-ycor
if gender = 0 [
set color 118
]
if gender = 1 [
set color 98
]
]
end
to go
if tick-stopper >= stop-at-tick and stop-at-tick? [
set tick-stopper 0
stop
]
move-sheep
sheep-eat-grass
make-love-sheep
check-death-sheep
regrow-grass
set tick-stopper tick-stopper + 1
tick
end
to move-sheep
ask turtles with [shape = "sheep"] [
right random 60
left random 60
forward 1
set saturation saturation - 1
set age age + (((random life-exp.-sheep) + 1) / ((life-exp.-sheep + 1)/ 2))
if gender = 0 and love-cooldown-sheep-f > 0 [
set love-cooldown-sheep-f love-cooldown-sheep-f - 1
set saturation (saturation - (saturation-loss-til-birth-sheep / contribution-period-sheep))
]
]
if gender = 1 [
if love-cooldown-sheep-m > 0 [
set love-cooldown-sheep-m love-cooldown-sheep-m - 1
]
]
end
to sheep-eat-grass
ask turtles with [shape = "sheep"] [
if pcolor = green and saturation < max-saturation-sheep [
set pcolor brown
set saturation saturation + saturation-from-grass
]
ifelse show-saturation?
[ set label saturation ]
[ set label "" ]
]
end
to make-love-sheep
ask turtles with [shape = "sheep"] [
if gender = 0 and love-cooldown-sheep-f = 1 [hatch 1 [set saturation birth-saturation-sheep set gender random 2 set age 0
if gender = 0 [set color 118]
if gender = 1 [set color 98]
if gender = 1 and love-cooldown-sheep-m = 0 and saturation > saturation-for-love-sheep and 1 = count turtles with [shape = "sheep" and gender = 0 and love-cooldown-sheep-f = 0 and saturation > saturation-for-birth-sheep] in-radius 1 [
set saturation saturation - saturation-loss-at-love-sheep
set love-cooldown-sheep-m cooldown-for-love-sheep
ask turtles with [shape = "sheep"] in-radius 1 [
if gender = 0 and saturation > saturation-for-birth-sheep and love-cooldown-sheep-f = 0 [set love-cooldown-sheep-f contribution-period-sheep]
]
]
]
]
]
end
to check-death-sheep
ask turtles with [shape = "sheep"] [
set age%-sheep (100 * (age / life-exp.-sheep))
if saturation <= 0 [die]
if age%-sheep < 22.5039287 [
if (10 ^(0.00984 *(age%-sheep ^ 2) - 0.25918 * age%-sheep + 2.922))/ life-exp.-sheep > random 10000 [die]
]
if age%-sheep > 156.24733 [
if 10000 / (life-exp.-sheep / 100) > random 10000 [die]
]
if age%-sheep > 22.5039287 and age%-sheep < 156.24733 [
if (10 ^(1.899801588 -(((16 / 75 * (age%-sheep ^ 3)) - (50 * (age%-sheep ^ 2))) / 131250)))/ life-exp.-sheep > (random 10000) [die]
]
]
end
to regrow-grass
ask patches with [pcolor = brown] [
set next-to count neighbors4 with [pcolor = green]
if (random 1000000 / 10000) <= (grass-growth% * count neighbors4 with [pcolor = green]) [set pcolor green]
]
end
Thanks for your help <3
This is my first project with NetLogo 6.0.4 and it isn't planned to start any other projects after this one.
You have a bracketing problem in your move-sheep procedure. You have a structure like this:
to move-sheep
ask turtles with [shape = "sheep"]
[ right random 60
...
if gender = 0 and love-cooldown-sheep-f > 0
[
]
]
if gender = 1
[ if love-cooldown-sheep-m > 0
[ set love-cooldown-sheep-m love-cooldown-sheep-m - 1
]
]
end
So you accidentally closed the ask turtles before dealing with the if gender = 1. As soon as you have if gender = 1 then it switches to turtle context.
[
globals [ gl_my-car gl_cars-count gl_accelerator gl_decelerator gl_speed-max gl_speed-min gl_speed-maxcircle gl_speed-maxright gl_distance-straight
gl_distance-left gl_distance-right gl_degree-per-foot gl_side gl_slowdown gl_straightdistance
gl_distanceto00 gl_carminseparation gl_reactiontime
gl_motospeed-max gl_my-moto gl_moto-count
gl_truckspeed-max gl_my-truck gl_truck-count
gl_busspeed-max gl_my-bus gl_bus-count
gl_motominseparation gl_truckminseparation gl_busminseparation
]
breed [cartop car]
breed [mototopview moto]
breed [trucktopview truck]
breed [bustopview bus]
turtles-own [
speed droundabout headingdirection
lane
]
to setup
clear-all
set gl_cars-count 0
; 100 ticks per second
set gl_moto-count 0
set gl_truck-count 0
set gl_bus-count 0
set gl_accelerator 0.001 ; 10 ft per second per second
set gl_decelerator 0.001 ; 10 ft per second per second
set gl_speed-max 0.5133333333333 ; 35mph, 51.3333 ft per second
set gl_speed-min 1.e-10
set gl_speed-maxcircle gl_speed-max * 0.5 ; half normal speed
set gl_speed-maxright gl_speed-max * 0.62 ; about 60% normal speed
set gl_distance-straight 34.77
set gl_distance-left 58.34
set gl_distance-right 35.2
set gl_degree-per-foot 3.81972
set gl_side sqrt (15 ^ 2 - 6 ^ 2)
set gl_slowdown (gl_speed-max ^ 2 - gl_speed-maxcircle ^ 2) / (2 * (gl_decelerator))
set gl_straightdistance gl_slowdown + gl_side
set gl_distanceto00 sqrt (gl_straightdistance ^ 2 + 6 ^ 2)
set gl_carminseparation 15; assume car lenght 10' & distance between cars 5'
set gl_motominseparation 10
set gl_truckminseparation 20
set gl_busminseparation 25
set gl_reactiontime 100; 100 ticks or 1 second reaction time
;;;tao xe oto
create-cartop NumberCartop
[
set color (random 3 * 40 + 15) ; 15=red=go right, 55=green=go straight, 95=sky=go left
set shape "car top"
set size 5
set speed gl_speed-max - random-float .1 ;;thhiet lap hinh dang xe và bao cao vi tri
set droundabout 0
set headingdirection 0
distribute-cars
]
;;;;tao xe may
create-mototopview Numbermotos
[
set color (random 3 * 40 + 15 )
set shape "motortopview"
set size 3
set speed gl_motospeed-max - random-float .1 ;;thhiet lap hinh dang xe và bao cao vi tri
set droundabout 0
set headingdirection 0
distribute-motos
]
;;; tao xe tai
create-trucktopview Numbertruck
[
set color (random 3 * 40 + 15 )
set shape "trucktopview"
set size 7
set speed gl_truckspeed-max - random-float .1 ;;thhiet lap hinh dang xe và bao cao vi tri
set droundabout 0
set headingdirection 0
distribute-truck
]
;; tao xe bus
create-bustopview Numberbus
[
set color (random 3 * 40 + 15 )
set shape "bustopview"
set size 7
set speed gl_busspeed-max - random-float .1 ;;thhiet lap hinh dang xe và bao cao vi tri
set droundabout 0
set headingdirection 0
distribute-bus
]
set gl_my-car one-of cartop
watch gl_my-car
set gl_my-moto one-of mototopview
watch gl_my-moto
set gl_my-truck one-of trucktopview
watch gl_my-truck
set gl_my-bus one-of bustopview
watch gl_my-bus
ask patches
[
;;;tao vong xuyen
if (pxcor ^ 2 + pycor ^ 2 < 35 ^ 2) and (pxcor ^ 2 + pycor ^ 2 > 10 ^ 2)
[
set pcolor grey
]
;;;;tao cay xanh trong vong xuyen
if (pxcor ^ 2 + pycor ^ 2 < 7 ^ 2) and (pxcor ^ 2 + pycor ^ 2 > 0 ^ 2)
[
set pcolor blue
]
;;;; tao duong phan van tri
if abs (pxcor) > 0 and abs (pxcor) < 7 and (pxcor ^ 2 + pycor ^ 2 > 10 ^ 2)
[
set pcolor grey
]
;;;tao giai phan cach giua duong pham van dong
if abs (pycor) >= 0 and abs (pycor) <= 1.5 and (abs (pxcor) > 35)
[
set pcolor yellow
]
;;;tao lan oto duong pham van dong
if abs (pycor) > 1.5 and abs (pycor) < 17 and (pxcor ^ 2 + pycor ^ 2 > 10 ^ 2)
[
set pcolor grey
]
;;tao dai phan cach lan xe may duong pham van dong
if abs (pycor) >= 17 and abs (pycor) <= 19 and (abs (pxcor) > 35)
[
set pcolor yellow
]
;;;tao lan xe may duong pham van dong
if abs (pycor) > 19 and abs (pycor) < 26 and (pxcor ^ 2 + pycor ^ 2 > 10 ^ 2)
[
set pcolor grey
]
;;;tao lan duong re phai pham van dong - phan van tri và phan van tri-pham van dong phia ben duoi
if ((abs (pxcor) - 55 < pycor) and (abs (pxcor) - 35 > pycor) and abs (pxcor) > -10 and pycor < -10)
[
set pcolor grey
]
;;;tao lan duong re phai pham van dong - phan van tri phia ben tren
if (( (- pxcor) + 55 > pycor) and ( (- pxcor) + 35 < pycor) and (pxcor) > 0 and pycor > 10)
[
set pcolor grey
]
;;;tao lan duong re phai phan van tri - pham van dong phia ben tren
if (( ( pxcor) + 55 > pycor) and ( ( pxcor) + 35 < pycor) and (pxcor) < 0 and pycor > 10)
[
set pcolor grey
]
]
reset-ticks
end
;;;phan phoi xe oto
to distribute-cars
set heading random 4 * 90
;;lan phan van tri ben phai
if (heading = 0)
[setxy (1 + random(pxcor + 6)) (40 + random (max-pycor - 30)) * (2 * random 2 - 1)]
;;lan phan van tri ben trai
if (heading = 180)
[setxy (-1 + random(pxcor - 6)) ((40 + random (max-pycor - 30)) * (2 * random 2 - 1))]
;;lan pham van dong ben duoi
if (heading = 90)
[setxy ((40 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (-3 + random(pycor - 13 ))]
;;;lan pham van dong ben tren
if (heading = 270)
[setxy ((40 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (3 + random(pycor + 13 ))]
if any? other turtles-here
[distribute-cars ]
end
;;;phan phoi xe may
to distribute-motos
set heading random 4 * 90
;;;lan phan van tri ben phai
if (heading = 0)
[setxy (1 + random(pycor + 6)) (40 + random (max-pycor - 30)) * (2 * random 2 - 1)]
;;lan pham van dong ben duoi
if (heading = 90)
[setxy ((40 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (-20 + random(pycor - 6 ))]
;;lan phan van tri ben trai
if (heading = 180)
[setxy (-1 + random(pycor - 6)) ((40 + random (max-pycor - 30)) * (2 * random 2 - 1))]
;;;lan pham van dong ben tren
if (heading = 270)
[setxy ((40 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (20 + random(pycor + 6 ))]
if any? other turtles-here
[distribute-motos ]
end
;;;phan phoi xe tai
to distribute-truck
set heading random 4 * 90
;;lan phan van tri ben phai
if (heading = 0)
[setxy (1 + random(pxcor + 6)) (60 + random (max-pycor - 30)) * (2 * random 2 - 1)]
;;lan phan van tri ben trai
if (heading = 180)
[setxy (-1 + random(pxcor - 6)) ((60 + random (max-pycor - 30)) * (2 * random 2 - 1))]
;;lan pham van dong ben duoi
if (heading = 90)
[setxy ((60 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (-3 + random(pycor - 13 ))]
;;;lan pham van dong ben tren
if (heading = 270)
[setxy ((60 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (3 + random(pycor + 13 ))]
if any? other turtles-here
[distribute-truck ]
end
;;;phan phoi xe buyt
to distribute-bus
set heading random 4 * 90
;;lan phan van tri ben phai
if (heading = 0)
[setxy (1 + random(pxcor + 6)) (60 + random (max-pycor - 30)) * (2 * random 2 - 1)]
;;lan phan van tri ben trai
if (heading = 180)
[setxy (-1 + random(pxcor - 6)) ((60 + random (max-pycor - 30)) * (2 * random 2 - 1))]
;;lan pham van dong ben duoi
if (heading = 90)
[setxy ((60 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (-3 + random(pycor - 13 ))]
;;;lan pham van dong ben tren
if (heading = 270)
[setxy ((60 + random (max-pxcor - 38)) * (2 * random 2 - 1)) (3 + random(pycor + 13 ))]
if any? other turtles-here
[distribute-bus ]
end
to go
ask cartop [goallcar]
ask mototopview [goallmoto]
ask trucktopview [goalltruck]
ask bustopview [goallbus]
tick
if ticks > 30000 [stop]
end
to goallcar
let myhd heading
set headingdirection (subtract-headings myhd (towardsxy 0 0))
ifelse color = red and distancexy 0 0 < 31.7
[
goright
]
[
ifelse distancexy 0 0 <= 15
[
gostraightleft
]
[
gomainroad
]
]
plot [speed] of gl_my-car * 360000 / 5280 ; convert from feet per tick to mph
end
to goright
; if [ pcolor ] of patch-ahead 23 != grey
if headingdirection > 0 and headingdirection < 40 ; begin right turn
[
set gl_cars-count gl_cars-count + 1
set droundabout 0
;;;rt 45
if heading = 90
[
;; ask cars
if distancexy 0 0 = -55 and distancexy 0 0 = 55
[
rt 50
if pycor = -20
[
rt 90
]
]
]
rt 45
]
ifelse droundabout < gl_distance-right
[
let myhd heading
let d gl_distance-right - droundabout
ifelse d > 12
[
let t d / speed
let cars-45degrees cartop with [(subtract-headings heading myhd = 45) and (distance myself < 52.35)]
let cars-ininterval cars-45degrees with [(distancexy 0 0) + speed * t > 15 and (distancexy 0 0) +
speed * t < 46.39]
ifelse any? cars-ininterval
[
let deceleration-to-stop (speed ^ 2 / (2 * (d - 12)))
set speed speed - deceleration-to-stop
]
[
set speed speed + gl_accelerator
]
]
[
set speed speed + gl_accelerator
]
if (speed > gl_speed-maxright) [set speed gl_speed-maxright]
if (speed < gl_speed-min) [set speed gl_speed-min]
; plot [speed] of gl_my-car * 360000 / 5280 ; convert from feet per tick to mph
fd speed
set droundabout droundabout + speed
]
[
; plot [speed] of gl_my-car * 360000 / 5280; convert from feet per tick to mph
rt 45
fd speed
set droundabout 0
readjustcordinate
]
end
to gostraightleft
; if [ pcolor ] of patch-ahead 5 != grey
if droundabout = 0 ; begin roundabout left turn or go straight
[
set gl_cars-count gl_cars-count + 1
set speed gl_speed-maxcircle
set droundabout 0.00001 ; start roundabout
rt 66.422
]
ifelse ((color = sky and droundabout < gl_distance-left ) or (color = green and droundabout <
gl_distance-straight ))
[
let carsinroundabout other cartop with [distancexy 0 0 < 15]
fd speed
lt speed * gl_degree-per-foot
set droundabout droundabout + speed
let d distancexy 0 0 / 14.9999
setxy (xcor / d) (ycor / d)
]
[
; plot [speed] of gl_my-car * 360000 / 5280; convert from feet per tick to mph
rt 66.422
fd speed
set droundabout 0
readjustcordinate
]
end
to gomainroad
let myhd heading
let dfromcenter (distancexy 0 0)
let speed1 speed; save the initial speed for later use
if ( dfromcenter > 15)
[
let dseparation gl_carminseparation + speed * gl_reactiontime
let cars-same-direction other cartop with [heading = myhd]
ifelse any? cars-same-direction
[
let cars-ahead other cars-same-direction with [(distance myself) != 0 and (towards myself) != myhd]
ifelse any? cars-ahead
[
let car-nearest (min-one-of cars-ahead [distance myself])
let dtocar-nearest distance car-nearest
let vofcar-nearest [speed] of car-nearest
ifelse dtocar-nearest < dseparation
[
if speed >= vofcar-nearest
[
set speed speed - gl_decelerator
]
if dtocar-nearest < gl_carminseparation
[
set speed speed - gl_decelerator
if speed >= vofcar-nearest
[ set speed vofcar-nearest - gl_decelerator ]
]
]
[ set speed speed + gl_accelerator ] ; end car-nearest
]
[ set speed speed + gl_accelerator ] ; end cars-ahead
]
[ set speed speed + gl_accelerator ] ; end cars-same-direction
] ; end distancexy 0 0
; if ( (distancexy 0 0) > 15 and (distancexy 0 0) < 16.7)
; [
; let cars-45degree cars with [(subtract-headings heading myhd = -45) ]
; ]
if ( dfromcenter > 25 and dfromcenter < 50 )
[
let d dfromcenter - 25
let t d / speed
let cars-inroundabout cartop with [(distancexy 0 0) <= 15]
let cars-ininterval cars-inroundabout with [(subtract-headings heading myhd > 0 )]
if any? cars-ininterval
[
let deceleration-to-stop (speed ^ 2 / (2 * d))
set speed speed - deceleration-to-stop
]
]
let vmax gl_speed-max
if (dfromcenter < gl_distanceto00)
[
let speed2 speed; save the just calculated speed
set speed speed1; restore the initial speed
ifelse color = red
[
let d sqrt ( dfromcenter ^ 2 - 36) - 31 + gl_distance-right
let t d / speed
let cars-perpendicular cartop with [(subtract-headings heading myhd = 90) and (subtract-headings
(towards myself) myhd < 0)]
let cars-ininterval cars-perpendicular with [(distancexy 0 0) + speed * t > 15 and (distancexy 0 0) +
speed * t < 46.39]
ifelse any? cars-ininterval
[
let deceleration-to-stop (speed ^ 2 / (2 * (d - 12)))
set speed speed - deceleration-to-stop
]
[
set speed speed + gl_accelerator
]
if (speed > speed2) [set speed speed2]
]
[
set speed speed2
]
let dfromcircle sqrt(dfromcenter ^ 2 - 36) - gl_side ; gl_side = sqrt(15^2+6^2)
set vmax sqrt(gl_speed-max ^ 2 - 2 * gl_decelerator * (gl_slowdown - dfromcircle)) ; gl_slowdown = (v^2 - v0^2)/(2a)
]
if vmax > gl_speed-max
[
set vmax gl_speed-max
]
if speed > vmax
[
set speed vmax
]
if speed < gl_speed-min
[
set speed gl_speed-min
]
forward speed
end
;;;;;chay xe moto
to goallmoto
let myhd heading
set headingdirection (subtract-headings myhd (towardsxy 0 0))
ifelse color = red and distancexy 0 0 < 31.7
[
goright
]
[
ifelse distancexy 0 0 <= 15
[
gostraightleft
]
[
gomainroad
]
]
plot [speed] of gl_my-car * 360000 / 5280 ; convert from feet per tick to mph
end
;;;chay xe truck
to goalltruck
let myhd heading
set headingdirection (subtract-headings myhd (towardsxy 0 0))
ifelse color = red and distancexy 0 0 < 31.7
[
goright
]
[
ifelse distancexy 0 0 <= 15
[
gostraightleft
]
[
gomainroad
]
]
plot [speed] of gl_my-car * 360000 / 5280 ; convert from feet per tick to mph
end
;;;chay xe bus
to goallbus
let myhd heading
set headingdirection (subtract-headings myhd (towardsxy 0 0))
ifelse color = red and distancexy 0 0 < 31.7
[
goright
]
[
ifelse distancexy 0 0 <= 15
[
gostraightleft
]
[
gomainroad
]
]
plot [speed] of gl_my-car * 360000 / 5280 ; convert from feet per tick to mph
end
to chuyenlan
distribute-cars
goallcar
;;;if heading = 0 and color = red
;;;[
;; if
;;rt 45
;; if (xcor = -10)
;; ]
;;if any? other turtles-here
;; [chuyenlan ]
;; ]
end
to readjustcordinate
if (heading > 355 or heading < 5)
[
set heading 0
set xcor 6
]
if (heading > 85 and heading < 95)
[
set heading 90
set ycor -6
]
if (heading > 175 and heading < 185)
[
set heading 180
set xcor -6
]
if (heading > 265 and heading < 275)
[
set heading 270
set ycor 6
]
end
]
[![1]
how to write Algorithms running cars. 3-lane road. cheap car left lane 1 and lane 2 car go straight, lanes 3 cheap car right. tạo random initial car. (Low red car on the right, go straight green, sky swerved left). to 1 position if the car red là có all moved to the right lane for cheap car. green car vehicle moving straight to go straight lane, sky car move to the left lane cheap.
revise section drive algorithm. because it runs false
[1]]
how to write Algorithms running cars. 3-lane road. cheap car left lane 1 and lane 2 car go straight, lanes 3 cheap car right. tạo random initial car. (Low red car on the right, go straight green, sky swerved left). to 1 position if the car red là có all moved to the right lane for cheap car. green car vehicle moving straight to go straight lane, sky car move to the left lane cheap.
revise section drive algorithm. because it runs false
[1]
: http://i.stack.imgur.com/59IAs.jpg