Multi-Nomial Logit / Modelling Choice [Netlogo] - netlogo

I have used multinomial logit model as the probability function to model the choice for a particular set of agents, my problem comes at the end when I have calculated the Probabilities which are P1, P2, and P3 and how I can use these to actually model the choice. My idea was to use something like the lotterywinning example from the modellibrary, but the problem is that in this case the Probabilities are not set but change for each tick and even though P1 has the lowest chance to occur it can have the highest chance in the next iteration.
Thanks for your help.
ps. Eq for Multinomial Logit is P{ik}= {exp(utilityik) \sum exp(utilityjk)}, for each of the cases.
to flightchoice-business
let flight-time1 mean [time1] of airline1
let airfare-airline1 mean [airfare] of airline1
set beta1 .8
set beta2 .2
set utility1 beta1 * (airfare-airline1) + beta2 * abs((time - flight-time1) * 10)
let flight-time2 mean [time1] of airline2
let airfare-airline2 mean [airfare] of airline2
set beta1 .8
set beta2 .2
set utility2 beta1 * (airfare-airline2) + beta2 * abs((time - flight-time2) * 10)
let flight-time3 mean [time1] of airline3
let airfare-airline3 mean [airfare] of airline3
set beta1 .8
set beta2 .2
set utility3 beta1 * (airfare-airline3) + beta2 * abs((time - flight-time3) * 10)
let cumulsum exp(utility1) + exp(utility2) + exp(utility3)
let P1 exp(utility1) / cumulsum
let P2 exp(utility2) / cumulsum
let P3 exp(utility3) / cumulsum
let buy random-float P1 + P2 + P3
end

You're on the right track. Your code should continue as follows:
...
let buy random-float P1 + P2 + P3
ifelse buy < P1 [
do-stuff-with-P1
] [
ifelse buy < P1 + P2 [
do-stuff-with-P2
] [
do-stuff-with-P3
]
]
You can generalize this with a function that takes a list, and it's a bit nicer in my opinion:
to-report weighted-random [ weights ]
let pick random-float sum weights
let total 0
let i 0
foreach weights [
set total total + ?
if pick < total [ report i ]
set i i + 1
]
end
You'd use this as follows:
let buy weighted-random (list P1 P2 P3)
if buy = 0 [ do-stuff-with-P1 ]
if buy = 1 [ do-stuff-with-P2 ]
if buy = 2 [ do-stuff-with-P3 ]

Related

How to plot a stem graph with multiple colors depending on the interval

Suppose you have a Matlab function which is defined over an interval [0:3*period], is there a way to produce a stem graph so that each period will have different colored stems?
Here's a bit of code so you can see what I mean:
T = 36;
n = [ 0 : 3 * T ];
x1 = cos( 5 * pi * n / 6 );
x2 = cos( 4 * pi * n / 9 );
z = x1 + x2;
Now I want to plot z(n) with a stem graph over three periods, but each period has to be a different color ( [ 0 : T ] in blue, [ T : 2T ] in red, and [ 2T : 3T ] in green ). Is there a way to specify the color of the stem graph depending on the interval of the graph?
This can be easily achieved by splitting data into three separate groups based on the reference period (logical indexing) and, subsequently, by plotting a separate stem for every group on the same axis (hold approach):
% Build data...
T = 36;
n = 1:(3*T);
z = cos(5 * pi() * n / 6) + cos(4 * pi() * n / 9);
% Define the splitting indices...
idx1 = n <= T;
idx2 = (n > T) & (n <= 2*T);
idx3 = (n > 2*T) & (n <= 3*T);
% Plot the data groups into the current axis...
stem(n(idx1),z(idx1),'fill','-b');
hold on;
stem(n(idx2),z(idx2),'fill','-r');
stem(n(idx3),z(idx3),'fill','-g');
hold off;
Here is the final result:

Predator-Prey Modelling in MATLAB

