/* BEGIN_HEADER                                              Java TreeView
 *
 * $Author: alokito $
 * $RCSfile: KnnModel.java,v $
 * $Revision: 1.16 $
 * $Date: 2008-06-11 01:58:58 $
 * $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.model;
import java.util.Vector;

import edu.stanford.genetics.treeview.*;

public class KnnModel extends TVModel implements DataModel {
	/**
	 * This not-so-object-oriented hack is in those rare instances
	 * where it is not enough to know that we've got a DataModel.
	 */
	public String getType() {
		return "KnnModel";
	}
	
	// accessor methods
	public int getNumArrayClusters() {
		return aClusterMembers.length;
	}
	public int getNumGeneClusters() {
		return gClusterMembers.length;
	}
	
	public int [] getArrayClusters() {
		if (aClusterMembers==null) return null;
		int n = aClusterMembers.length;
		int[] clusters = new int[n];
		for (int i = 0; i < n; i++)
			clusters[i] = aClusterMembers[i].length;
		return clusters;
	};
	public int [] getGeneClusters() {
		if (gClusterMembers==null) return null;
		int n = gClusterMembers.length;
		int[] clusters = new int[n];
		for (int i = 0; i < n; i++)
			clusters[i] = gClusterMembers[i].length;
		return clusters;
	};
	
	public KnnModel() {
		super();
		/* build KnnModel, initially empty... */	
	}
	
	/**
	 *
	 *
	 * @param fileSet fileset to load
	 *
	 */
	public void loadNew(FileSet fileSet) 
	throws LoadException {
		resetState();
		setSource(fileSet);
		final KnnModelLoader loader = new KnnModelLoader(this);
		loader.loadInto(); 
	}
	
	/**
	 * Don't open a loading window...
	 */
	public void loadNewNW(FileSet fileSet) throws LoadException {
		resetState();
		setSource(fileSet);
		final KnnModelLoader loader = new KnnModelLoader(this);
		loader.loadIntoNW(); 
	}
	
	public String[] toStrings() {
		String[] msg = {"Selected KnnModel Stats",
				"Source = " + source.getCdt(),
				"Nexpr   = " + nExpr(),
				"NGeneHeader = " + getGeneHeaderInfo().getNumNames(),
				"Ngene   = " + nGene(),
				"eweight  = " + eweightFound,
				"gweight  = " + gweightFound,
				"aid  = " + aidFound,
				"gid  = " + gidFound
				};
		
		/*
		 Enumeration e = genePrefix.elements();
		 msg += "GPREFIX: " + e.nextElement();
		 for (; e.hasMoreElements() ;) {
		 msg += " " + e.nextElement();
		 }
		 
		 e = aHeaders.elements();
		 msg += "\naHeaders: " + e.nextElement();
		 for (; e.hasMoreElements() ;) {
		 msg += ":" + e.nextElement();
		 }
		 */
		
		return msg;
	}
	static final int gap = 1;
	/**
	 * This method adds a GROUP column to the CDT
	 * 
	 * @param tempTable - RectData object with two columns, the first of gene names and the second of group membership
	 * @param ptype the parse type for error reporting.
	 */
	public void setGClusters(RectData tempTable, int ptype) {
		HeaderInfo geneHeader = getGeneHeaderInfo();
		boolean result = checkCorrespondence(tempTable, geneHeader, ptype);
		if (result) {
			geneHeader.addName("GROUP", geneHeader.getNumNames()-1);
			for (int row = 0; row < geneHeader.getNumHeaders(); row++)
				geneHeader.setHeader(row, "GROUP", tempTable.getString(row, 1));
		}
	}
	public void setAClusters(RectData tempTable, int kagparse) {
		HeaderInfo arrayHeader = getArrayHeaderInfo();
		boolean result = checkCorrespondence(tempTable, arrayHeader, kagparse);
		if (result) {
			arrayHeader.addName("GROUP", arrayHeader.getNumNames()-1);
			for (int row = 0; row < arrayHeader.getNumHeaders(); row++)
				arrayHeader.setHeader(row, "GROUP", tempTable.getString(row, 1));
		}
	}
	public void parseClusters() throws LoadException {
		gClusterMembers =calculateMembership
		(getGeneHeaderInfo(), "GROUP");
		aClusterMembers =calculateMembership
		(getArrayHeaderInfo(), "GROUP");
	}
	public int [][] calculateMembership(HeaderInfo headerInfo, String column) {
		int groupIndex = headerInfo.getIndex(column);
		if (groupIndex < 0) return null;
		int [] counts = getCountVector(headerInfo, groupIndex);
		int [][]members = new int [counts.length][]; 
		for (int i = 0 ; i < counts.length; i++) {
			members[i] = new int[counts[i]];
		}
		populateMembers(members, headerInfo, groupIndex);
		return members;
	}
	private void populateMembers(int[][] members, HeaderInfo headerInfo, int index) {
		int [] counts = new int[members.length];
		for (int i = 0; i < counts.length; i++)
			counts[i] = 0;
		for (int i = 0; i < headerInfo.getNumHeaders(); i++) {
			Integer group = new Integer(headerInfo.getHeader(i,index));
			int g = group.intValue();
			members[g][counts[g]] = i;
			counts[g]++;
		}
	}

	/**
	 * For a column of ints, returns the number of occurences of 
	 * each int in the column.
	 * 
	 * @param headerInfo
	 * @param columnIndex
	 * @return
	 */
	private int [] getCountVector(HeaderInfo headerInfo, int columnIndex) {
		Vector counts = new Vector();
		for (int i = 0; i < headerInfo.getNumHeaders(); i++) {
			Integer group = new Integer(headerInfo.getHeader(i,columnIndex));
			Integer current = (Integer) counts.elementAt(group.intValue());
			Integer insertElement = new Integer(1);
			if (current != null)
				insertElement = new Integer(current.intValue() + 1);
			counts.insertElementAt(insertElement, group.intValue());
		}
		int [] cv = new int [counts.size()];
		for (int i =0; i < cv.length; i++) {
			cv[i] = ((Integer)counts.elementAt(i)).intValue();
		}
		return cv;
	}
	/**
	 * check to see that the order of names in the first column of the temptable
	 * matches the headerinfo.
	 * @param tempTable
	 * @param headerInfo
	 * @param ptype
	 * @return true if it matches
	 */
	private boolean checkCorrespondence(RectData tempTable, HeaderInfo headerInfo, int ptype) {
		return true;
	}

	/**
	 * holds membership of the gene clusters
	 */
	private int [] gClusterMembers[];
	/**
	 * holds membership of the array clusters
	 */
	private int [] aClusterMembers[];
	
}

