/*  
 *  src/org/metaqtl/MetaChrom.java
 * 
 *  $Author: veyrieras $, $Date: 2006-10-17 15:41:54 $, $Version$
 *
 *  MetaQTL : a Java package for QTL Meta-Analysis
 * 
 *  Copyright (C) 2003-2006  Jean-Baptiste Veyrieras, INRA, France.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA * 
 */
package org.metaqtl;

import org.metaqtl.numrec.NumericalUtilities;
import org.metaqtl.util.MappingFunction;
/**
 * A MetaChrom is the result of the merge of the members of a
 * {@link ChromCluster}.
 */
public class MetaChrom {
	/**
	 * The number of chromosomes implied.
	 */
	public int nc;
	/**
	 * The number of markers.
	 */
	public int nm;
	/**
	 * The number of marker intervals implied in this consensus.
	 */
	public int ni;
	/**
	 * The number of degrees of freedom.
	 */
	public int dof;
	/**
	 * The number of marker per implied chromosome
	 */
	public int[] nmc;
	/**
	 * The number of occurence per marker oved chromosomes. 
	 */
	public int[] mrkOc;
	/**
	 * The chi-square value of this chromosome.
	 */
	public double chi2;
	/**
	 * The p-value of this chromosome.
	 */
	public double pvalue;
	/**
	 * The standardized residual between original marker intervals
	 * and those of the meta chromosome.
	 */
	public double[] rsd;
	/**
	 * The absolute positions of markers in Morgan.
	 */
	public double[] d;
	/**
	 * The standard deviation of the position in Morgan.
	 */
	public double[] sdd;
	/**
	 * The name of the meta chrom.
	 */
	public String name;
	/**
	 * The names of the genetic maps.
	 */
	public String[] mapNames;
	/**
	 * The ordered marker names.
	 */
	public String[] mrkNames;
	
	private void MetaChromSkeleton (MultiFitResult result, ChromCluster chromCluster, Chromosome skeleton)
	{
		int i,j,k,c,sidx;
		double skd;
		boolean ref,notref;
		int[] idx;
		double[] x;
		double[][] cov;
		
		j=k=0;
		
		if (result.m>0)
		{	
			x 	= new double[result.m + 1];
			idx = new int[result.m + 1];
			
			for(i=0;i<result.m;i++)
			{
			   x[i+1] = result.theta[i];
			}
			
			NumericalUtilities.indexx(result.m, x, idx);
			for (i=0;i<result.m;i++)
			{
				skd=skeleton.getDistance(j, IMetaQtlConstants.MAPPING_FUNCTION_HALDANE, IMetaQtlConstants.MAPPING_UNIT_M);
				//System.out.println(">"+i+" "+j+" "+skd+" "+x[idx[i+1]]);
				if (x[idx[i+1]] > skd && j != skeleton.nm)
				{
					for(;j < skeleton.nm;j++,k++)
					{
						skd = skeleton.getDistance(j, IMetaQtlConstants.MAPPING_FUNCTION_HALDANE, IMetaQtlConstants.MAPPING_UNIT_M);
						if (skd > x[idx[i+1]])
						{
							break;			
						}
						else
						{	
							d[k] = skd;
							mrkNames[k] = skeleton.getMarkerName(j);
						}
						//System.out.println("s "+k+" "+mrkNames[k]+" "+d[k]);
					}
				}
				if (x[idx[i+1]] <= skd || j == skeleton.nm)
				{
					d[k] = x[idx[i+1]];
					mrkNames[k] = chromCluster.getMarkerNameByIndex(idx[i+1]-1);
					//System.out.println("x "+k+" "+mrkNames[k]+" "+d[k]);
					k++;				
				}
			}
		}	
			
		for(;j < skeleton.nm;j++,k++)
		{
			d[k] =  skeleton.getDistance(j, IMetaQtlConstants.MAPPING_FUNCTION_HALDANE, IMetaQtlConstants.MAPPING_UNIT_M);
			mrkNames[k] = skeleton.getMarkerName(j);
			//System.out.println("s "+k+" "+mrkNames[k]+" "+d[k]);
		}
		for(i=0;i<nm;i++)
			d[i]-=d[0];
	}
	