I have a Predator-Prey Model:
dR/dt = λR - aRF
dF/dt = -μF + bRF
Where λ and μ are growth rates of rabbits (R) and foxes (F) respectively, treated in isolation. a is the predation rate of foxes on rabbits, and b is the growth rate of popluation of foxes through predation on rabbits.
So far I have the following code, but I've really confused myself, where is my model going wrong?
function PredPrey
lambda = 0.1; % Lambda = Reproduction rate of rabbits
mu = 0.15; % Mu = Death rate of foxes
a = 0.005; % a = Rate of rabbits caught per fox
b = 0.002; % b = foxes born per rabbit caught
N = 3;
R = zeros(1,N);
F = zeros(1,N);
R(1) = 100;
F(1) = 10;
for n = 2:N
R(n) = R(n-1) + lambda*R(n-1) - a*R(n-1)*F(n-1);
F(n) = F(n-1) - mu*F(n-1) + b*a*R(n-1)*F(n-1);
end
Xvals = 1:N;
plot(Xvals,R,'b',Xvals,F,'r')
end
Basically you have a system of odes which needs tools like ode45 to handle. I suggest you to take a look at
https://www.mathworks.com/help/matlab/ref/ode45.html
Moreover, you may use
function f = predPrey(t,x)
f = zeros(2,1);
% x(1) represents the number of rabbits
% x(2) represents the number of foxes
% Model's parameters
a = 0.01
b = 0.02
c = 0.03
d = 0.04
f(1) = a*x(1) - b*x(1)*x(2);
f(2) = -c*x(2) + d*x(1)*x(2);
end
with the following command:
[time,valx] = ode45(#(t,x) predPrey(t,x),[0,5],[200,100]);
to solve the system for time t = 0 to t = 5 with the initial population of 200 rabbits and 100 foxes.
Note that
rabbit = valx(:,1)
fox = valx(:,2)

How to create a table in Matlab?

Following is the graph that I used to calculate the PMV at points: A, B, C, D, E
%This is the code I used to calculate the PMV at points: A, B, C, D, E.
%Where:
%ta=tr=interior temperature setting (22°C, 23°C, 27°C) (variable);
%va=0,2 m/s (invariable);
%RH=50% (invariable);
%W=0 (invariable);
%Met= energy metabolism (1,2 met or 1,4 met) (variable);
%Iclo= static clothing insulation (0,5 clo or 1,0 clo) (variable).
ta=22.0;
tr=22.0;
va=0.2; %air speed
RH=50; %relative humidity
W=0;%mechanical work
Met=1.2;%energy metabolism in met (1 met=58.2 W/m2)
Iclo=0.5;%static clothing insulation
%preparation of variables
PHI=RH/100;%hygrometric dimensionless degree
Icl=Iclo*.155;%Conversion from clo to m2K/W
M=Met*58.15;%conversion of metabolism in unit of measurement of SI
Iclr=Icldyn_7730(va, Icl, M); %calculation of dynamic clothing insulation
vw=0.0052*(M-58);
vr=va+vw;
PMV_Fanger=PMV_evaluator( M,W,ta,tr,vr,PHI,Iclr );
Observation: the functions I called are the following: "Icldyn_7730"
function [ Icldyn ] = Icldyn_7730(va, Iclst, M)
%calculation of dynamic clothing insulation
%Input data
% va, air speed, m/s
% Iclst, static clothing insulation
% M, metabolism in W/m2
vw=0.0052*(M-58);
if vw>0.7
vw=0.7;
end
vr=va+vw;
%Static cloting insulation conversion m2K/W to clo
Iclo = Iclst/0.155;
%Clothing area factor
if Iclst <=0.078
fcl= 1.00 + 1.290 * Iclst;
else
fcl= 1.05 + 0.645 * Iclst;
end
%Static boundary layer thermal insulation in quiet air in m2K/W
Iast = 0.111;
%Total static insulation
Itotst= Iclst + Iast / fcl;
%Clothing insulation correction for wind (vr) and and walking (vw)
vraux= vr;
if vraux > 3.5
vraux=3.5;
end
if vraux < 0.15
vraux=0.15;
end
vwaux=vw;
if vwaux>0.7
vwaux=0.7;
end
CorIt=exp(-0.281*(vraux-0.15)+0.044*(vraux-0.15)^2-0.492*vwaux+0.176*vwaux^2);
if CorIt>1
CorIt=1;
end
CorIa=exp(-0.533*(vraux-0.15)+0.069*(vraux-0.15)^2-0.462*vwaux+0.201*vwaux^2);
if CorIa>1
CorIa=1;
end
Itr = Itotst * CorIt;
Iar = CorIa * Iast;
if Iclo<=0.6
Itr= ((0.6-Iclo) * Iar + Iclo * Itr) / 0.6;
end
Itdyn = Itr;
Iadyn = Iar;
Icldyn = Itdyn - Iadyn / fcl;
end
and "PMV_evaluator"
function [ PMV ] = PMV_evaluator( M,W,ta,tr,vr,PHI,Icl )
%Function for the calculation of the PMV index
% Input data
% M, metabolic rate in W/m2
% W, mechanical work in W/m2
% ta, air temperature in °C
% tr, mean radiant temperature in °C
% vr, rwlative air velocity in m/s
% PHI, hygrometric ratio dimensionless
% Icl in m2K/W (dynamic clothing insulation )
if (ta >=0)
ps = exp (16.6536-4030.183 / (235 + ta ));
else
ps = 0.6105* exp (21.875*ta / (265.5 + ta ));
end;
TAA = ta+273.0;
TRA = tr+273.0;
TCLA = TAA + (35.5-ta) / (3.5*Icl+0.1);
hcf = 12.1 * sqrt(vr);
%Clothing area factor
if Icl <=0.078
fcl= 1.00 + 1.290 * Icl;
else
fcl= 1.05 + 0.645 * Icl;
end
% Start of the loop for the evaluation of clothing surface temperature}
P1 = Icl * fcl;
P2 = P1 * 3.96;
P3 = P1 * 100;
P4 = P1 * TAA;
P5 = 308.7 - 0.028 * (M-W) + P2 * (TRA/100)^4;
XN = TCLA/100;
XF = XN;
EPS = 0.00015;
CONV = 100;
N=1;
while (CONV>EPS)
XF = (XF+XN)/2;
hcn = 2.38 * ((abs(100*XF - TAA))).^0.25;
if (hcf<=hcn)
hc = hcn;
else
hc = hcf;
end
XN = (P5+P4*hc-P2*XF^4)/(100+P3*hc);
CONV=abs(XF-XN);
end
tcl = 100*XN-273;
% End of the loop for the evaluation of clothing surface temperature}
%Skin diffusion heat loss
HL1=3.05*0.001*(5733-6.99*(M-W)-1000*PHI*ps);
%Sweat heat loss
if (M-W)>58.15
HL2= 0.42 * ((M-W)-58.15);
else
HL2=0;
end
%Respiration latent heat loss
HL3= 1.7*0.00001 * M * (5867-1000*PHI*ps);
%Respiration dry heat loss
HL4= 0.0014 * M * (34-ta);
%Radiative heat loss
HL5= 3.96 * fcl * ((0.01*tcl+2.73)^4-(0.01*tr+2.73)^4);
%Convective heat loss
HL6= fcl * hc * (tcl-ta);
%Thermal sensation transformation coefficient}
TS= 0.303 * exp(-0.036*M) + 0.028;
PMV= TS * (M-W-HL1-HL2-HL3-HL4-HL5-HL6);
end
How can I create a table like the following with MATLAB?
The data in the table are the values of PMV. They have been obtained from the individual calculations of MATLAB.
Consider using the table variable introduced in the later versions of matlab, this variable allows for disparate data sources. The full matlab help has an example where the a set of categorical row names occupies the first column while a set of headers occupies the top.
The writetable commmand in matlab will also write a table variable (rows/columns/headers etc) to an excel spreadsheet.
Verbosing zhqiat's answer, your table could be generated by the following code:
data = [-1.5924 -0.2152 -1.1426 0.0421; -1.5924 -0.2152 -1.1426 0.0421; -1.2319 0.0313 -0.8241 0.2595; 0.2329 1.0332 0.4686 1.1427; 0.2329 1.0332 0.4686 1.1427];
row_names = {'A', 'B', 'C', 'D', 'E'};
var_names = {'met1d2_clo0d5', 'met1d2_clo1d0', 'met1d4_clo0d5', 'met1d4_clo1d0'};
var_description = {'M = 1.2 met - 0.5 clo', 'M = 1.2 met - 1. clo', 'M = 1.4 met - 0.5 clo', 'M = 1.4 met - 1.0 clo' };
testtable = array2table(data, 'VariableNames', var_names, 'RowNames', row_names);
testtable.Properties.VariableDescriptions = var_description;
This would result in something like this:
Screenshot of Matlab-Table
We all might got your question wrong. So please try to refine it, if the right answers are missing.

