Sei sulla pagina 1di 27

Un exemplu de program care creaza un numar de turtles si le misca intr-un loc cu iarba verde, din care mananca.

Sunt doar doua butoane Setup si Go

turtles-own[energy] ;;variabila globala to Setup ;; to si end definesc functia (procedura) clear-all setup-patches setup-turtles reset-ticks end to setup-patches ask patches [ set pcolor green ] end to setup-turtles create-turtles 25 ask turtles [ setxy random-xcor random-ycor ] end to Go move-turtles eat-grass tick end to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy energy + 10 ] ] end to move-turtles ask turtles [ right random 360 forward 1 set energy energy - 1 ] end Programul poate fi dezvoltata prin adaugarea de monitoare, slidere, butoane si plot-uri.

Monitoarele sunt campuri destinate sa afiseze o variabila globala.

Codul asociat cu monitorul e inclus in campul Reporter

Switch-urile se asociaza cu o variabila globala, definita chiar la nivelul switch-ului

Dar aceasta variabila trebuie testata undeva in program. In cazul nostru, asta se face in functia eat-grass

to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy energy + 10 ] ifelse show-energy? [ set label energy ] ;; if show-energy switch is on (condition TRUE) [ set label "" ] ;; is switch is off ] end Interesanta instructiunea ifelse care specifica ambele optiuni si pentru if si pentru else. Interesant si modul de folosire a proprietatii label a obiectelor din clasa turtle. O varianta si mai complexa, in care agentii mananca se inmultesc sau mor, iar iarba creste la loc dupa un timp. Se modifica functia go, astfel:
to go move-turtles eat-grass reproduce check-death regrow-grass tick end

;; sa nu uitam acest tick!!!

Se observa ca au aparaut niste functii noi:


to reproduce ask turtles [ if energy > 50 [ set energy energy - 50 hatch 1 [ set energy 50 ] ] ] end to check-death ask turtles [ if energy <= 0 [ die ] ] end

to regrow-grass ask patches [ if random 100 < 3 [ set pcolor green ] ] end

Observatii: hatch ( a cloci, a scoate pui) este o primitiva Netlogo hatch number [commands] Se pare ca pozitia puiului este implict setata ca random (desi probabil este posibil ca in secventa de comenzi asociata cu hatch sa se specifice si pozitia puiului. die comanda omorarea turtles Plotting Nota: actualizarea plot-urilor se face la tick Vrem sa adaugam o fereastra de plotting in care sa vizualizam evolutia unor variabile. Incepem cu Add plot si definim axele si pen-urile pltului:

Apoi modificam functiile setup si go ca sa apeleze o functie noua do-plots.

turtles-own[energy] to Setup clear-all setup-patches setup-turtles reset-ticks do-plots end to setup-patches ask patches [ set pcolor green ] end to setup-turtles create-turtles 1 ask turtles [ setxy random-xcor random-ycor ] end to go move-turtles eat-grass reproduce check-death regrow-grass tick ;; sa nu uitam acest tick!!!. Daca il omitem, programul ruleaza OK, dar actualizarea imaginii ;; treuie setata pe 'continuous' - daca e pe on tick nu se vede nimic!! do-plots end to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy energy + 10 ] ifelse show-energy? [ set label energy ] ;; do this if switch is on [ set label "" ] ;; do this if switch is off ] end

to move-turtles ask turtles [ right random 360 forward 1 set energy energy - 1 ] end to reproduce ask turtles [ if energy > 50 [ set energy energy - 50 hatch 1 [ set energy 50 ] ] ] end to check-death ask turtles [ if energy <= 0 [ die ] ] end to regrow-grass ask patches [ if random 100 < 5 [ set pcolor green ] ] end to do-plots set-current-plot "Totals" set-current-plot-pen "turtles" plot count turtles set-current-plot-pen "grass" plot count patches with [pcolor = green] end

Tick counter netlogo mentine o variabila globala implicita denumita ticks care se actualizeaza cu numarul de pasi executati. Poate fi testata in program, de exemplu pentru a iesi din bucle
to go if ticks >= 500 [ stop ] move-turtles eat-grass check-death reproduce regrow-grass tick ;; aici se incrementeaza variabila ticks do-plots end

