Ultimate local-realistic CHSH simulation of two level entangled state event by event.
 By Fred Diether with 2D vectors, also with Joy’s hidden variable and modified
 epr-simple by Michel Fodje.  Some parts by John Reed.

<<Quaternions`;
β0=Quaternion[1,0,0,0];
β1=Quaternion[0,1,0,0];
β2=Quaternion[0,0,1,0];
β3=Quaternion[0,0,0,1];
Qcoordinates={β1,β2,β3};
m=5000;
plotArray1=Table[{0,0,0,0,0},m];
plotArray2=Table[{0,0,0,0,0},m];
plotArray3=Table[{0,0,0,0,0},m];
Do[vectorA=RandomChoice[{{1,0,0},{0,1,0}}];  (*0 and 90 degrees x-y*)
vectorB=RandomChoice[{{-(1/(Sqrt[2])),-(1/(Sqrt[2])),0},{-(1/(Sqrt[2])),(1/(Sqrt[2])),0}}];  (*-135, +135*)
vectorS=Flatten[{RandomPoint[Circle[]],0}]; (*Singlet spin vector*)
s1=ToSphericalCoordinates[vectorS][[3]];
λ2=(12/64)Cos[(s1/2)]^2;  (*hidden variable*)
λ=RandomChoice[{-1,1}];  (*hidden variable*)
Da=vectorA.Qcoordinates;  (*Convert to quaternion coordinates*)
Db=vectorB.Qcoordinates;
Ls1=λ*vectorS.Qcoordinates; (*singlet spin quaternion*)
Ls2=-Ls1;
If[Abs[Re[Da**Ls1]]>λ2,A=Sign[Re[Da**Ls1]],A=Null];
If[Abs[ArcTan[vectorA[[1]],vectorA[[2]]]]<((5π)/16), Aa=1,Aa=Null];
If[Abs[ArcTan[vectorA[[1]],vectorA[[2]]]]<((5π)/16), AA=-1,AA=Null];
If[Abs[Re[Ls2**Db]]>λ2,B=Sign[Re[Db**Ls2]],B=Null ];
If[((14π)/64)<Abs[ArcTan[vectorB[[1]],vectorB[[2]]]]<((32π)/32), Bb=1,Bb=Null];
If[Abs[ArcTan[vectorB[[1]],vectorB[[2]]]]<((5π)/16), BB=1,BB=Null];
plotArray1[[i]]={vectorA,vectorB,A,B,i};
plotArray2[[i]]={vectorA,vectorB,Aa,Bb,i};
plotArray3[[i]]={vectorA,vectorB,AA,BB,i},{i,m}]
neg=DeleteCases[plotArray3,{_,_,Null, Null,_}];
neg1=DeleteCases[neg,{_,_,_,Null,_}];
neg2=DeleteCases[neg1,{_,_,Null,_,_}];
pos=DeleteCases[plotArray2,{_,_,Null, Null,_}];
pos1=DeleteCases[pos,{_,_,_,Null,_}];
pos2=DeleteCases[pos1,{_,_,Null,_,_}];
negpos=Catenate[{neg2,pos2}];
abab=DeleteCases[plotArray1,{_,_,Null, Null,_}];
abab1=DeleteCases[abab,{_,_,_,Null,_}];
abab2=DeleteCases[abab1,{_,_,Null,_,_}];
abab3=Catenate[{abab2,negpos}];

CHSH Analysis of Particle Data

N1=Length[abab3];
a1=ConstantArray[0,N1];
b1=ConstantArray[0,N1];
A1=ConstantArray[0,N1];
B1=ConstantArray[0,N1];
a=abab3[[All,1]];b=abab3[[All,2]];A1=abab3[[All,3]];B1=abab3[[All,4]];

nP1=0; nN1=0; nP2=0; nN2=0; nP3=0; nN3=0;nP4=0;  nN4=0;
Do[aa=a[[j]];
a1[[j]]=ArcTan[aa[[1]],aa[[2]]]*180/π;
bb=b[[j]];
b1[[j]]=ArcTan[bb[[1]],bb[[2]]]*180/π;
aliceD=A1[[j]];bobD=B1[[j]];
If[(a1[[j]]-b1[[j]])==135&&aliceD*bobD==1,nP1++];
If[(a1[[j]]-b1[[j]])==135&&aliceD*bobD==-1,nN1++];If[(a1[[j]]-b1[[j]])==-135&&aliceD*bobD==1,nP2++];
If[(a1[[j]]-b1[[j]])==-135&&aliceD*bobD==-1,nN2++];If[(a1[[j]]-b1[[j]])==225&&aliceD*bobD==1,nP3++];
If[(a1[[j]]-b1[[j]])==225&&aliceD*bobD==-1,nN3++];
If[(a1[[j]]-b1[[j]])==-45&&aliceD*bobD==1,nP4++];
If[(a1[[j]]-b1[[j]])==-45&&aliceD*bobD==-1,nN4++],{j,N1}]
E1=N[(nP1-nN1)/(nP1+nN1)];
E2=N[(nP2-nN2)/(nP2+nN2)];
E3=N[(nP3-nN3)/(nP3+nN3)];
E4=N[(nP4-nN4)/(nP4+nN4)];
CHSH=Abs[E1+E2+E3-E4];
Print["CHSH = ", CHSH]