matlab quadprog constraints issue

I have a portfolio of weights I am using quadprog in matlab.
I have all the inputs for the quadprog optimizer. I am just having some trouble formulating
the constraints
I would like my constraints to have a lower bound of either 0 or 1%, is there a way to do that while maintainng my objective function
Thanks!
I am not sure if I understand your question well.
If your weights are already defined in terms of percentage, it is directly the definition of quadprog:
x = quadprog(H, f, [], [], [], [], lb, [])
So H, e, and f should be provided by the matlab description of:
quadprog(H,f) - returns a vector x that minimizes 1/2 * x' * H * x + f' * x. H must be positive definite for the problem to have a finite minimum."
And lb is a vector of the constraints. For instance if x is a vector 3 x 1, then lb = [0.01; 0.01; 0.01] in the case of the desired percentage is 0.01 (1%)
On the other hand, lets assume the sum_{i=1}^{n} w_i is not equal to 1. Therefore, w_i is not defined in terms of percentage.
Therefore, the constraint that you need is p_i (percentage)= w_i / (sum w_i) >= 0.01 (in the case of the lower bound be 1%).
Note that the constraint in this case is
w_i >= 0.01 * (sum w_i)
Or
-0.01 * (sum_{j=1}^{i-1} w_j) + 0.99 * w_i - 0.01 * (sum_{j=i+1}^{n} w_j) >= 0
Or
0.01 * (sum_{j=1}^{i-1} w_j) - 0.99 w_i + 0.01 * (sum_{j=i+1}^{n} w_j) <= 0
Therefore, this is a constraint of the type Ax <= b.
So
A_ij = 0.01 when i is different from j
A_ij = -0.99 when i = j and b = zeros(n, 1)
In this case you are using
x = quadprog(H, f, A, b)
I hope I helped you!
Daniel