Comanda clear-all reseteaza contorul de tick-uri. Sliders Vrem sa modificam din inetrfata grafica valoarea initiala a numarului de turtles cu care pornim si valoarea energetica a ierbii si energia puilor la nastere. Incepem prin a adauga cele 3 slidere pe care le asociem cu niste variabile globale:

Dupa care modificam un pic codul:


to setup-turtles create-turtles number ask turtles [ setxy random-xcor random-ycor ] end to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy (energy + energy-from-grass) ]

ifelse show-energy? [ set label energy ] [ set label "" ] ] end


to reproduce ask turtles [ if energy > birth-energy [ set energy energy - birth-energy hatch 1 [ set energy birth-energy ] ] ] end

Despre BREED (rasa, specie) In continuare analizez si comentez exemplu de cod Breeds and shapes din sectiunea Code Examples Pornim de la o interfata de genul asta:

Speciile (breeds) se definesc la inceputul zonei de cod inainte de orice procedura. breed [monsters monster] breed [fish a-fish] ;; the word "fish" is both singular and plural, ;; so we need to use something different for ;; the singular form breed [humans human] ;; bag si niste oameni breed [rate o-rata] ;; si niste rate

Popularea cu turtles se face - in acest exemplu cu comanda sprout (a rasari, a germina) care e asociata cu patches.

to setup clear-all set-default-shape monsters "monster" set-default-shape fish "fish" set-default-shape humans "boy" set-default-shape rate "bird2"

;; clear all patches and turtles ;; shape is defined in Turtle Shapes Editor ;; ditto

ask patches with [pxcor = 0] [ ;; just the middle column of patches ifelse random 2 = 0 ;; flip a coin [ sprout-monsters 1 ] [ sprout-fish 1 ] ] ask patches with [pxcor = -1] [ if random 2 = 1 [ sprout-humans 1 ] ] ask turtles [ ;; includes both monsters and fish set heading 90 ;; face east ] ask patches with [ pxcor > 5 and pycor > 4 ] [sprout-rate 1] end

Comenzile de miscare: to move-monsters ;; ask monsters [ fd 1 ] ask monsters [ back random 3 ] end to move-fish ask fish [ fd 1 ] tick end

;; echivalent cu [ forward 1 ]

to move-humans ask humans [ fd 1] ask humans [ if xcor > 4 [set shape "girl" ] ] tick end

Recapitulare: - Pentru generarea/nasterea turtles am gasit 3 metode: a. cu comanda create-turtles how_many [commands...] Observatii importante 1. Daca am definit o serie de breeds atunci putem invoca comanda createturtles sub forma: create-breed_name De exemplu: create-humans 25 [set color green] - Agentii creati cu comanda create-turtles sunt pusi unul peste altul in patch-ul cu coordonatele xcor=0 si ycor=0!! - Ca sa-i dispersam e nevoie de ceva de genul urmator: create-humans 5 [ask humans [ setxy random-xcor random-ycor ] ] ceea ce este echivalent cu: create-humans 5 ask humans [ setxy random-xcor random-ycor ] 2. Forma (shape) agentilor se stabileste cu comanda: set-default-shape humans "boy" ;; denumirea formei pedefinite

b. Cu comanda sprout-<breed_name> sprout-turtles how_many Comanda sprout este asociata cu patch-urile ( sprout inseamna a germina, a inmuguri, a da rod) deci trebuie invocata musai intr-un context de tipul:
ask patches with [pxcor = 0] [ ;; just the middle column of patches ifelse random 2 = 0 ;; flip a coin [ sprout-monsters 1 ] [ sprout-fish 1 ] ]

c. Cu comanda hatch how_many [ commands ] Asta este asociata cu turtles (hatch inseamna a cloci, a face pui, a ecloza) si trebuie invocata intr-un context de tipul ask turtles Exemplu:
to reproduce ask turtles [ if energy > 50 [ set energy energy - 50 hatch 1 [ set energy 50 ] ] ] end

Pentru disparitia/moartea turtles exista urmatoarele posibilitati: - comanda [ die ] invocata cu ask turtles, de exemplu: ask turtles [if age > 50 die] comanda clear-<breed_name> omoara toata specia si reseteaza contorul who

Pentru sistematizarea ideilor, facem un nou proiect denumit Miscari elementare Gui-ul arata asa:

