
ClearAll["Global`*"];


(***********getting the initial seed***************)
(*gets random fractions in (-1,1)*)
randomFrac[] := RandomInteger[{-75, 75}]/100;
seedA=randomFrac[];
seedB=randomFrac[];
Print["test parameters ",seedA,"  ",seedB];
(***********done getting seed**********************)




(**************doing the pappus iteration**********)

(**start with counterclockwise labels*)

markedBox[a_, b_] := {
  {-1, 1, 1},
  {-1, -a, 1},
  {-1, -1, 1},
  {1, -1, 1},
  {1, b, 1},
  {1, 1, 1}
};

intersection[p_, q_, r_, s_] := Cross[Cross[p, r], Cross[q, s]];


(*The two Pappus rules:*)

boxReverse[{lp_,l_,lm_,rm_,r_,rp_}]:={lm,l,lp,rp,r,rm};

left[m_] := (
  {lp, l0, lm, rm, r0, rp} = m;
  {
    lp, l0, lm,
    intersection[l0, lm, rm, r0],
    intersection[lp, lm, rm, rp],
    intersection[lp, l0, r0, rp]
  }
);

right[m_] := (
  {lp, l0, lm, rm, r0, rp} = m;
   boxReverse[ {
    intersection[lp, l0, r0, rp],
    intersection[lp, lm, rm, rp],
    intersection[l0, lm, rm, r0],
    rm, r0, rp}]
);

geometricSub[k_, m_] := If[k == 1, left[m], right[m]];

(**************done with the pappus iteration************)



(***********computes marked boxes and quads****************)

(*Generate all marked boxes without reversing any labels*)

boxD0 = markedBox[seedA, seedB];
boxD1 = Table[geometricSub[k, boxD0], {k, 1, 2}];
boxD2 = Flatten[Table[geometricSub[k, boxD1[[j]]], {j, 1, 2}, {k, 1, 2}], 1];
boxD3 = Flatten[Table[geometricSub[k, boxD2[[j]]], {j, 1, 4}, {k, 1, 2}], 1];
boxD4 = Flatten[Table[geometricSub[k, boxD3[[j]]], {j, 1, 8}, {k, 1, 2}], 1];

(*Converts the marked box to the quad.
Quad orientation (c vs cc) is the same as box orientation*)

toQuad[m_] := (
  {lp, l0, lm, rm, r0, rp} = m;
  q2 = l0;
  q1 = intersection[lp, l0, r0, rp];
  q0 = r0;
  q3 = intersection[l0, lm, rm, r0];
  q = {q0, q1, q2, q3};
  Table[{q[[i, 1]]/q[[i, 3]], q[[i, 2]]/q[[i, 3]]}, {i, 1, 4}]
);

(*Extract all quads from the marked boxes*)

quadD0 = toQuad[boxD0];
quadD1 = Table[toQuad[boxD1[[j]]], {j, 1, 2}];
quadD2 = Table[toQuad[boxD2[[j]]], {j, 1, 4}];
quadD3 = Table[toQuad[boxD3[[j]]], {j, 1, 8}];
quadD4 = Table[toQuad[boxD4[[j]]], {j, 1, 16}];

(*********done computing boxes and quads*****************)



(***********compute direct matrices*********************)
(*Projective map from a quad to the square [-1,1]^2*)

squareMap[m_]:=(
m2=Table[Append[m[[j]],1],{j,1,4}];
squareMap0[m2])

squareMap0[{V0_,V1_,V2_,V3_}]:=
Simplify[
  {{-1,-1,1},{-1,1,1},{1,-1,1}} .
  {
    Cross[V1,V2]/Det[{V1,V2,V3}],
    Cross[V2,V0]/Det[{V2,V0,V3}],
    Cross[V0,V1]/Det[{V0,V1,V3}]
  }
]


(*Projective map carrying Q1 to Q2*)

proj[Q1_,Q2_]:=(
mx1=squareMap[Q1];
mx2=squareMap[Q2];
Inverse[mx2].mx1)

matxD4=Table[proj[quadD0,quadD4[[j]]],{j,1,16}];
(********************done computing direct matrices*******************)





(************this computes the base map*****************************)

(*The normalized quad with invariants alpha=(a,b)
  and tau=(t1,t2)*)

normalizedQuad[a_,b_,t1_,t2_]:=(
P0={(a-1)/2,0};
P1=(b-1)/2 {t1,t2};
P2={(a+1)/2,0};
P3=(b+1)/2 {t1,t2};
PP0=Append[P0,1];
PP1=Append[P1,1];
PP2=Append[P2,1];
PP3=Append[P3,1];
{PP0,PP1,PP2,PP3})

QQ0={-1,-1,1};
QQ1={+1,-1,1};
QQ2={+1,+1,1};
QQ3={-1,+1,1};