program runs differently depending on the use of cos or cosd( matlab functions)

My Matlab program works properly when the angles are in radians and thus I call cos and sin functions in the code below. When the angles are in degrees and thus I call cosd and sind, my program doesn't work as expected.
%Initial configuration of robot manipulator
%There are 7DOF( degrees of freedom) - 1 prismatic, 6 revolute
%vector qd represents these DOF
%indexes : d = gd( 1), q1 = qd( 2), ..., q6 = qd( 7)
qd( 1) = 1; % d = 1 m
qd( 2) = pi / 2; % q1 = 90 degrees
qd( 3 : 6) = 0; % q2 = ... = q6 = 0 degrees
qd( 7) = -pi / 2;
%Initial position of each joint - the tool is manipulated separately
%calculate sinusoids and cosines
[ c, s] = sinCos( qd( 2 : length( qd)));
and here is the sinCos code
function [ c, s] = sinCos( angles)
%takes a row array of angles in degrees and returns all the
%sin( angles( 1) + angles( 2) + ... + angles( i)) and
%cos( angles( 1) + angles( 2) + ... + angles( i)) where
%1 <= i <= length( angles)
sum = 0;
s = zeros( 1, length( angles)); % preallocate for speed
c = zeros( 1, length( angles));
for i = 1 : length( angles)
sum = sum + angles( i);
s( i) = sin( sum); % s( i) = sin( angles( 1) + ... + angles( i))
c( i) = cos( sum); % c( i) = cos( angles( 1) + ... + angles( i))
end % for
% end function
The whole program is ~ 700 lines, so I displayed only the part above. My program simulates the motion of a redundant robot that tries to reach a goal while avoiding two obstacles.
So, does my problem relates to cos and cosd? Do cos and cosd have a different behavior that affects my program? Or I have a bug in my program that is revealed?
By difference, do you mean something on the order of less than .00001? Because extremely small errors can be discounted due to floating point arithmetic errors. Computers are not able to accurately calculate decimal numbers with as much accuracy as they are able to store them. It is for this reason you should never directly compare two floating-point numbers; a range of error must be allowed for. You can read more about this here: http://en.wikipedia.org/wiki/Floating_point#Machine_precision_and_backward_error_analysis
If your error is greater than .0001 or so, you might consider searching for a bug in your program. If you are not already using matlab to convert units for you, consider doing so as I have found that it can eliminate many 'obvious' errors (and in some cases increase precision).