Si codul complet (lucrurile demne de atentie sunt marcate cu rosu): breed [arrows arrow] to setup clear-all ;; clear all patches and turtles set-default-shape arrows "arrow" create-arrows 5 [ask arrows [ setxy random-xcor random-ycor ] ] ask arrows [ set color red ] ask turtles [ ;; includes both monsters and fish set heading random 360 ;; zero grade inseamna in sus!! ] end

to rotate-left ask arrows [ left 10 ] tick end to rotate-right ask arrows [ right 10 ] tick end to Move-forward ask arrows [ fd 0.5 ] tick end to Move-back ask arrows [bk 0.5] tick end

;;grade

;; se poate misca si cu mai putin de o unitate per tick

;; se poate misca si cu mai putin de o unitate per tick

to auto ask arrows [ left random 100 ] ask arrows [ fd 0.5 ] tick end

Miscari elementare 2 Adaugam un slider care defineste si controleaza variabila globala speed .

Observatie: Nu este nevoie sa redefinim in cod variabila globala asociata cu sliderul. Va fi recunoscuta automat. Procedura asociata cu butonul Auto se executa repetat, datorita unei proprietati a butonului (exista un check-boc denumit Forever). Codul se modifica in felul urmator: to Move-forward ask arrows [ fd speed ] tick end to Move-back ask arrows [bk speed] tick end to auto ask arrows [ left random 100 ] ask arrows [ fd speed ] tick end Cate ceva despre adresarea individuala a agentilor Cream un nou proiect denumit 3.Miscari elementare.nlogo, cu interfata grafica:

Si codul asta:
breed [arrows arrow] arrows-own [ speed ] to setup clear-all ;; clear all patches and turtles set-default-shape arrows "arrow" create-arrows 3 [ask arrows [ setxy random-xcor random-ycor ] ] ask arrows [ set color red ] ask turtles [ ;; includes both monsters and fish set heading random 360 ] end to rotate-left ask arrows [ left 10 ] tick end to rotate-right ask arrows [ right 10 ] tick end to auto ask arrows [ left random 100 ] ask arrows [ fd speed ] ask arrow 1 [ show speed ] tick end

Sunt cateva elemente noi aici: 1. Speed este o proprietate a agentilor individuali, definita imediat dupa breed.
arrows-own [ speed ]

2. Cand am definit butoanele, le-am asociat direct o bucatica de cod ca in figura:

3. Comanda show afiseaza un mesaj (valoarea unei variabile de exemplu, in fereastra de dialog din josul ferestrei de lucru) In continuare sunt de analizat comenzile:

towards towardsxy turtle turtles turtle-set turtles-at turtles-on print show write
Pornesc de la informatiile din manual si construiesc mici proiecte care sa ilustreze functiile respective. Nota: Netlogo permite file I/O, de exemplu citirea unor configuratii de patches dintrun fisier. Neighborhoods example Interfata grafica arata asa:

Exista doua noutati evidente in interfata asta: Un text informativ static - note (Add, note) Un cooser (drop down menu) care permite initializarea unei variabile globale cu valori numerice sau string. In exemplul considerat e o variabila string. Procedurile asociate cu butoanele au si ele o serie de particularitati interesante: to setup ca ;; echivalent cu clear-all crt 8 ;; echivalent cu create 8 [ fd 10 ] ;; comanda inclusa in create ask turtle 0 [ fd 7 ] ask turtle 1 [ fd 14 ] ask turtle 2 [ fd 7 ] end Modul de functionare a acestei proceduri: se simuleaza o distributie random a celor 8 turtles. Comanda crt 8 creaza 8 turtles pe care le pune gramada in origine. Ele au totusi headinguri random, asa ca urmatoarea comanda [ forward 10 ] le muta pe toate inainte pe directia initiala a fiecareia. Rezulta o distributie destul de random. Restul procedurilor sunt destinate sa ilustreze ideea de vecinatate se coloreaza patchurile din vecinatate, cu precizarea ca vecinatatea e definita in mai multe moduri. Colorarea efectiva se face cu functia auxiliara paint-agents [ agents ] : to paint-agents [agents] ask agents [ set pcolor [color] of myself + 2 ] end Aici avem nise noutati: - Procedura are un parametru de intrare: [agents] - apelarea ei se face in urmatoarele moduri: a. Se specifica pur si simplu o lista de agenti ca in exemplul urmator: paint-agents patches at-points [[1 1] [-1 1] [-1 -1] [1 -1 ]] (nota: adresarea path-urilor in exemplul de mai sus este relativa la un punct curent. vezi mai departe) In afara de at-points, definirea subseturilor de agenti se mai poate face si cu operatori i: with, at-points, in-radius, in-cone ;; reporters b. ask turtles [ paint-agents patches in-radius radius ] c. ask turtles [ paint-agents neighbors4 ]

