Agglomerative Nesting

Input: data set 𝒜 ⊂ (ℝ^n), parameter p=1 or 2 specifying whether to use (Subscript[ℓ, 1])-norm or LS distance-like function,parameter DD specifying the distance function between sets: DD=0: Dc-distance.  DD=1: Dmin1-distance;  DD=2: Dmin2-distance; DD=5: Ward.If DD=1, it should be p=1; If DD=2, it should be p=2;
If Ind≠0, Print: DistanceMatrix, Figure;
Output: all partitions (cluster-centers of all partitions, objective function values,and CH and DB indexes);
Submodules: d[], FF[], Fmin[], G[], MinEl[], C1[], DC2[], Dmin1[], Dmin2[], Indexes[], HD1[], HD2[]

AgglNest[A_,p_:1,DD_:0,Ind_:1]:=Module[{PI,cen,R,i1,i2},
PI=Table[{A[[i]]},{i,Length[A]}];Print["PI0: ",PI];
slpart=ListPlot[Table[PI[[j]],{j,Length[PI]}],PlotStyle->Table[{PointSize[.05],Hue[2j/Length[PI]]},{j,Length[PI]}] ,PlotRange->AG,AspectRatio->1,GridLines->{tab,tab},ImageSize->150];
If[p==1,cen=Table[Median[PI[[j]]],{j,Length[PI]}],cen=Table[Mean[PI[[j]]],{j,Length[PI]}]];Print["Cen0: ",cen];
slcen=ListPlot[cen,PlotMarkers->{"✶",15}];
Print[Show[slpart,slcen,GridLines->{tab,tab},PlotRange->AG,ImageSize->Small]];Print["|PI|=",Length[PI],"; F=",Fmin[A,cen,p]//N];
While[Length[PI]≥ 2,
(*If[p==1,R=DistanceMatrix[cen,DistanceFunction->ManhattanDistance],R=DistanceMatrix[cen,DistanceFunction->SquaredEuclideanDistance]];*)
Which[p==1&&DD==0,R=DistanceMatrix[cen,DistanceFunction->ManhattanDistance],
p==2&&DD==0,R=DistanceMatrix[cen//N,DistanceFunction->SquaredEuclideanDistance],
p==2&&DD==5,R=Table[Length[PI[[i]]]*Length[PI[[j]]]*Norm[cen[[i]]-cen[[j]]]^2/(Length[PI[[i]]]+Length[PI[[j]]])//N,{i,Length[PI]},{j,Length[PI]}],
p==1&&DD==1,R=Table[Dmin1[PI[[i]],PI[[j]]],{i,Length[PI]},{j,Length[PI]}],
p==2&&DD==2,R=Table[Dmin2[PI[[i]],PI[[j]]],{i,Length[PI]},{j,Length[PI]}]
];
If[Ind≠0,Print[TableForm[R]]];
{i1,i2}=MinEl[R];
If[Ind≠0,Print["Najbliži klasteri ",{i1,i2}," : ",{PI[[i1]],PI[[i2]]}]];
drop=Delete[PI,{{i1},{i2}}];
PI=Append[drop,Join[PI[[i1]],PI[[i2]]]];
If[p==1,cen=Table[Median[PI[[j]]],{j,Length[PI]}],cen=Table[Mean[PI[[j]]],{j,Length[PI]}]];
Print["Nova part = ",PI,"\nNovi centri = ",cen//N];
Print["|PI|=",Length[PI],"; F=",Fmin[A,cen,p]//N];
If[p==2&&Length[PI]>1,ind=Indexes[A,PI,cen];
Print["; CH = ",ind[[1]],"; DB = ",ind[[2]]]];
slpart=ListPlot[Table[PI[[j]],{j,Length[PI]}],PlotStyle->Table[{PointSize[.05],Hue[2j/Length[PI]]},{j,Length[PI]}] ,PlotRange->AG,AspectRatio->1,GridLines->{tab,tab},ImageSize->150];
slcen=ListPlot[cen,PlotMarkers->{"✶",15}];
If[Ind≠0,Print[Show[slpart,slcen,GridLines->{tab,tab},PlotRange->AG,ImageSize->Small]]];
]
]