rawBaseMap[RR0_,RR1_,RR2_,RR3_]:=(
{PP0,PP1,PP2,PP3}=normalizedQuad[a,b,t1,t2];
mm=squareMap0[{PP0,PP1,PP2,PP3}];
nn=Inverse[mm];

SS0=nn.RR0;
SS1=nn.RR1;
SS2=nn.RR2;
SS3=nn.RR3;

S0=Take[SS0,2]/SS0[[3]];
S1=Take[SS1,2]/SS1[[3]];
S2=Take[SS2,2]/SS2[[3]];
S3=Take[SS3,2]/SS3[[3]];

A0=Det[{S3-S0,S1-S0}];
A1=Det[{S0-S1,S2-S1}];
A2=Det[{S1-S2,S3-S2}];
A3=Det[{S2-S3,S0-S3}];

AA=A0+A1+A2+A3;
B0=2 A0/AA;
B1=2 A1/AA;
B2=2 A2/AA;
B3=2 A3/AA;

alphaPrime=Factor[{B2-B0,B3-B1}])


baseMatrix[RR0_,RR1_,RR2_,RR3_]:=(
alphaPrime=rawBaseMap[RR0,RR1,RR2,RR3];
den=Denominator[alphaPrime[[1]]];
aa1=Expand[den alphaPrime];
aa2=Append[aa1,den];

mat=Table[
 {Coefficient[aa2[[i]],a],
  Coefficient[aa2[[i]],b],
  aa2[[i]]/.{a->0,b->0}},
 {i,1,3}];

Factor[mat])

(**************done with general base map calculation*************)






(***************computing the base maps.*********************)
(*the subdivision points*)
ss0={-u0,-1,1};
ss1={1,-u1,1};
ss2={+u2,1,1};
ss3={-1,u3,1};

zz=Cross[Cross[ss0,ss2],Cross[ss1,ss3]];

uu0 = -(1 + a b - b + 3 a)/(3 - a b + a + b);
uu1 =  (1 + a b + a - 3 b)/(3 - a b - a - b);
uu2 = -(1 + a b - a + 3 b)/(3 - a b + a + b);
uu3 =  (1 + a b + b - 3 a)/(3 - a b - a - b);

(*This comes from the general derivation file*)
subLeft  = baseMatrix[QQ0, ss3, zz, ss0];
subRight = baseMatrix[zz, ss1, QQ2, ss2];

(*These are the pappus subdivision rules*)
rulesA = {u0 -> uu0, u1 -> uu1, u2 -> uu2, u3 -> uu3};
rulesB = rulesA /. {a -> -b, b -> a};
rulesC = rulesA /. {a -> -a, b -> -b};
rulesD = rulesA /. {a -> b, b -> -a};

(*These are the base maps at each level*)
subA = {subLeft/.rulesA, subRight/.rulesA};
subB = {subLeft/.rulesB, subRight/.rulesB};
subC = {subLeft/.rulesC, subRight/.rulesC};
subD = {subLeft/.rulesD, subRight /.rulesD};

(*These are the depth 4 compositions*)
baseD4 = Flatten[Table[Simplify[subD[[i]].subC[[j]].subB[[k]].subA[[l]]],{i,1,2},{j,1,2},{k,1,2},{l,1,2}],3];
(********************done defining the base maps**********************************)





(*******************matrix identity tests:********************)
(*this is the algebraic miracle: the base maps equal the direct maps*)

a=seedA;
b=seedB;

testD4Raw=Table[Inverse[baseD4[[j]]].matxD4[[j]],{j,1,16}];
testD4=Table[Simplify[testD4Raw[[j]]/testD4Raw[[j,1,1]]],{j,1,16}];
Print["matrix identity check"];
Print[testD4];
(****************done with matrix identity tests****************)




(***********************base action sanity check*********************)
(**checks that base matrices map the initial area-invariant point
   to the area invariants of the 16 depth 4 quads.  The permutation
   implements the "reverse and switch rule."*)


(* first compute area invariant*)

areaTri[Q_, k_] := (
  i0 = Mod[k - 2, 4] + 1;
  i1 = k;
  i2 = Mod[k, 4] + 1;
  v = Q[[i0]] - Q[[i1]];
  w = Q[[i2]] - Q[[i1]];
  Det[{v, w}]
);

AS[Q_] := (
  aa = Table[areaTri[Q, k], {k, 1, 4}];
  s = aa[[1]]+aa[[2]]+aa[[3]]+aa[[4]];
  aa = 2 aa/s;
  xx = aa[[3]] - aa[[1]];
  yy = aa[[4]] - aa[[2]];
  {xx,yy}
);

(*now check the base action*)

Print["point check"];
pointD0 = AS[quadD0];
pointsD4 = Table[AS[quadD4[[j]]], {j, 1, 16}];
pointsCheckD4Raw = Table[baseD4[[j]].Append[pointD0, 1], {j, 1, 16}];
pointsCheckD4 = Table[Simplify[Take[pointsCheckD4Raw[[j]], 2]/pointsCheckD4Raw[[j, 3]]], {j, 1, 16}];
perm = {16, 8, 12, 4, 14, 6, 10, 2, 15, 7, 11, 3, 13, 5, 9, 1};
imageTest = Table[Simplify[pointsD4[[perm[[j]]]] - pointsCheckD4[[j]]], {j, 1, 16}];
Print[imageTest];

