 /* BEGIN_HEADER                                              Java TreeView
 *
 * $Author: avsegal
 * $RCSfile: AtrAligner.java
 * $Revision: 
 * $Date: Jun 25, 2004
 * $Name:  
 *
 * This file is part of Java TreeView
 * Copyright (C) 2001-2014 Alok Saldanha, All Rights Reserved. Modifications Copyright (C) Lawrence Berkeley Lab.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * END_HEADER
 */
 
package edu.stanford.genetics.treeview.plugin.dendroview;

/**
 * @author avsegal
 *
 * Aligns the array ordering to match a different array tree. Used statically two
 * align one fileset to another.
 */

import edu.stanford.genetics.treeview.*;
import java.util.*;

public class AtrAligner {
	
    /**
     * 
     * @param atrHeader1 the atr header to be aligned
     * @param arrayHeader1 the array header to be aligned
     * @param atrHeader2 the atr header to align to
     * @param arrayHeader2 the array header to align to
     * @return a new ordering of arrayHeader1
     * @throws DendroException
     */
	public static int [] align(HeaderInfo atrHeader1, HeaderInfo arrayHeader1, HeaderInfo atrHeader2, HeaderInfo arrayHeader2)
		throws DendroException
	{
		int numArrays = arrayHeader1.getNumHeaders();
		int [] newOrder = new int[numArrays];
		AtrAnalysisNode root1;
		
		for(int i = 0; i < numArrays; i++)
		{
			newOrder[i] = i;
		}
		
		root1 = createAnalysisTree(atrHeader1, arrayHeader1);
		
	
		
		
		alignTree(root1, arrayHeader1, arrayHeader2, newOrder);
		
		return newOrder;
	}
	
	/**
	 * Creates an AtrAnalysis tree based on the atr and array headers.
	 * @param atrHeader ATR header
	 * @param arrayHeader array header
	 * @return the root node of the tree
	 * @throws DendroException
	 */
	private static AtrAnalysisNode createAnalysisTree(HeaderInfo atrHeader, HeaderInfo arrayHeader)
		throws DendroException
	{
		int numArrays = arrayHeader.getNumHeaders();
		
		AtrAnalysisNode [] leafNodes = new AtrAnalysisNode[numArrays];
		Hashtable id2node = new Hashtable(((atrHeader.getNumHeaders() * 4) /3)/2, .75f);
		
		String newId, leftId, rightId;
		
		AtrAnalysisNode newN, leftN, rightN;
		
		for(int i = 0; i < atrHeader.getNumHeaders(); i++)
		{
			newId = atrHeader.getHeader(i, "NODEID");
			leftId = atrHeader.getHeader(i, "LEFT");
			rightId = atrHeader.getHeader(i, "RIGHT");
			
			newN = (AtrAnalysisNode)id2node.get(newId);
			leftN = (AtrAnalysisNode)id2node.get(leftId);
			rightN = (AtrAnalysisNode)id2node.get(rightId);
			
			
			if (newN != null) {
				System.out.println("Symbol '" + newId +
				"' appeared twice, building weird tree");
			}
			else
			{
				newN = new AtrAnalysisNode(newId, null);
				id2node.put(newId, newN);
			}				
			
			if (leftN == null) { // this means that the identifier for leftn is a new leaf
				int val; // stores index (y location)
				val = arrayHeader.getHeaderIndex(leftId);
				if (val == -1) {
					throw new DendroException("Identifier " + leftId + " from tree file not found in CDT");
				}
				leftN = new AtrAnalysisNode(leftId, newN);
				leftN.setIndex(val);
				leftN.setName(arrayHeader.getHeader(val, "GID"));
				
				leafNodes[val] = leftN;
				id2node.put(leftId, leftN);
			}
			
			if (rightN == null) { // this means that the identifier for rightn is a new leaf
				//		System.out.println("Looking up " + rightId);
				int val; // stores index (y location)
				val = arrayHeader.getHeaderIndex(rightId);
				if (val == -1) {
					throw new DendroException("Identifier " + rightId + " from tree file not found in CDT.");
				}
				rightN = new AtrAnalysisNode(rightId, newN);
				rightN.setIndex(val);
				rightN.setName(arrayHeader.getHeader(val, "GID"));
				leafNodes[val] = rightN;
				id2node.put(rightId, rightN);
			}
			
			if(leftN.getIndex() > rightN.getIndex())
			{
				AtrAnalysisNode temp = leftN;
				leftN = rightN;
				rightN = temp;	
			}
			
			rightN.setParent(newN);
			leftN.setParent(newN);
			
			newN.setLeft(leftN);
			newN.setRight(rightN);
		}
		
		
		return (AtrAnalysisNode)leafNodes[0].findRoot();
		
	}
	
	/**
	 * Aligns tree rooted at root1 to a different atr tree as best as possible.
	 * @param root1 root of the tree to align
	 * @param arrayHeader1 array header of the tree to align
	 * @param arrayHeader2 array header of the tree to align to
	 * @param ordering the ordering array which this method will fill
	 */
	private static void alignTree(AtrAnalysisNode root1, HeaderInfo arrayHeader1, HeaderInfo arrayHeader2, int [] ordering)
	{
		Vector v1 = new Vector();
		Hashtable gid2index = new Hashtable();
		int gidIndex = arrayHeader2.getIndex("GID");
		
		for(int i = 0; i < arrayHeader2.getNumHeaders(); i++)
		{
			gid2index.put(arrayHeader2.getHeader(i)[gidIndex], new Integer(i));
		}
		
		root1.indexTree(arrayHeader2, gid2index);
		
		
		root1.enumerate(v1);
			
		for(int i = 0; i < v1.size(); i++)
		{
			 ordering[i] = arrayHeader1.getHeaderIndex(((AtrAnalysisNode)v1.get(i)).getID());
		}
		
	}
}
