/*
 * Upgma_Li.java
 */

package coalescent.analysis;

import  coalescent.util.*;
import  coalescent.tree.*;
import  coalescent.process.*;
import  coalescent.dna.*;
import  java.util.*;

import cern.jet.random.engine.MersenneTwister64;

/**
 *
 * @author  Haipeng
 */
public class Upgma {
    public static boolean randomArrangeOTU = true;
    protected static MersenneTwister64 random = RandomUtil.getMersenneTwister64();
    protected static SequenceUtility sample= new SequenceUtility();
    protected static GenealogyAnalyzer ga = new GenealogyAnalyzer();
    
    public static Genealogy tree( Collection sequence){
        double[][] dis = sample.getHaplotypeDistance(sequence);
        String[] names = sample.getName(sequence);
        return tree(dis, names);
    }
    
    public static Genealogy tree( double[][] dist ){
        return tree(dist, null);
    }
    
    /**
     * The matrix of distance is low-triangle
     * n = distance.length+1;
     */
    public static Genealogy tree(double[][] distance, String[] names) {
        final int n = distance.length+1;
        Genealogy newTree = new DefaultGenealogy();
        List currentLeaves = new ArrayList(n);
        
        for(int i = 0; i < n; i ++) {
            DefaultNode node = new DefaultNode();
            node.setEventNumber(0);
            node.setSize(1);
            if( names == null )
                node.setName("Seq"+(i+1));
            else
                node.setName(names[i]);
            currentLeaves.add(node);
        }
        
        // java.text.DecimalFormat decimal = new java.text.DecimalFormat("#.#####");
        
        int join[]=new int[2];
        for(int nn = n, next = n + 1; nn > 1; nn --, next ++){
            DefaultNode nextNode = new DefaultNode();
            nextNode.setName("Seq" + next);
            double minLength = getJoin(distance, join, currentLeaves);
            
            Node a = (Node)(currentLeaves.get(join[0]));
            Node b = (Node)(currentLeaves.get(join[1]));
            
            nextNode.setEventNumber(n - nn + 1);
            nextNode.addChild(a);
            nextNode.addChild(b);
            nextNode.setSize(a.getSize() + b.getSize());
            
            a.getBranch().setLength(minLength / 2 - ga.getTMRCA(a));
            b.getBranch().setLength(minLength / 2 - ga.getTMRCA(b));
            
            List newLeaves = new ArrayList(currentLeaves);
            newLeaves.remove(a);
            newLeaves.remove(b);
            newLeaves.add(nextNode);
            
            /*
            System.out.println(((Node)(currentLeaves.get(0))).getName());
            for (int j = 1; j < nn; j ++) {
                System.out.print(((Node)(currentLeaves.get(j))).getName() + "          ");
                for (int k = 0; k < distance[j - 1].length; k ++) System.out.print(decimal.format(distance[j - 1][k]) + " ");
                System.out.println();
            }
            System.out.println();
            System.out.println(a.getName() + "(index" + join[0] + ") - " + b.getName() + "(index" + join[1] + ") -> " + nextNode.getName() + " minLength = " + minLength);
            */
            
            // the last element in newLeaves is the new node
            distance = recomputeDistance(distance, currentLeaves, join[0], join[1], newLeaves);
            currentLeaves = newLeaves;
        }
        newTree.setRoot((Node)(currentLeaves.get(0)));
        
        return newTree;
    }
    
        /*
                return the node number to joint
                Note that the nodeList corresponds
                to the non-null row in distance matrix
         */
    public static double getJoin(double[][] dis, int[] join, List currentLeaves) {
        double xmin = Double.MAX_VALUE;
        int numOfEqualPairs = 0; // added by Haipeng
        int n = dis.length + 1;
        for (int i = 0; i < n - 1; i ++) {
            for (int j = i + 1; j < n; j ++) {
            	double d = dis[j - 1][i];
            	// double d = getOneDistance(dis, i, j);
                if (d < xmin) {
                    xmin = d;
                    join[0] = i;
                    join[1] = j;
                    /*
                    Node a = (Node)(currentLeaves.get(i));
                    Node b = (Node)(currentLeaves.get(j));
                    System.out.println(a.getName() + " - " + b.getName() + ": " + xmin);
                     */
                    numOfEqualPairs = 0; // added by Haipeng, and this joint will be counted in the next action.
                }
                if (d == xmin) numOfEqualPairs ++; // added by Haipeng
            }
        }
        
        // choose randomly a pair from the pairs with the smallest distance, added by Haipeng
        if (randomArrangeOTU && numOfEqualPairs > 1) {
            int index = 0;
            int chosenPair = (int)(random.nextDouble() * numOfEqualPairs) + 1;
            for (int i = 0; i < n - 1; i ++) {
                for (int j = i + 1; j < n; j ++) {
                    if (getOneDistance(dis, i, j) == xmin) {
                        index ++; // added by Haipeng
                        if (index == chosenPair) {
                            join[0] = i;
                            join[1] = j;
                        }
                    }
                }
            }
        }
        
        /*
        Node aa = (Node)(currentLeaves.get(join[0]));
        Node bb = (Node)(currentLeaves.get(join[1]));
        System.out.println(aa.getName() + " - " + bb.getName() + ": " + xmin);
         */
        
        return xmin;
    }
    
    protected static double[][] initialDistance(int n) {
        double[][] distance = new double[n - 1][];
        for (int j = 0; j < distance.length; j ++) distance[j] = new double[j + 1];
        
        return distance;
    }
    
    // index is zero-based
    protected static double getOneDistance(double[][] dis, int firstIndex, int secondIndex) {
        int sortedIndex_1 = firstIndex;
        int sortedIndex_2 = secondIndex;
        if (sortedIndex_1 < sortedIndex_2) {
            sortedIndex_1 = secondIndex;
            sortedIndex_2 = firstIndex;
        }
        // Now, sortedIndex_1 > sortedIndex_2
        
        return dis[sortedIndex_1 - 1][sortedIndex_2];
    }
    
    // Recompute the distance matrix
    // the last element in newLeaves is the new node
    public static double[][] recomputeDistance(double[][] dis, List currentLeaves, int ii, int jj, List newLeaves) {
        int n = newLeaves.size();
        double[][] newDist = initialDistance(n);
        
        for (int i = 1; i < n; i ++) {
            Node firstNode = (Node)(newLeaves.get(i));
            int firstIndex = currentLeaves.indexOf(firstNode);
            for (int j = 0; j < i; j ++) {
                Node secondNode = (Node)(newLeaves.get(j));
                int secondIndex = currentLeaves.indexOf(secondNode);
                
                if (firstIndex != -1 && secondIndex != -1) { // nothing needs to be changed, the two nodes are the same
                    newDist[i - 1][j] = getOneDistance(dis, firstIndex, secondIndex);
                }
                else {
                    if (firstIndex == -1 && secondIndex != -1) { // firstNode is new
                        double avg = (getOneDistance(dis, ii, secondIndex) + getOneDistance(dis, jj, secondIndex)) / 2.0d;
                        newDist[i - 1][j] = avg;
                    }
                    else {
                        if (firstIndex != -1 && secondIndex == -1) { // secondNode is new
                            double avg = (getOneDistance(dis, ii, firstIndex) + getOneDistance(dis, jj, firstIndex)) / 2.0d;
                            newDist[i - 1][j] = avg;
                        }
                        else {
                            System.out.println("Logical error in Upgma.recomputeDistance()!!!");
                        }
                    }
                }
            }
        }
        
        return newDist;
    }
}
