#
#	Experimental code to compute NNI distances between
#	two trees.
#
#	The minimum NNI distance is an NP-complete problem, so this
#	algorithm is by nature an approximation.
#
#	Gaston H. Gonnet (Apr 3rd, 2012)
#
NNIdistance := proc( t1:Tree, t2:Tree ) -> posint;

LeafSet := proc( t:Tree )
if type(t,Leaf) then [t,{t[1]}]
else r1 := LeafSet(t[1]);
     r2 := LeafSet(t[3]);
     r := r1[2] union r2[2];
     [ Tree(r1[1],t[2],r2[1],r), r ]
fi end:

AllLeafSets := proc( t:Tree )
if type(t,Leaf) then {}
else AllLeafSets(t[1]) union AllLeafSets(t[3]) union {t[4]} fi end:

NewLabel := proc()
s := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
r := s[Rand(1..26)];
to 9 do r := r . s[ Rand(1..length(s)) ] od;
r end:

r := LeafSet(t1);  ls1 := r[2];  T1 := r[1];
r := LeafSet(t2);  ls2 := r[2];  T2 := r[1];

if ls1 <> ls2 then error('the NNIdistance can only be computed for trees over the same leaf-set')
elif length(ls1) <= 3 then return(0) 
elif length(ls1) = 4 then
     error('code not correct');
     return( If( AllLeafSet(T1) = AllLeafSet(T2), 0, 1 ))
elif BipartiteSquared(t1,t2) = 0 then return(0)
fi;

n := length(ls1);
cls := sort( AllLeafSets(T1) intersect AllLeafSets(T2) minus {ls1},
	x -> |length(x)-n/2| );
if cls <> [] then
     # there is a reasonable internal edge to divide the problem
     #
     #  T1 := T1(cls1)-------T1(rest)
     #  T2 := T2(cls1)-------T2(rest)
     #  NNId(T1,T2) = NNId( XXX1------T1(rest), XXX1------T2(rest) ) +
     #                NNId( T1(cls1)------XXX2, T2(cls1)------XXX2 )
     #
     cls1 := cls[1];
     ccls1 := ls1 minus cls1;
     assert( length(cls1) >= 2 and length(cls1) <= n-2 );
     XXX1 := NewLabel();
     XXX2 := NewLabel();

     # make the trees XXX1------T1(rest) and T1(cls1)------XXX2
     for t in Infix(T1) do
	if type(t,Leaf) then next
	elif not type(t[1],Leaf) and (t[1,4]=cls1 or t[1,4]=ccls1) then
	    tt1 := t;  k1 := 1;  break
	elif not type(t[3],Leaf) and (t[3,4]=cls1 or t[3,4]=ccls1) then
	    tt1 := t;  k1 := 3;  break
	fi
     od;
     # beware, the original T1 is now modified
     if tt1[k1,4]=cls1 then
	  T1_XXX2 := Tree(Leaf(XXX2,tt1[2]+1),tt1[2],tt1[k1]);
	  t := tt1[k1];  tt1[k1] := Leaf(XXX1,tt1[k1,2]);  XXX1_T1 := T1
     else XXX1_T1 := Tree(Leaf(XXX1,tt1[2]+1),tt1[2],tt1[k1]);
	  t := tt1[k1];  tt1[k1] := Leaf(XXX2,tt1[k1,2]);  XXX2_T1 := T1
     fi;

     # make the trees XXX1------T2(rest) and T2(cls1)------XXX2
     for t in Infix(T2) do
	if type(t,Leaf) then next
	elif not type(t[1],Leaf) and (t[1,4]=cls1 or t[1,4]=ccls1) then
	    tt2 := t;  k2 := 1;  break
	elif not type(t[3],Leaf) and (t[3,4]=cls1 or t[3,4]=ccls1) then
	    tt2 := t;  k2 := 3;  break
	fi
     od;
     # beware, the original T2 is now modified
     if tt2[k2,4]=cls1 then
	  T2_XXX2 := Tree(Leaf(XXX2,tt2[2]+1),tt2[2],tt2[k2]);
	  t := tt2[k2];  tt2[k2] := Leaf(XXX1,tt2[k2,2]);  XXX1_T2 := T2
     else XXX1_T2 := Tree(Leaf(XXX1,tt2[2]+1),tt2[2],tt2[k2]);
	  t := tt2[k2];  tt2[k2] := Leaf(XXX2,tt2[k2,2]);  XXX2_T2 := T2
     fi;

     return( procname(XXX1_T1,XXX1_T2) + procname(T1_XXXX2,T2_XXX2) );
fi;


error('code incomplete')

end:

if false then

OpenWriting(tmp2);
Set(gc=1e8):
ReadProgram( '/home/darwin/v2/source/bio-recipes/Orthologues/OMAGroups/Firmicutes89/411xx/3955' );
inds := Shuffle( [op(Indices(Trees))] ):
t1 := Trees[inds[1],Tree];
t2 := Trees[inds[2],Tree];
printlevel := 3;
NNIdistance(t1,t2);
done

fi:
