<< "C:\\drorbn\\AcademicPensieve\\Projects\\Arrow_Diagrams_and_gl(N)\\Arrow_Diagrams_and_gl(N).m"

NoOfDiags=Length[AllDiags=Diagrams[4ar]]

DiagToIndex = Dispatch[Thread[AllDiags -> Array[B, {NoOfDiags}]]]

OurBasis=BasisAArrow[4] /. DiagToIndex

NoOfRels=Length[Rels=R /@ Diagrams[R6T+2ar] /. DiagToIndex]

v68={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,1,0,0,-1,1,0,0,0,0,0,0,0,0,-1,-1,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0,0,0,0,0,-1,-1,0,0,-1,0,0,0,1,1,1,1,1,-1,1,0,0,0,0,1,1,0,1,0,1,0,0,-1,-1,0,0,1,0,0,0,-1,-1,-1,-1,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,-1,-1,1,1,3,0,-2,2,-1,-1,-1,-1,-1,-1,2,1};
v=v68;
v=First[simplenull];
v=simplenull[[2]];
V = v.OurBasis

Norm2[expr_] := Length[expr];
Norm2[expr_] := expr /. c_.*B[_] :> Abs[c];
Norm2[V]

BestV=V;
Norm2BestV=Norm2[BestV];
Dynamic[{Norm2BestV, BestV}]

While[True,
k=RandomInteger[{1,NoOfRels}];
s=If[Random[]>0.5, 1, -1];
NewV=BestV+ s*Rels[[k]];
If[Norm2[NewV]<Norm2BestV,
BestV=NewV;
Norm2BestV=Norm2[BestV]
]
]

Tally[Length /@ Union[Rels]] // Sort

m=4;
diags=Diagrams[m ar];
rels=R /@ Diagrams[R6T+(m-2)ar];
mat = SparseArray[
Join @@ Table[
rel=rels[[i]];
{i,Position[diags, #][[1,1]]} -> Coefficient[rel, #]& /@ Cases[rel, diag_Diag, Infinity],
{i,Length[rels]}
],
{Length[rels], Length[diags]}
]

rmat=LatticeReduce[mat // Transpose];

DeleteCases[Flatten[rmat], 0]  // Length

matrix=Normal[mat];
Print[{norms=(#.#)& /@ matrix; changes, Total[norms], Sort[Tally[norms]]}];
Dynamic[{norms=(#.#)& /@ matrix; changes, Total[norms], Sort[Tally[norms]]}]

T=0.05;
bestnorm = Min[(#.#)& /@ matrix];
While[True,
i=RandomInteger[{1, Length[matrix]}];
j=RandomInteger[{1, Length[matrix]}];
While[i==j, j=RandomInteger[{1, Length[matrix]}]];
s=If[Random[]>0.5, 1, -1];
new=matrix[[i]]+s*matrix[[j]];
(* new /= GCD@@new; *)
If[(norm=new.new) < matrix[[i]].matrix[[i]] || T>0 && Random[]<E^(-1/T),
matrix[[i]] = new;
++changes;
If[norm<bestnorm, bestnorm=norm]
]
]