(*Exercise 3*)
rats={{1.4,1},{2.2,1.5},{3,1.7}};
squirrels={{1,1.5},{2,2.2},{2.3,2}};

(*Plots the data*)
ratsPlot=ListPlot[rats,PlotStyle->{Red,Thick}];
squirrelsPlot=ListPlot[squirrels,PlotStyle->{Blue,Thick}];
Show[ratsPlot,squirrelsPlot,PlotRange->{{0,4},{0,3}},AxesOrigin->{0,0},ImageSize->Large]

(*What separating line is the "best" one?*)
Manipulate[Show[Plot[a x+ b,{x,0,4},PlotStyle->{Black,Thick},PlotRange->{{0,4},{0,3}},ImageSize->Large],ratsPlot,squirrelsPlot],{{a,0.5},-2,2},{{b,.7},-2,2}]

(*Constraints are:*)
const1=And@@Table[squirrels[[i,2]]≥a squirrels[[i,1]]+b+d,{i,1,3}]
const2=And@@Table[rats[[i,2]]≤a rats[[i,1]]+b-d,{i,1,3}]

(*Answer:*)
sol=Maximize[d,const1&&const2,{a,b,d}]
optimalSep=Plot[a x+ b/.sol[[2]],{x,0,4},PlotStyle->{Black,Thick},PlotRange->{{0,4},{0,3}}];
band=RegionPlot[a x+ b-d≤ y≤a x+ b+d/.sol[[2]],{x,0,4},{y,0,3},PlotStyle->LightGray,BoundaryStyle->Gray];
Show[band,ratsPlot,squirrelsPlot,optimalSep,ImageSize->Large]

(*Checking signs:*)
Table[a rats[[i,1]]-rats[[i,2]]+b/. sol[[2]],{i,1,3}]
Table[a squirrels[[i,1]]-squirrels[[i,2]]+b/. sol[[2]],{i,1,3}]

(*Doing it by hand, with two-phase simplex method with variables: a,b,d,s1,s2,s3,s4,a1,s5,a2,s6,a3,*)
A={{1,1,1,1,0,0,0,0,0,0,0,0,1.5},{2,1,1,0,1,0,0,0,0,0,0,0,2.2},{2.3,1,1,0,0,1,0,0,0,0,0,0,2},{1.4,1,-1,0,0,0,-1,1,0,0,0,0,1},{2.2,1,-1,0,0,0,0,0,-1,1,0,0,1.5},{3,1,-1,0,0,0,0,0,0,0,-1,1,1.7}};
targetI=-{0,0,0,0,0,0,0,1,0,1,0,1,0};(*Phase I is to minimize sum of artificial variables*)

tab1=tableau[A,targetI,{4,5,6,8,10,12}]
thetas[tab1,1]

tab2=tableau[A,targetI,{4,5,6,8,10,1}]
thetas[tab2,2]

tab3=tableau[A,targetI,{4,5,6,2,10,1}]
thetas[tab3,7]

tab3=tableau[A,targetI,{4,5,6,2,7,1}]

(*End of Phase I, no basic artificial variables*)

(*Phase II*)
A=tab3[[1]][[2;;7,{2,3,4,5,6,7,8,10,12,14}]];
targetII={0,0,-1,0,0,0,0,0,0,0};(*original target function*)

tab1=tableau[A,targetII,{4,5,6,2,7,1}]
thetas[tab1,3]

tab2=tableau[A,targetII,{3,5,6,2,7,1}]
thetas[tab2,9]

tab3=tableau[A,targetII,{3,5,9,2,7,1}]

(*This is the optimal solution; discard quantities less than 10^-10 and take them to be 0.*)