Codul complet: ;; This procedure creates 8 turtles in puts them in a circle, ;; and moves three to the edges of the world
to setup ca crt 8 [ fd 10 ] ask turtle ask turtle ask turtle ask turtle ask turtle ask turtle ask turtle ask turtle ask turtle ask turtle ask turtle end

0 1 2 0 1 2 3 4 5 6 7

[ [ [ [ [ [ [ [ [ [ [

fd 7 ] fd 14 ] fd 7 ] set color set color set color set color set color set color set color set color

red ] yellow ] green ] blue ] gray ] cyan ] magenta ] white ]

;; This procedure colors all the patches neighboring each turtle. ;; neighbors reports the eight patches surrounding the turtle. ;; Note that patches have neighbors as well, and can also use the neighbors reporter.
to paint-neighbors clear-patches ask turtles [ paint-agents neighbors ] end
;; ;; ;; ;; This procedure is similar to paint-neighbors, but uses the neighbors4 reporter. neighbors4 reports only the four patches adjacent to the current patch, and does not include the four neighbors which are only diagonally touching the current patch. As with neighbors, both turtles and patches can use neighbors4.

to paint-neighbors4 clear-patches ask turtles [ paint-agents neighbors4 ] end ;; This procedure uses in-radius to paint a "circle" around each turtle. ;; "agentset in-radius n" reports those agents in agentset whose distance from the current agent ;; is less than or equal to n. For patches, distance is measured from the center of the patch. ;; Note that the caller can be a turtle or a patch, and agentset can be a set of turtles or a set of ;; patches, so you can also use in-radius to locate turtles within a given radius ;; of another turtle or patch. Also notice that the reported agentset includes the patch ;; that the turtle is currently on.

to paint-in-radius clear-patches ask turtles [ paint-agents patches in-radius radius ] end

;; ;; ;; ;;

This procedure uses the at-points reporter to paint an arbitrary neighborhood. at-points lets you specify groups of agents on individual patches, using points relative to the calling agent (so [0 0] indicates the patch the agent is on). As with the above primitives, at-points can be used by both turtles and patches.

to paint-at-points clear-patches ask turtles [ if points = "corners" [ paint-agents patches at-points [[1 1] [-1 1] [-1 -1] [1 -1 ]] ] if points = "left" [ paint-agents patches at-points [[-1 1] [-1 0] [-1 -1]] ] if points = "L-shape" [ paint-agents patches at-points [[-1 1] [-1 0] [-1 -1] [0 -1] [1 -1 ]]] if points = "line-up" [ paint-agents patches at-points [[0 1] [0 2] [0 3] [0 4]] ] ] end

;; This is a helper procedure, used to set the color of a set of patches.


to paint-agents [agents] ask agents [ set pcolor [color] of myself + 2 ] end

Note: Ideea de neighborhood (neighbor, neighbor4) se refera doar la patches. Nu e clar cum functioneaza paint-agents

Am rescris-o asa: to paint-agents [which_agents] ask which_agents [ set pcolor [color] of myself + 2 ] end Si merge. Daca inlocuiesc myself cu self da eroare. In schimb, daca lansez din command center comanda:

ask turtle 0 [show [color] of self] - merge imi raspunde cu un numar codul culorii ask turtle 0 [show [color] of myself]- da eroare! Explicatia din manual suna asa:
"self" and "myself" are very different. "self" is simple; it means "me". "myself" means "the turtle or patch who asked me to do what I'm doing right now."

Exista un code example denumit "Myself Example" care explica mai multe. Daca elimin parantezele patrate din [color] iar da eroare. Alta informatie extrasa din manual: Formularea:
let new-color color ask turtle 0 [ set color new-color ]

