Not calculating "set" correctly - syntax? - set

I am trying to use set to calculate a value, but it always return 0.5. When I breakdown the equation to individual operators, it works fine, but when I put it all together, all I get is 0.5. I think I have a syntax misunderstand. Any suggestions?
to go
;;see if a new risk is generated [randomly]
if random 2 = 1 ;;50% chance risk be generated on an individual project
[
make-risk
ask one-of projects
[
ask one-of risks [
set risk-encounter ((((RE-influence * ( [duration] of myself ) * 0.5)) / (( [duration] of myself )))) ;;calculate RE. THIS DOES NOT WORK :-( Always sets to 0.5
set temp-RE-score risk-encounter
]
set total-RE total-RE + temp-RE-score ;;update the project's RE score
]
]
ask projects[
set label precision total-RE 1
set size total-RE / 10 ; size according to RE score
]
tick
if ticks >= (max [duration] of projects ) * 2 [stop] ;; stops all the projects once max duration is reached (* 2)
end

Related

Turtle distribution

How to create a set of turtles with the rising distribution of their location from the edge of the environment to the middle?
You can use something like this in setup
let center-x (max-pxcor + min-pxcor) / 2
let center-y (max-pycor + min-pycor) / 2
let std-dev 5 ; change this to vary how clumped the turtles are
crt 100
[
set xcor random-normal center-x std-dev
set ycor random-normal center-y std-dev
]
That will work if you have world-wrapping on. If world-wrapping is off, you would have to add some code to check that the values of xcor and ycor from random-normal are within the world (e.g., the turtle's new xcor is between min-pxcor and max-pxcor) -- otherwise, the code will sometimes try to put the new turtle outside the space, which is an error.
You could also use a triangular distribution that varies the density of turtles linearly from a peak at the center of the space to zero at the edge.
let center-x (max-pxcor + min-pxcor) / 2
let center-y (max-pycor + min-pycor) / 2
crt 100
[
set xcor random-triangular min-pxcor center-x max-pxcor
set ycor random-triangular min-pycor center-y max-pycor
]
NetLogo does not have this triangular distribution built-in, so you need to add this procedure to your code:
to-report random-triangular [a-min a-mode a-max]
; Return a random value from a triangular distribution
; Method from https://en.wikipedia.org/wiki/Triangular_distribution#Generating_Triangular-distributed_random_variates
; Obtained 2015-11-27
if (a-min > a-mode) or (a-mode > a-max) or (a-min >= a-max)
[ error (word "Random-triangular received illegal parameters (min, mode, max): " a-min " " a-mode " " a-max) ]
let a-rand random-float 1.0
let F (a-mode - a-min) / (a-max - a-min)
ifelse a-rand < F
[ report a-min + sqrt (a-rand * (a-max - a-min) * (a-mode - a-min)) ]
[ report a-max - sqrt ((1 - a-rand) * (a-max - a-min) * (a-max - a-mode)) ]
end

bash: How to round/floor/ceiling non-decimals thousands number?

lets say I have this number here 100675
how to turn it into 101000
all the solution I have found on google are solving decimals number.
The bash shell is able to do calculations internally, such as with the following transcript:
pax:~> for x in 100675 100499 100500 100999 101000; do
...:~> ((y = (x + 500) / 1000 * 1000))
...:~> echo " $x becomes $y"
...:~> done
100675 becomes 101000
100499 becomes 100000
100500 becomes 101000
100999 becomes 101000
101000 becomes 101000
This statement, ((y = (x + 500) / 1000 * 1000)), first adds 500 to make the otherwise-truncating integer division by 1,000 into a rounding division, then re-multiplies it by 1,000.
This is a bit of a weird function, but here goes a rough version that might be what you need. At least this could be a starting point.
# in:
# $1 - the number to round
# $2 - the 10 power to round at. Defaults to 3 (i.e. 1000)
# output:
# The rounded number
roundPow()
{
local n="$1"
local pow="${2:-3}"
local div="$((10 ** pow))"
echo "$((((n + div / 2) / div) * div))"
}
This is very rough around the edges, it's not validating parameters, etc, but should give you a baseline.
Hope this helps.

Code not working with bigger values of for loops

I am implementing a Szudik's pairing function in Matlab, where i pair 2 values coming from 2 different matrices X and Y, into a unique value given by the function 'CantorPairing2D(X,Y), After this i reverse the process to check for it's invertibility given by the function 'InverseCantorPairing2( X )'. But I seem to get an unusual problem, when i check this function for small matrices of size say 10*10, it works fine, but the for my code i have to use a 256 *256 matrices A and B, and then the code goes wrong, actually what it gives is a bit strange, because when i invert the process, the values in the matrix A, are same as cvalues of B in some places, for instance A(1,1)=B(1,1), and A(1,2)=B(1,2). Can somebody help.
VRNEW=CantorPairing2D(VRPRO,BLOCK3);
function [ Z ] = CantorPairing2D( X,Y )
[a,~] =(size(X));
Z=zeros(a,a);
for i=1:a
for j=1:a
if( X(i,j)~= (max(X(i,j),Y(i,j))) )
Z(i,j)= X(i,j)+(Y(i,j))^2;
else
Z(i,j)= (X(i,j))^2+X(i,j)+Y(i,j);
end
end
end
Z=Z./1000;
end
function [ A,B ] = InverseCantorPairing2( X )
[a, ~] =(size(X));
Rfinal=X.*1000;
A=zeros(a,a);
B=zeros(a,a);
for i=1:a
for j=1:a
if( ( Rfinal(i,j)- (floor( sqrt(Rfinal(i,j))))^2) < floor(sqrt(Rfinal(i,j))) )
T=floor(sqrt(Rfinal(i,j)));
B(i,j)=T;
A(i,j)=Rfinal(i,j)-T^2;
else
T=floor( (-1+sqrt(1+4*Rfinal(i,j)))/2 );
A(i,j)=T;
B(i,j)=Rfinal(i,j)-T^2-T;
end
end
end
end
Example if A= 45 16 7 17
7 22 11 25
11 12 9 17
2 11 3 5
B= 0 0 0 1
0 0 0 1
1 1 1 1
1 3 0 0
Then after pairing i get
C =2.0700 0.2720 0.0560 0.3070
1.4060 0.5060 0.1320 0.6510
0.1330 0.1570 0.0910 0.3070
0.0070 0.1350 0.0120 0.0300
after the inverse pairing i should get the same A and same B. But for bigger matrices it is giving unusual behaviour, because some elements of A are same as B.
If possible it would help immensely a counter example where your code does fail.
I got to reproduce your code behaviour and I have rewritten your code in a vectorised fashion. You should get the bug, but hopefully it is a first step to uncover the underlying logic and find the bug itself.
I am not familiar with the specific algorithm, but I observe a discrepancy in the CantorPairing definition.
for elements where Y = X your if statement would be false, since X = max(X,X); so for those elements your Z would be X^2+X+Y, but for hypothesis X =Y, therefore your would have:
X^2+X+X = X^2+2*X;
now, if we perturb slightly the equation and suppose Y = X + 10*eps, your if statement would be true (since Y > X) and your Z would be X + Y ^2; since X ~=Y we can approximate to X + X^2
therefore your equation is very temperamental to numerical approximation ( and you definitely have a discontinuity in Z). Again, I am not familiar with the algorithm and it may very well be the behaviour you want, but it is unlikely: so I am pointing this out.
Following is my version of your code, I report it also because I hope it will be pedagogical in getting you acquainted with logical indexing and vectorized code (which is the idiomatic form for MATLAB, let alone much faster than nested for loops).
function [ Z ] = CantorPairing2D( X,Y )
[a,~] =(size(X));
Z=zeros(a,a);
firstConditionIndeces = Y > X; % if Y > X then X is not the max between Y and X
% update elements on which to apply first equation
Z(firstConditionIndeces) = X(firstConditionIndeces) + Y(firstConditionIndeces).^2;
% update elements on the remaining elements
Z(~firstConditionIndeces) = X(~firstConditionIndeces).^2 + X(~firstConditionIndeces) + Y(~firstConditionIndeces) ;
Z=Z./1000;
end
function [ A,B ] = InverseCantorPairing2( X )
[a, ~] =(size(X));
Rfinal=X.*1000;
A=zeros(a,a);
B=zeros(a,a);
T = zeros(a,a) ;
% condition deciding which updates to be applied
indecesToWhichApplyFstFcn = Rfinal- (floor( sqrt(Rfinal )))^2 < floor(sqrt(Rfinal)) ;
% elements on which to apply the first update
T(indecesToWhichApplyFstFcn) = floor(sqrt(Rfinal )) ;
B(indecesToWhichApplyFstFcn) = floor(Rfinal(indecesToWhichApplyFstFcn)) ;
A(indecesToWhichApplyFstFcn) = Rfinal(indecesToWhichApplyFstFcn) - T(indecesToWhichApplyFstFcn).^2;
% updates on which to apply the remaining elements
A(~indecesToWhichApplyFstFcn) = floor( (-1+sqrt(1+4*Rfinal(~indecesToWhichApplyFstFcn )))/2 ) ;
B(~indecesToWhichApplyFstFcn) = Rfinal(~indecesToWhichApplyFstFcn) - T(~indecesToWhichApplyFstFcn).^2 - T(~indecesToWhichApplyFstFcn) ;
end

NetLogo Sandpile Model - Code Required to Enhance Model

The below code relates to the NetLogo Sandpile Model where at each time step a random grain of sand is added. When the count of grains of sand exceeds a threshold limit it will trigger an avalanche type event.
I now want to enhance this model with further code so that at each tick (prior to the random grain of sand being added) the code now executes the following rules:
(1) Each patch count will increase its count (n + 1) if the majority of its 8 neighbours are n > 1.
(2) Each patch count will decrease its count to (n = 0) if the majority of its 8 neighbours are n < 1.
It will then move to the second step with the random addition of a grain of sand as in the original code below:
xtensions [sound]
globals [
;; By always keeping track of how much sand is on the table, we can compute the
;; average number of grains per patch instantly, without having to count.
total
;; We don't want the average monitor to updating wildly, so we only have it
;; update every tick.
total-on-tick
;; Keep track of avalanche sizes so we can histogram them
sizes
;; Size of the most recent run
last-size
;; Keep track of avalanche lifetimes so we can histogram them
lifetimes
;; Lifetime of the most recent run
last-lifetime
;; The patch the mouse hovers over while exploring
selected-patch
;; These colors define how the patches look normally, after being fired, and in
;; explore mode.
default-color
fired-color
selected-color
threshold-color
]
patches-own [
;; how many grains of sand are on this patch
n
;; A list of stored n so that we can easily pop back to a previous state. See
;; the NETLOGO FEATURES section of the Info tab for a description of how stacks
;; work
n-stack
;; Determines what color to scale when coloring the patch.
base-color
]
;; The input task says what each patch should do at setup time
;; to compute its initial value for n. (See the Tasks section
;; of the Programming Guide for information on tasks.)
to setup [setup-task]
clear-all
set default-color blue
set fired-color red
set selected-color green
set selected-patch nobody
ask patches [
set n runresult setup-task
set n-stack []
set base-color default-color
]
let ignore stabilize false
ask patches [ recolor ]
set total sum [ n ] of patches
;; set this to the empty list so we can add items to it later
set sizes []
set lifetimes []
reset-ticks
end
;; For example, "setup-uniform 2" gives every patch a task which reports 2.
to setup-uniform [initial]
setup task [ initial ]
end
;; Every patch uses a task which reports a random value.
to setup-random
setup task [ random error-count ]
end
;; patch procedure; the colors are like a stoplight
to recolor
set threshold-color threshold + 2
set pcolor scale-color base-color n 0 threshold-color
end
to go
if ticks = time
[ sound:play-note "Trumpet" 60 64 2 stop ]
let drop drop-patch
if drop != nobody [
ask drop [
update-n 1
recolor
]
let results stabilize animate-avalanches?
let avalanche-patches first results
let lifetime last results
;; compute the size of the avalanche and throw it on the end of the sizes list
if any? avalanche-patches [
set sizes lput (count avalanche-patches) sizes
set lifetimes lput lifetime lifetimes
]
;; Display the avalanche and guarantee that the border of the avalanche is updated
ask avalanche-patches [ recolor ask neighbors4 [ recolor ] ]
display
;; Erase the avalanche
ask avalanche-patches [ set base-color default-color recolor ]
;; Updates the average monitor
set total-on-tick total
tick
]
end
to explore
ifelse mouse-inside? [
let p patch mouse-xcor mouse-ycor
set selected-patch p
ask patches [ push-n ]
ask selected-patch [ update-n 1 ]
let results stabilize false
ask patches [ pop-n ]
ask patches [ set base-color default-color recolor ]
let avalanche-patches first results
ask avalanche-patches [ set base-color selected-color recolor ]
display
] [
if selected-patch != nobody [
set selected-patch nobody
ask patches [ set base-color default-color recolor ]
]
]
end
;; Stabilizes the sandpile. Reports which sites fired and how many iterations it took to
;; stabilize.
to-report stabilize [animate?]
let active-patches patches with [ n > threshold ]
;; The number iterations the avalanche has gone for. Use to calculate lifetimes.
let iters 0
;; we want to count how many patches became overloaded at some point
;; during the avalanche, and also flash those patches. so as we go, we'll
;; keep adding more patches to to this initially empty set.
let avalanche-patches no-patches
while [ any? active-patches ] [
let overloaded-patches active-patches with [ n > threshold ]
if any? overloaded-patches [
set iters iters + 1
]
ask overloaded-patches [
set base-color fired-color
;; subtract 'threshold' amount from this patch
update-n -4
if animate? [ recolor ]
;; edge patches have less than four neighbors, so some sand may fall off the edge
let selected-neighbors n-of 4 neighbors
;; World is wrapped horizonatlly and vertically so we can always select 4 random neighbors.
;; However, we only want to select neighbors which are on the table.
;; That is what the next section of code does.
set selected-neighbors selected-neighbors with [
(abs (pxcor - [ pxcor ] of myself) < 2) ;; selects patch < 2 from myself which is one patch away.
and
(abs (pycor - [ pycor ] of myself) < 2)
]
ask selected-neighbors [
update-n 1
if animate? [ recolor ]
]
]
if animate? [ display ]
;; add the current round of overloaded patches to our record of the avalanche
;; the patch-set primitive combines agentsets, removing duplicates
set avalanche-patches (patch-set avalanche-patches overloaded-patches)
;; find the set of patches which *might* be overloaded, so we will check
;; them the next time through the loop
set active-patches patch-set [ neighbors ] of overloaded-patches
]
report (list avalanche-patches iters)
end
;; patch procedure. input might be positive or negative, to add or subtract sand
to update-n [ how-much ]
set n n + how-much
set total total + how-much
end
to-report drop-patch
if drop-location = "center" [ report patch 0 0 ]
if drop-location = "random" [ report one-of patches ]
if drop-location = "mouse-click" and mouse-down? [
every 0.3 [ report patch mouse-xcor mouse-ycor ]
]
report nobody
end
;; Save the patches state
to push-n ;; patch procedure
set n-stack fput n n-stack
end
;; restore the patches state
to pop-n ;; patch procedure
; need to go through update-n to keep total statistic correct
update-n ((first n-stack) - n)
set n-stack but-last n-stack
end

How to create random binary/boolean variable in Netlogo

I'd like to assign a random boolean variable to each turtle, but I'm not seeing a function that would simulate a draw from a Bernoulli distribution.
This gets close, but it's awkward:
ifelse random-in-range 0 1 < .5 [set expensive? false]
[ set expensive? true ]
Anyone know a better way?
A few options:
one-of [ true false ]
random 2 = 1
random-float 1 < 0.5 - If you need to modify the probability, to get any Bernoulli distribution you want
If I deal with a lot of probabilistic stuff in a model, I like to add
to-report probability [ p ]
report random-float 1 < p
end
as an easy shorthand.
Also, note that the ifelse is redundant in your code. You can just do set expensive? one-of [ true false ] or whichever is your preferred method.

Resources