Menu
  • HOME
  • TAGS

How to set variables such as probabilities to turtles one at a time locally in NetLogo

Tag: variables,netlogo

In NetLogo I would like to iterate through each turtle one-at-a-time, with two breeds; bigs and smalls. In looking at one turtle, I would like to assign its neighbours probabilities, then make those probabilities into a list, multiply the list and then use that value to decide if the turtle should be moved or not. Then once the loop has finished working on one turtle, these values should be lost so they don't impact on the next central turtles neighbourhood. I have been using this code, but I realise now it seems to be overwritting the values as the 'ask smalls' comes last in the Probability_Product but I'm not sure how to fix it. Most of the undefined variables here are on a slider in the GUI. Thanks!

   breed [ bigs big ]
breed  [ smalls small ] 
bigs-own [ probability]
  smalls-own [ probability]


to setup
  clear-all 
  set-default-shape bigs "square"
  set-default-shape smalls "square"

   ask n-of bigs-number patches with [ abs (min-pxcor - pxcor) > 2]
    [sprout-bigs 1 [ set color red ]] 

    ask n-of smalls-number patches with [not any? bigs-here] 
     [sprout-smalls 1 [ set color blue ]]

    reset-ticks
end


to go  
ask turtles with [count turtles-on neighbors4 < 4 ][  
  ;; so only turtles will a space in the neighbours 4 can move
       let vacant-patches neighbors4 with [not any? turtles-here ]
  ;print Probability_Product 

if count turtles-on neighbors4 < 4 [
             if random 1001 <= Probability_Product * 1000    ;;if random number in the probability range, the following happens 
                     [ move-to one-of vacant-patches ]]
     ]
  tick
end

to-report Probability_Product  
  if ( count turtles-on neighbors4 < 4 ) or ( count turtles-on neighbors4 = 0 ) [

ifelse breed = bigs 

[  ask bigs-on neighbors4 [set probability Prob_big_big_breaking]  ask smalls-on neighbors4 [set probability Prob_small_big_breaking]
   let prob-list ( sentence ([probability] of turtles-on neighbors4))
  print prob-list
ifelse prob-list != [] 
 [ report reduce  * prob-list ] ;; multiplies all the probabilities together
       [report 1 ]]

[  ask smalls-on neighbors4 [set probability Prob_small_small_breaking]  ask bigs-on neighbors4 [set probability Prob_small_big_breaking]
  let prob-list ( sentence ([probability] of turtles-on neighbors4))
  print prob-list
ifelse prob-list != [] 
 [ report reduce  * prob-list ] ;; multiplies all the probabilities together
       [report 1 ]]]

 end

Best How To :

This isn't really an answer (EDIT: Maybe it is now?), but it's a necessary response, and it won't fit into a comment. I have other questions in comments.

I'm still not sure whether I've answered your question in comments. I think there are a few things that need to be done first to clarify what your code is supposed to do. First, I've edited the code in your question to format it in order make it clearer (while trying to preserve your style as much as possible). Second, I added closing brackets on the line after ask bigs and after ask smalls. Most importantly, I think that it would help if you could provide a Minimal Working Example (MWE)--the smallest, simplest version of your program that still contains code that (a) runs, and (b) illustrates the problem you're trying to solve. It takes some work to construct an MWE, because you have to figure out what you can take out (because leaving it in will just confuse readers), and what you have to leave in, because it's essential to creating the problem. (However, sometimes you'll figure out the answer to your question on your own when you try to create an MWE.)

For example, here is an MWE, in the sense that it runs, but you'll have to change it to illustrate your problem.

breed [bigs big]
breed [smalls small]
bigs-own [probability]
smalls-own [probability]
globals [Prob_bigs_bigs_breaking Prob_smalls_smalls_breaking]

to setup
  reset-ticks
  ask n-of 20 patches [sprout-bigs 1 []]
  ask n-of 20 patches [sprout-smalls 1 []]