este echivalenta cu:


ask turtle 0 [ set color [color] of myself ]

Am incercat sa lansez asta din centrul de comanda, din perspectiva turtles si merge. Dar tot nu e clar cine e myself. Daca lansez tot din perspectiva turtles comanda: ask turtle 0 [show color] primesc de N ori acelasi raspuns (N=numarul de turtles definit) Iar comanda show who primeste raspuns de la toti agentii de tip turtle. Din perspectiva observer, pot intreba: show [color] of turtle 0 si primesc raspuns. [color] e un reporter, color e o proprietate. Daca intreb show color din perspectiva turtles, primesc N raspunsuri, fiecare turtle isi raporteaza culoarea. Din perspectiva turtles, comenzile: show color show [color] of self produc acelasi rezultat cei N agenti isi raporteaza culoarea. OK mergem mai departe cu exemplele: Box drawing example

Box drawing example

Deci, avem o variabila globala edge definita de un slider si doua proceduri, setupcorner si setup-center Codul are putine noutati:
globals [halfedge] ;; setup procedure for case where point (0,0) is in the center of Box to setup-center ca ;; clear everything set halfedge int (edge / 2) ask patches[ if (pxcor = (- halfedge) and pycor >= (- halfedge) and pycor <= (0 + halfedge) ) [set pcolor blue if ( pxcor = (0 + halfedge) and pycor >= (halfedge) and pycor <= (0 + halfedge) ) [set pcolor blue] if ( pycor = (- halfedge) and pxcor >= (- halfedge) and pxcor <= (0 + halfedge) ) [set pcolor blue] if ( pycor = (0 + halfedge) and pxcor >= (- halfedge) and pxcor <= (0 + halfedge) ) [set pcolor blue] ] end

globals se defineste O SINGURA DATA ca lista de variabile globals [var1] globals [var2]

;; da eroare

globals [ var1 var2] ;; merge si in sfarsit o declaratie normala


set halfedge int (edge / 2)

Breed procedures.nlogo ;;defineste un caine, o pisica si o vaca mari (universul e limitat la 3x3 celule) breed [dogs dog] breed [cats cat] breed [cows cow] to setup clear-all set-default-shape dogs "dog" set-default-shape cats "cat" set-default-shape cows "cow" ask patch 0 1 [ sprout-dogs 1 ] ask patch 0 0 [ sprout-cats 1 ] ask patch 0 -1 [ sprout-cows 1 ] end Asta e perfect echivalent cu (mai putin elegant): breed [dogs dog] breed [cats cat] breed [cows cow] to setup clear-all set-default-shape dogs "dog" set-default-shape cats "cat" set-default-shape cows "cow" create-dogs 1 [set heading 0] ask dogs [fd 1] create-cats 1 create-cows 1 [set heading -180] ask cows [fd 1] end si procedura go to go ;; "turtles" refers to all of the turtles, ;; no matter what breed they are ask turtles [ ;; each turtle takes its breed, adds "-speak" ;; onto it, and then runs that procedure

run word breed "-speak" ] end ;; Here we have the separate procedure definitions ;; for each breed. to dogs-speak ;; dog procedure set label "arf arf!" end to cats-speak ;; cat procedure set label "meow!" end to cows-speak ;; cow procedure set label "mooooo!" end E interesanta smecheria, dar e echivalenta cu: to go ;; "turtles" refers to all of the turtles, ;; no matter what breed they are ask turtles [ if (breed = dogs) [ set label "Ham"] if (breed = cats) [ set label "Miau"] if (breed = cows) [ set label "Muuu"] ] end si la fel de echivalenta cu asta: to go ;; "turtles" refers to all of the turtles, ;; no matter what breed they are ask turtles [ ask dogs [set label "Ham"] ask cats [set label "miau"] ask cows [set label "Muuu!!"] ] end

Un prim exemplu care foloseste agenti de tip link Link Breeds Example.nlogo

Exista o singura procedura in proiect Exemplul asta pare a fi important pentru ca ar putea fi nucleul unei aplicatii in care se construieste o retea neuronala pornind de la un set de agenti conectati intre ei !!
;; every link breed must be declared as either directed or undirected directed-link-breed [red-links red-link] undirected-link-breed [blue-links blue-link] blue-links-own [ weight ] ;; !!link breeds can own variables to setup clear-all create-ordered-turtles 10 [ fd 5 set color gray ] ask n-of 5 turtles [ ;; create-<breed>-with is used to make undirected links create-blue-link-with one-of other turtles [ set color blue set weight random 10 set label weight ] ] ;; different breeds can have different default shapes set-default-shape red-links "curved link" ask n-of 5 turtles [ ;; create-<breed>-to/from are used to make directed links create-red-link-to one-of other turtles [ set color red ] ] end

Cateva lucruri noi, de remarcat aici: ask n-of number [command] Se aplica o comanda unui numar specificat (number) de turtles 1.Hill Climbing Example.nlogo Exemplul asta seamana mult cu ideea de a asocia patch-urile cu o altitudine (stocata in tag-uri RFID) si de a instrui agentii (roboti) sa o ia la vale (downhill). NetLogo are doua functii: uphill si downhill (cu variantele uphill4, downhill4) Care comanda deplasarea agentului (turtle) intr-o casuta (patch) din vecinatate (neighbors, sau neighbors4) care are un parametru specificat mai mare (uphill) sau mai mic (downhill) decat casuta curenta. Sintaxa este: uphill patch_variable Daca nu e nici o casuta in vecinatate care sa aiba o valoare mai mare decat patch_variable, atunci agentul nu sse misca. Daca sunt mai multe casute cu aceeasi valoare a patch_variable in vecinatate, se alege una random.

Codul:
turtles-own [ at_peak ;; indicates whether a turtle has reached a "peak", ;; that is, it can no longer go "uphill" from where it stands ] to setup clear-all ;; make a landscape with hills and valleys ask n-of 10 patches [ set pcolor 120 ] ;; slightly smooth out the landscape

repeat 20 [ diffuse pcolor 1 ] ;; put some turtles on patch centers in the landscape ask n-of 30 patches [ sprout 1 [ set at_peak false set color red pen-down ] ] end to go ;; stop when all turtles are on peak if all? turtles [at_peak] [ stop ] ask turtles [ ;; remember where we started let old-patch patch-here ;; to use UPHILL, the turtles specify a patch variable uphill pcolor ;; are we still where we started? if so, we didn't ;; move, so we must be on a peak if old-patch = patch-here [ set at_peak true ] ] tick end

Sunt mai multe chestii interesante aici: a. Specificatorul n-of <number> b. pcolor definita printr-un numar.

c. Comanda diffuse <what> percent/100 Se refera la patches dar e o comanda de observer. Se executa de toate patch-urile! Exemplu:
diffuse chemical 0.5 ;; each patch diffuses 50% of its variable ;; chemical to its neighboring 8 patches. Thus, ;; each patch gets 1/8 of 50% of the chemical ;; from each neighboring patch.)

Asta merita un studiu separat, pentru ca feromonii difuzeaza. d. repeat <number> [commands ... ] repeta lista de comenzi de numarul specificat de ori. Exemplu: pd repeat 36 [ fd 1 rt 10 ] pd este prescurtarea de la pen-down fd forward rt right Efectul este ca agentul deseneaza un cerc aproximat din 36 de segmente. e. if all? turtles [at_peak] if all? testeaza o conditie logica. Interesant ca e pusa in paranteze patrate. f. let old-patch patch-here Aici avem o metoda de a defini variabile locale. Explicatia din manual:

let
let variable value Creates a new local variable and gives it the given value. A local variable is one that exists only within the enclosing block of commands. If you want to change the value afterwards, use set.

Deci conceptul de variabila locala se refera la ceva foarte local si volatil. g. uphill pcolor Deplasarea in sus in functie de culoarea patch-urilor din vecinatate

Exemplu separat Diffuse_test.nlogo

Codul: patches-own [pheromone] to setup clear-all ask patch 0 0 [set pheromone 100] ask patches [set plabel pheromone ] end to diffuse_once diffuse pheromone 0.5 ask patches [set plabel precision pheromone 3 ] end

Aici e interesant modul de a limita numarul de zecimale afisate folosind precision


precision number places Reports number rounded to places decimal places

Potrebbero piacerti anche