Print["action of permutation"];
indices0 = Tuples[{0, 2}, 4];
indices1 = Table[indices0[[perm[[j]]]], {j, 1, 16}];
indices2 = Table[Join[indices0[[j]], {"   "}, indices1[[j]]], {j, 1, 16}];
Print[MatrixForm[indices2]];
(***********done with base action check********************************)




(******************checks that the subdivision rule works***********)

(*all orientations counterclockwise: standard rule as in Ch2 of the paper, followed by orientation reversal*)
subdivideUnitSquare0[u_]:=(
  pt1={-u[[1]],-1,1};
  pt2={1,-u[[2]],1};
  pt3={u[[3]],1,1};
  pt4={-1,u[[4]],1};
  xx=Cross[Cross[pt1,pt3],Cross[pt2,pt4]];
  xx=Simplify[xx/xx[[3]]];
  v0={-1,-1,1};
  v1=pt1;
  v2=xx;
  v3=pt4;
(*note the orientation reversal. This matches the paper.*)
  {v0,v3,v2,v1})

(*all orientations counterclockwise: standard rule as in Ch2 of paper*)

quadReverse[{q1_,q2_,q3_,q4_}]:={q1,q4,q3,q2};

(*standard subdivision rule*)

subdivideUnitSquare2[u_]:=(
  pt1={-u[[1]],-1,1};
  pt2={1,-u[[2]],1};
  pt3={u[[3]],1,1};
  pt4={-1,u[[4]],1};
  xx=Cross[Cross[pt1,pt3],Cross[pt2,pt4]];
  xx=Simplify[xx/xx[[3]]];
  v0=xx;
  v1=pt2;
  v2={1,1,1};
  v3=pt3;
  {v0,v1,v2,v3})

subdivideGeneral0[u_,Q_]:=(
  mm=squareMap0[Q];
  mm=Inverse[mm];
  IQ=subdivideUnitSquare0[u];
  IQ=Table[mm.IQ[[j]],{j,1,4}];
  Table[Simplify[IQ[[j]]/IQ[[j,3]]],{j,1,4}])


subdivideGeneral2[u_,Q_]:=(
  mm=squareMap0[Q];
  mm=Inverse[mm];
  IQ=subdivideUnitSquare2[u];
  IQ=Table[mm.IQ[[j]],{j,1,4}];
  Table[Simplify[IQ[[j]]/IQ[[j,3]]],{j,1,4}])

rho[Q_]:={Q[[3]],Q[[4]],Q[[1]],Q[[2]]};

rule0={u0,u1,u2,u3}/.rulesA;
rule1={u0,u1,u2,u3}/.rulesB;
rule2={u0,u1,u2,u3}/.rulesC;
rule3={u0,u1,u2,u3}/.rulesD;

homogeneousQuad[Q_] := Table[Append[Q[[j]], 1], {j, 1, 4}];


subdivisionCheck[u_, Q_, QL_, QR_] := Module[{P, X, Y},
  P = homogeneousQuad[Q];
  X = subdivideGeneral0[u, P];
  Y = homogeneousQuad[QR];
  Print[Simplify[X - Y]];
  X = subdivideGeneral2[u, P];
  Y = homogeneousQuad[QL];
  Print[Simplify[X - Y]];
];

Print["subdivision rule check"];

subdivisionCheck[rule0, quadD0, quadD1[[1]], quadD1[[2]]];
Table[subdivisionCheck[rule1, quadD1[[j]], quadD2[[2 j - 1]], quadD2[[2 j]]], {j, 1, 2}];
Table[subdivisionCheck[rule2, quadD2[[j]], quadD3[[2 j - 1]], quadD3[[2 j]]], {j, 1, 4}];
Table[subdivisionCheck[rule3, quadD3[[j]], quadD4[[2 j - 1]], quadD4[[2 j]]], {j, 1, 8}];



(****************done subdivision rule************)




(****************base case check******************)
(*This checks that the algebraic invariant of Q is the projective center of Q*)

Print["initial invariant check"];
pt0=AS[quadD0];
qqD0=Table[Append[quadD0[[j]],1],{j,1,4}];
pt1=Cross[Cross[qqD0[[1]],qqD0[[3]]],Cross[qqD0[[2]],qqD0[[4]]]];
pt1=pt1/pt1[[3]];
pt1=Take[pt1,2];
diff01=Simplify[pt0-pt1];
Print["point difference ",diff01];





(************graphics check******************)
pointsD4 = Table[AS[quadD4[[j]]], {j,1,16}];

frame={{-1,-1},{-1,1},{1,1},{1,-1}};
Graphics[{
  EdgeForm[Black],
  White, Polygon[frame],
  Yellow, Polygon[quadD0],
  Pink, Table[Polygon[quadD4[[j]]], {j,1,16}],
  Black, PointSize[0.015], Point[pointsD4]
}]
(***********done with graphics check******************)