%  This code implements the model described in the paper that was published in Climate
%
%  https://www.mdpi.com/2225-1154/13/9/194
%
%
%  It implements two different values of the parameter delta 
%  one for the support group called deltaS and the other for the opposed group called deltaO
%  each of these are time constants that give the time frame of people leaving the group independent 
%   of their interactions with those in other groups
%  In this code the parameter beta in the paper is called B. 
%
%% y(1) is the Support group size
% y(2) is the Oppose Group size
%
%   In this codde the size of the groups are scaled to be the fraction of total population 
%
%   Setup the parameters
piis=.9;
piio=.9;
pias=.9;
piao=.9;
deltaS=3.;
deltaO=3.;
phi=.9;
r=1.;
rho=.2;
% yp(1) is the RHS for ODE for Support
% yp(2) is the RHS for ODE for Oppose
%
% grouped parameters in model are
A=phi*rho;
B=.15;
%
% which is called beta in the papaer
%
C=(1-pias)*(1-piao);

par=[A; B; C; P; phi; piis; piio; deltaS; deltaO; r];

initcon=[.35 .4];

F=ode(ODEFcn=@Opinion,InitialValue=initcon,Parameters=par);
sol1=solve(F,0,1000);

plot(sol1.Time,sol1.Solution,"-o")
legend("Support","Opposed")
title("Opinion Dynamics over time",Interpreter="latex")
xlabel("Time",Interpreter="latex")
ylabel("Group Size",Interpreter="latex")
aa=sol1.Solution(1,end);
bb=sol1.Solution(2,end);
cc=P-aa-bb;
XX=['Ending Support ,  Ending Neutral,  Ending Oppose'];
disp(XX)
YY=[aa,cc,bb];
disp(YY)


function yp=Opinion(t,y,par)
%
% Social Infliuence and Personal Experience Combined Opinion Model
%
A = par(1);
B = par(2);
C = par(3);
P = par(4);
phi = par(5);
piis = par(6);
piio = par(7);
deltaS = par(8);
deltaO = par(9);
r = par(10);

 yp=[A*r*(1-y(1)-y(2))-A*(1-piis)*(1-piis)*y(1)/r+(1-phi)*(1-y(1)-y(2))*B*y(1)-(1-phi)*(1-piis)*B*C*y(1)*y(2)-(1/deltaS)*y(1);
   A*(1-y(1)-y(2))/r-A*r*(1-piio)*(1-piio)*y(2)+(1-phi)*(1-y(1)-y(2))*B*y(2)-(1-phi)*(1-piio)*B*C*y(1)*y(2)-(1/deltaO)*y(2)];

end