end

to go  
  ask turtles with [count turtles-on neighbors4 < 4 ][  
     ;; so only turtles will a space in the neighbours 4 can move
     move-turtle
  ]
  tick
end

to-report Probability_Product

  ask bigs with [count turtles-on neighbors4 < 4 ] [ 
    ;; self is each big in turn
    ask bigs-on neighbors4 [set probability Prob_bigs_bigs_breaking] 
  ]

  ask smalls with [count turtles-on neighbors4 < 4 ][
    ;; self is each small, in turn  
    ask smalls-on neighbors4 [set probability Prob_smalls_smalls_breaking]
  ]

  ;; Here self is the turtle that called move-turtle, which called Probability_Product.
  if any? turtles with [count turtles-on neighbors4 < 4 ][
    let prob-list ( sentence ([probability] of turtles-on neighbors4))
    if prob-list != [] 
      [ report reduce  * prob-list ] ;; multiplies all the probabilities together
  ]

  report 0
end

to move-turtle
  if random 1001 <= Probability_Product * 1000 [
    ;.....
  ]
end

Next, I suggest that the ask bigs and ask smalls lines should be done in a separate procedure from the function containing if any? .... Putting this all in one procedure is confusing, because in the ask blocks in Probability_Product, we refer to turtles defined by those asks, but in the if any?, we refer to the turtle defined by the ask two procedures "above", i.e. defined by the ask in go, which then calls move-turtle, which then calls Probability_Product. When we get to the if any?, it was hard to figure out what turtle neighbors4 was relative, because it's defined two procedures above, and because Probability_Product also refers to all bigs and all smalls.

In addition to being confusing, I'm not sure that Probability_Product is doing what you want. For each turtle, this procedure goes and asks all bigs and all smalls to do something. So, if the bigs and smalls are the only turtles, Probability_Product asks all turtles to do something, and then for the next turtle, again asks all turtles to do the same thing, and so on.

EDIT:

It seems to me that what Probability_Product is supposed to do in the MWE can be done more simply with the following function. Maybe I'm misinterpreting your intention, and it may be that in the full program there is more that needs to be done, since the function below doesn't set or use the probability variables at all. Even if this isn't what you want, perhaps this example will help you think through what you need to do.

to-report new-Probability_Product
  let neighbor-count count turtles-on neighbors4
  let big-neighbor-count count bigs-on neighbors4
  let small-neighbor-count count smalls-on neighbors4

  if-else neighbor-count < 4 and neighbor-count > 0
    [ if-else is-big? self  ; self is turtle from ask in go procedure
        [ report (Prob_big_big_breaking ^ big-neighbor-count) *    ; if self is a big
                 (Prob_small_big_breaking ^ small-neighbor-count) ]
        [ report (Prob_small_big_breaking ^ big-neighbor-count) *  ; if self is a small
                 (Prob_small_small_breaking ^ small-neighbor-count) ] ]
    [ report 1]
end

The idea behind this function is that the only thing that the probability variable is doing in Probability_Product is holding the values set in the sliders. Then those values are multiplied. But we can just multiply those values directly.

(A number of my other comments still seem applicable.)

How do I use the Find function with a variable term, for example Run1, Run2, RunX

vba,excel-vba,loops,variables