	/**
	 * Get a new instance of <code>MetaChrom</code> which is 
	 * initialized by using the result
	 * of the merge of the members of a {@link ChromCluster}.
	 * 
	 * @param result the result of the merge of the members of the cluster.
	 * @param cluster the chromosome cluster.
	 */
	public MetaChrom(MultiFitResult result, ChromCluster chromCluster) {
		int i,j,k,c,sidx;
		double dd,ddd,tmp;
		boolean ref,notref;
		int[] idx;
		double[] x;
		double[][] cov;
		Chromosome[] chromosomes;
		
		chromosomes = chromCluster.getClusterMembers();
		
		if (chromosomes != null) {
			/* Get the name of the meta chromosome */
			this.name = chromCluster.name;
			/* The number of chromosomes which have been used to build
			 * the consensus chromosome */
			this.nc  = chromosomes.length;
			/* Get the number of markers per chrom */
			this.nmc	  = new int[nc];
			this.mapNames = new String[nc]; 
			for(i=0;i<nc;i++) {
				this.nmc[i] 	 = chromosomes[i].nm;
				this.mapNames[i] = chromosomes[i].mapName;
			}
			this.nm    = chromCluster.getMarkerNumber(); /* the number of markers */
			this.d     = new double[nm]; /* the absolute ordered distances */
			this.sdd   = new double[nm]; /* the standard deviation */
			this.mrkNames = new String[nm]; /* the ordered marker names 	   */
			/* Get the number of occurences per marker */
			this.mrkOc = new int[nm];
			/*
			 * Get the WLS parameters
			 */
			this.chi2      = result.chi2;
			this.pvalue    = result.pvalue;
			this.dof	   = result.dof;
			this.ni        = result.n;
			this.rsd	   = new double[ni];
			for(i=0;i<ni;i++)
				rsd[i] = result.rsd[i];
			
			for(c=0;c<nc;c++)
				if (chromosomes[c].skeleton)
					break;
			if (c < nc)
			{
				MetaChromSkeleton(result, chromCluster, chromosomes[c]);
			}
			else
			{
				/* 
				 * Now we have to get both the absolute positions of
				 * the marker and the marker names ordered in ascending
				 * order.
				 * 
				 * Therefore begin with a heap sort of the estimated positions
				 * of markers 
				 * 
				 */
				x 	= new double[result.m + 1];
				idx = new int[result.m + 1];
				for(i=0;i<result.m;i++) {
					x[i+1] = result.theta[i];
				}
				
				NumericalUtilities.indexx(result.m, x, idx);
				
				cov = result.cov; /* to slighten the code */
				/* Means that no skeleton was found 
				 * Then the marker with the last absolute
				 * index has been set to zero.
				 */
				d[0]=0.0;
				sidx=k=0;
				i=1;
				if (x[idx[i]] < 0.0) {
					dd     = x[idx[i]]; /* keep the distance of the first marker */
					sdd[0] = Math.sqrt(cov[idx[i]-1][idx[i]-1]);
					sidx   = idx[i]-1; /* keep also this absolute index */
					/* Get its name */
					mrkNames[0] = chromCluster.getMarkerNameByIndex(sidx);
					mrkOc[0]    = chromCluster.getMarkerOccurence(sidx);
					/* Set notref to true for the first marker */
					ref = false;
					/* And finally increment the counter on parameters x */
					i++;
				} else {
					/* This means that the arbitrary reference is the
					 * first marker	 */ 
					dd       = 0.0;
					mrkNames[0] = chromCluster.getMarkerNameByIndex(nm-1);
					mrkOc[0]    = chromCluster.getMarkerOccurence(nm-1);
					ref      = true;
				}
				for(;i<=result.m;i++) {
					if (x[idx[i]]>=0.0 && !ref) {
						/* Then positionnate the reference */
						d[++k]   = -dd;
						sdd[k]   = 0.0;
						mrkNames[k] = chromCluster.getMarkerNameByIndex(nm-1);
						mrkOc[k]    = chromCluster.getMarkerOccurence(nm-1);
						ref      = true;
					}
					d[++k]   = x[idx[i]] - dd;
					sdd[k]   = cov[idx[i]-1][idx[i]-1];
					sdd[k]   = Math.sqrt(sdd[k]);
					mrkNames[k] = chromCluster.getMarkerNameByIndex(idx[i]-1);
					mrkOc[k]    = chromCluster.getMarkerOccurence(idx[i]-1);
				}
				if (!ref) {
					/* Then positionnate the reference */
					d[++k]   = -dd;
					sdd[k]   = 0.0;
					mrkNames[k] = chromCluster.getMarkerNameByIndex(nm-1);
					mrkOc[k]    = chromCluster.getMarkerOccurence(nm-1);
				}
			}
		}
	}
	
}
