Simulation of Gisin & Gisin Model by John Reed (2014)
Modified by Fred Diether, Jan. 2022.

(* simulation of Gisin & Gisin model *)
(* build λ, the hidden variable *)
m=10000;
z=RandomReal[{-1,1},m];
t=RandomReal[2π,m];
r=Sqrt[1-z^2];
x=r Cos[t];
y=r Sin[t];
λ={x,y,z};
noise=RandomReal[{0,1},m];

Δangle=1;
nAngle=360/Δangle;
(*angles=Table[angle[j]=π/180 Δangle (j-1),{j,1,nAngle}];*)
angles=Table[angle[j]=π/180 Δangle (j),{j,1,nAngle}];
correlationArray=ConstantArray[0,nAngle];
nHits=ConstantArray[0,nAngle];
AB=ConstantArray[0,m];
β=1*2π/360;
b={Cos[β],Sin[β],0};
B=Sign[b.λ];

Do[      (* Do loop i over each angle in nAngle *)
α=angles[[i]]+π/180;
        a={Cos[α],Sin[α],0};
A1=a.λ;
A=Sign[a.λ];
   (* Do loop j over samples *)
jCorr=0;
jHits=0;

If[Abs[A1[[j]]]>noise[[j]],{  (*If true, this is a good hit *)
jHits+=1;
jCorr+=A[[j]]*B[[j]]}];
AB[[j]]=jCorr;
nHits[[i]]+=jHits;
correlationArray[[i]]+=-jCorr,{i,nAngle},{j,m}]
normCorr=correlationArray/nHits//N;

data=ListPlot[normCorr,PlotMarkers->{Automatic,Small},DataRange->{0,360}];
negcosine=Plot[-Cos[w*Degree],{w,0,360},PlotStyle->{Magenta}];
Show[{data,negcosine}]

Length[AB]

Total[AB]

A
B