Yes, you need a variable, and just concatenate it. Use something like this: Dim counter as long counter = 1 Cells.Find(What:="Run:" & counter, After:=Cells(1, 1), _ ...yaddayadda Or use it in a loop: For i=1 to 100 Cells.Find(What:="Run:" & i, After:=Cells(1, 1), _ ...yaddayadda Next i ...

Variable value changing after returning from a function in C

c,variables,matrix

Update the function void allocate( int ***mat, int n, int m ) { int i; *mat = (int **) malloc( n * sizeof( int* ) ); for ( i = 0; i < n; i++ ) { ( *mat )[i] = ( int *) malloc ( m * sizeof( int...

Swift Reverse Geocoding using the Data

swift,variables,geocode

Your problem is most likely due to the fact that reverseGeocodeLocation is an asynchronous request made to Apple servers. What needs to happen is: You call reverseGeocodeLocation reverseGeocodeLocation finishes, starts its completion which calls a method passing the placemark you just recovered. In order to do that: @IBAction func btnInsertClicked(sender:...

VBA SUM Variable Range

excel,vba,variables,sum,range

Sub Test() Dim y As Variant Dim firstRow As Variant Dim lastRow As Variant lastRow = Range("C" & Rows.Count).End(xlUp).Row firstRow = Cells(lastRow, 3).End(xlUp).Row If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")" End If...

MySQL multi SELECT query into form and then UPDATE

php,mysql,forms,variables,post

Success, I figured it out myself [= i had to add a row to the end of the table with the end value of $i <tr hidden> <td hidden> <input type="text" name="ivalue" style="width:120px;" Value="'; echo $i;echo '" style="width:70px" hidden></font> </td> </tr> Then this was in my <form action="senddata.php" file> i...

Batch file %%i was unexpected at this time

variables,batch-file

If you are executing this directly in command prompt try this: for /f %i in ('wmic process where "name='chrome.exe'" get caption /format:value ^| find "chrome.exe" /c') do set var=%i for batch file left the double %...

Undefined local variable post

ruby-on-rails,ruby,variables,undefined,local

You need to use partial: when you pass locals to a partial as follows: <%= render partial: 'post', locals: { post: post, user: @user} %> I hope this will help you....

Run 3 variables at once in a python for loop.

python,loops,variables,csv,for-loop

zip the lists and use a for loop: def downloadData(n,i,d): for name, id, data in zip(n,i,d): URL = "http://www.website.com/data/{}".format(name) #downloads the file from the website. The last part of the URL is the name r = requests.get(URL) with open("data/{}_{}_{}.csv".format(name, id, data), "wb") as code: #create the file in the format...

How to check for a variable name using a string in Python?

python,variables

>>> spam= [1,2,3] >>> stuff = [spam] >>> eval('spam') in stuff True DISCLAIMER : do this at your own risk. ...

Writing PHP variable based on jQuery calculations and displaying predetermined value

php,jquery,list,variables,automation

The problem your having is the difference between server-side processing and client-side processing. An easy way to think about this is that PHP is handled before the HTML is even put on the screen replacing all the PHP parts with their variable contents. meaning that adding that php text with...

Compiler modifying a variable without adressing it

c#,variables,dictionary

What you are currently doing: Dict2 = Dict1; Is reference copying, so both Dict1 and Dict2 are pointing to the same location. You can create a new copy like: Dict2 = Dict1.ToDictionary(d=> d.Key, d=> d.Value); Remember, if your Key and Value are custom objects (based on some class), in that...

How can I use a variable to get an Input$ in Shiny?

r,variables,csv,shiny

input is just a reactivevalues object so you can use [[: print(input[[a]]) ...

PS pipe WorkingSet as variable

variables,powershell

Use Select-Object -ExpandProperty to grab just a single property from the process: $WorkingSet = Get-Process spiceworks |Select-Object -First 1 -ExpandProperty WorkingSet if($WorkingSet -gt 120MB) { # Send email } ...

XSLT filePath with document as variable

variables,xslt,filepath

I am mostly guessing here, but supposing your XSLT stylesheet contains: <xsl:variable name="vpDocNr" select="'abc123'"/> <BodyPart filePath="C:\FileOutEmail\{$vpDocNr}.xml"/> then the result of this part will be: <BodyPart filePath="C:\FileOutEmail\abc123.xml"/> ...

Maya MEL variables declaration and initialization

variables,maya,mel

You don't need to populate the variable, initializing it with a type declaration sets it to a default value (0 for ints, 0.0 for floats, and "" for strings). In general it's good practice to assign in place when the initial variable is meaningful: string $topCamera = "|top|topShape"; but it's...

Where are the local variables of an Android app stored?

android,variables,local

From https://source.android.com/devices/tech/dalvik/dalvik-bytecode.html: Because, in practice, it is uncommon for a method to need more than 16 registers, and because needing more than eight registers is reasonably common, many instructions are limited to only addressing the first 16 registers. When reasonably possible, instructions allow references to up to the first 256...

How to call a list for update multiple times until a condition is fulfilled in Netlogo

list,procedure,netlogo

This is easiest to solve using recursion: to-report remove-fenced-sublists [xs] if empty? xs [ report [] ] let pos position first xs butfirst xs if not is-number? pos [ report fput first xs remove-fenced-sublists butfirst xs ] report remove-fenced-sublists sublist xs (pos + 2) length xs end Sample run: observer>...

How to extract first letters of dashed separated words in a bash variable?

linux,string,bash,shell,variables

This isn't the shortest method, but it doesn't require any external processes. IFS=- read -a words <<< $MY_TEXT for word in "${words[@]}"; do MY_INITIALS+=${word:0:1}; done ...

calling string as variable in python

python,string,variables

It's probably better to use a dictionary here. Define one with segments = {}. Then you can create a SignalParam by keying into your dictionary with your segment number: segments[segment_number] = SignalParam() and use the object like this: segments[segment_number].frequency = 33 ...

PHP Define var = one or other (aka: $var=($a||$b);)

php,variables,operators

Update I've managed to create a function for you that achieves exactly what you desire, allowing infinite arguements being supplied and fetching as you desire: function _vars() { $args = func_get_args(); // loop through until we find one that isn't empty foreach($args as &$item) { // if empty if(empty($item)) {...

String concatenation not working in HTML declaration of TABS through PHP variables [closed]

php,html,variables,tabs

It looks like you are missing " //your code echo '<div class="tab-pane" id="panel-"'.$a.'>'; ///should be echo '<div class="tab-pane" id="panel-'.$a.'">'; ...

Call known function (with parameters) in class whose name is defined by string variable

java,function,class,variables

Your can use Reflection Object action = ???; // perhaps you need .newInstance() for action class // Hopefully you have a interface with performLogic String methodName = "performLogic"; try { Method method = action.getClass().getMethod(methodName, param1.class, param2.class); method.invoke(action, param1, param2); } catch (SecurityException | NoSuchMethodException e) { // Error by get...

Very weird behavior when using “var” keyword in an ajax request

javascript,ajax,variables,var

Cool, you discovered hoisting. MDN explains it as good as anyone: Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be...

read variable excel data into variant with the same format

excel,vba,excel-vba,variables,data-structures

You could force test to be an array with only one cell, if the last column is B or less : ' Define Last Column with a value LastCol = Sheets("Filter").Cells(20, Sheets("Filter").Columns.Count).End(xlToLeft).Column Col_Letter = Split(Cells(1, LastCol).Address(True, False), "$")(0) If LastCol <= 2 Then ReDim test(1 To 1, 1 To 1)...

gnuplot - get errors on fit parameters, get fit output values as variables, print variable to screen

variables,gnuplot,curve-fitting,data-fitting,function-fitting

Quoting the documentation: If activated by using set fit errorvariables, the error for each fitted parameter will be stored in a variable named like the parameter, but with "_err" appended. ...

Java: Assigning a variable its current value?

java,variables,optimization,value

the cost of calling the method isEmpty() (allocating new space in the thread stack etc) negate any gains. if you want to assign an empty String to the variable, its most efiicient to do so without the if statement.

Need Help in Python Variable updation (Pygame module)

python,python-2.7,variables,python-3.x,pygame

You are confusing the event KEYUP with the UP key. The event KEYUP occurs when a key (any key) is released. The event KEYDOWN occurs when any key is pressed down. In you code, this means that when the UP key is pressed down, the speed is set to 0.1,...

Find a single duplicate in a list of lists Netlogo

list,duplicates,netlogo

This is quick and dirty, but find-dup should return the first duplicated item (in this case a sublist) in the list. to go let listA [[-9 2] [-9 1] [-9 0][-9 -1][-9 -2][-9 -3][-9 -4][-8 0][-9 0]] show find-dup listA end to-report find-dup [ c ] ;returns the first duplicated...

Problems with Flash 8 (AS2), Timelines, and Variable Scopes

flash,variables,scope,actionscript-2

The issue is likely that your Text fields are being unloaded (eg There are frame where they are not on the stage anymore), so when frame 1 comes around, it re creates them (which gives them the text that you put in on the keyframe). To work around this, In...

Javascript: Resetting variable value created by form

javascript,forms,variables

your function resetForm(){ document.getElementById("form").reset(); } should be function resetForm(){ document.getElementById("form").reset(); msg.innerText=""; msg.className=""; } basically: you are not re-setting #message back to hidden which is where you start. And, I am also making sure that innerText is blank. ...

Why is interface variable instantiation possible?

c#,variables,interface,instance

You're not instantiating an interface, but an array of that interface. You can assign an instance of any class that implements IDynamicCode<string> to that array. Say you have public class Foo : IDynamicCode<string> { }, you can instantiate that and assign it to an element of that array: var x...

Running netlogo with 64 bit Java from a batch file

netlogo

What directory are you running that command from? For NetLogo to find extensions, sample models, etc., the current working directory at startup time must be the NetLogo directory. So your script should chdir there first.

subtracting from multiple variables at a time

python,variables,syntax-error

Just move them to two separate lines if minutes >= 60: hours += 1 minutes -= 60 From PEP 8 Compound statements (multiple statements on the same line) are generally discouraged. For the sake of completeness, I will tell you that you can add ; to terminate a statement, so...

SQL Repeated Condition in Two Tables

sql,variables,coding-style,condition

you can achieve it like this DECLARE @AccountId int; @AccountID=20; DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE [email protected]); DELETE FROM Table_B WHERE [email protected]; ...

Is there any way of protecting a variable for being modified at runtime in C?

c,variables,constants

You can make the result of the input be const like this: int func() { int op = 0; scanf( "%d", &op ); if( op == 0 ) return 1; else return 2; } int main() { const int v = func(); // ... } NB. Of course, there is...

How to avoid adding a link between two nodes twice

network-programming,netlogo

link-neighbor? will tell you that. It's a turtle reporter and it takes one argument; the turtle that you are want to know if it is connected to. So: ask n-of number-of-links turtles [create-link-with one-of other turtles with [not link-neighbor? myself]] will do the trick. Keep in mind that this will...

Having two arrays in variable php

php,mysql,arrays,variables,multidimensional-array

The explode function is being used correctly, so your problem is further up. Either $data[$i] = mysql_result($result,$i,"data"); isn't returning the expected string "2015-06-04" from the database OR your function $data[$i] = data_eng_to_it_($data[$i]); isn't returning the expected string "04 June 2015" So test further up by echo / var_dump after both...

Div with a simple variable height

javascript,html,css,variables,height

<?php $numberOfPurchases = getNumberOfPurchases(); // call the function that queries the database ?> <script> var defaultDivHeight = 10; var purchaseDiv = document.getElementById('purchaseDiv'); if (<?= numberOfPurchases; ?> > 0) { purchaseDiv.style.height = <?= numberOfPurchases; ?> * defaultDivHeight + 'px'; } else { purchaseDiv.style.height = defaultDivHeight + 'px'; } </script> I suggest...

Count variable Invalid Syntax [on hold]

python,variables,syntax

The specific error you are asking about is because of the missing colon: And card1 cannot be called. if guess==card1() count+=1 Should be if guess==card1: count+=1 There is also a missing closing bracket on the guess: guess = int(input(""" Pick One! 1:'Crown', 2:'Anchor', 3:'Heart', 4:'Diamond', 5:'Club', 6:'Spade', 0:'Quit', """)) ...

Delphi - Use a string variable's name in assignfile()

file,delphi,variables,assign

Is it possible to use a variable in the AssignFile command? Yes. The second parameter of AssignFile has type string. The expression cFileDir + '\' + sFile has type string. FWIW, AssignFile is known as a function rather than a command. Getting on top of terminology like this will...

PHP / JavaScript: How to pass variable from one page to another

javascript,php,jquery,variables,get

You can use cookies to do so setcookie(name, value, expire, path, domain, secure, httponly); i.e.: setcookie('language', 'german', 60000,"/"); and then check this wherever with $_COOKIE["language"] http://php.net/manual/en/features.cookies.php reference...

Assign the value from a text field into an int variable to do some math with other variables and then return it?

ios,xcode,variables,textfield,assign

The opposite of that would be getting converting string to float. You can do it with this init = [_Initial.text floatValue]; ...

If a = b, what happens if each value changes respectively?

java,variables

What happens to b? Nothing happens to b. When you do a = b; you're copying the value stored in b and putting it in a. (You're not making a an alias of b.) When you then do a += 1; you're changing the value stored in a (and...

php form mail function

php,email,variables,concatenation

As I mentioned in comments, you're overthinking this and there are a few simpler ways to go about this. Either by changing your whole block to: (no need for all those variables) $mail = " <h1> </h1><h2>Afzender:</h2><p> ( )</p><h2>Bericht:</h2><p> </p> "; then mail("$myEmail","$emailOnderwerp",$mail,... But, if you wish to continue using...

C# PictureBox variable in a class

c#,variables,picturebox

A class would be easier, and I would also recommend using a List instead of array. Example: class Container { public PictureBox picture { get; set; } public double number { get; set; } } List<Container> PicturesAndNumbers = new List<Container>(); To add things to the list you will need to...

SQL Multiple LIKE Statements

sql,sql-server,tsql,variables,like

WITH CTE AS ( SELECT VALUE FROM ( VALUES ('B79'), ('BB1'), ('BB10'), ('BB11'), ('BB12'), ('BB18'), ('BB2'), ('BB3'), ('BB4'), ('BB5'), ('BB6'), ('BB8'), ('BB9'), ('BB94'), ('BD1'), ('BD10'), ('BD11'), ('BD12'), ('BD13'), ('BD14'), ('BD15'), ('BD16'), ('BD17'), ('BD18'), ('BD19'), ('BD2'), ('BD20'), ('BD21'), ('BD22'), ('BD3'), ('BD4'), ('BD5'), ('BD6') ) V(VALUE) ) SELECT * FROM tbl_ClientFile...

How to get value from property in BeanShell (jmeter)

variables,jmeter,beanshell

In the first Thread Group: props.put("erroriden", vars.get("erroriden1")); In the second Thread Group: String[] erroriden = props.get("erroriden").split(","); JMeterVariables scope is limited to the current thread group only JMeter Properties are usual Java Properties which are global for JVM instance See How to use BeanShell: JMeter's favorite built-in component guide for more...

jQuery - Increase integer by using arrays content as the variable name

jquery,arrays,variables,integer

Just change increase[0]++ to window[increase[0]]++ ...

Get variable *value* instead of variable itself

javascript,variables

JavaScript has function scope for variables. If you want to use the same variable twice but it should not be the same reference, you need to put the code in different scopes (functions). So you could do this: button = document.getElementById("button"); button2 = document.getElementById("button2"); (function() { var x = 5;...

Is [ $var ] an acceptable way to check for variables set/empty in bash?

bash,shell,variables

./script one '' oops [ $2 ] will be false when $2 is the empty string. And as that other guy points out in a comment, bash will split both strings, opening up a range of issues, including potential security holes....