(*Exercise 2*)
(* variables: a1, a2, b, d, x1, x2, x3, x4, x5, x6.
Artificial vars: x2, x6*)
A={{1,-1,1,1,1,0,0,0,0,0,1},
{1,-1,1,-1,0,-1,0,0,1,0,0},
{0,0,1,1,0,0,1,0,0,0,1},
{0,0,1,-1,0,0,0,-1,0,1,0}};
(*Phase I*)
targetI={0,0,0,0,0,0,0,0,-1,-1,0};

tab1=tableau[A,targetI,{5,9,7,10}]
thetas[tab1,1]

tab2=tableau[A,targetI,{5,1,7,10}]
thetas[tab2,3]

tab3=tableau[A,targetI,{5,1,7,3}]

(*End of Phase I*)

(*Phase II*)
AII=tab3[[1]][[2;;5,{2,3,4,5,6,7,8,9,12}]];
targetII={0,0,0,-1,0,0,0,0,0};

tab1=tableau[AII,targetII,{5,1,7,3}]
thetas[tab1,4]

tab2=tableau[AII,targetII,{4,1,7,3}]

(*Optimal solution is a=0, b=1/2 and optimal value is delta=1/2.*)

(*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}]

(*Solving via two-phase simplex method with variables: a,b,d,s1,s2,s3,a1,s4,a2,s5,a3,s6. *)
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]

(*Note: using Chop to round quantities less than 10^(-10) to zero*)

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

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

tab3=Chop[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=Chop[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. Recall x1=a, x2=b, x3=d*)
optsol={a->0.384615,b->0.8846153846153846`,d->0.2307692307692308`};
optimalSep=Plot[a x+ b/.optsol,{x,0,4},PlotStyle->{Black,Thick},PlotRange->{{0,4},{0,3}}];
band=RegionPlot[a x+ b-d≤ y≤a x+ b+d/.optsol,{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/. optsol,{i,1,3}]
Table[a squirrels[[i,1]]-squirrels[[i,2]]+b/. optsol,{i,1,3}]

(*Checking with Mathematica built-in maximize function:*)
sol=Maximize[d,const1&&const2,{a,b,d}][[2]]
optsol