/*  
 *  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;
	/**
	 * 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,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];
			/* 
			 * 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; /* for slighten the code */
			
			/*
			 * Now, we have to check if a chromosome was defined
			 * as skeleton.
			 */
			for(i=0;i<nc;i++) {
				
				if (chromosomes[i].skeleton) {
				
					ddd= d[0] =0.0;
					sdd[0]=0.0;
					sidx=j=k=0;
					i=1;
					ref=notref=false;
					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]);
						ddd   -= dd;
						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 */
						notref = true;
						/* 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;
						j		 = 1;
						ddd      = MappingFunction.distance(
									chromosomes[i].mr[0],
									IMetaQtlConstants.MAPPING_FUNCTION_HALDANE,
									IMetaQtlConstants.MAPPING_UNIT_M
									);
					}
					for(;i<=result.m;i++) {
						tmp = x[idx[i]] - dd;
						if (x[idx[i]] > 0.0) {
							for(;j<chromosomes[i].nm;j++) {
								if (ddd < tmp) {
									/* Then positionnate the reference */
									d[++k]   = ddd;
									sdd[k]    = 0.0;
									mrkNames[k]  = chromCluster.getMarkerNameByIndex(nm-1);
									mrkOc[k]     = chromCluster.getMarkerOccurence(nm-1);
									ddd  += MappingFunction.distance(
											chromosomes[i].mr[j-1],
											IMetaQtlConstants.MAPPING_FUNCTION_HALDANE,
											IMetaQtlConstants.MAPPING_UNIT_M
											);
								}
							}
						}
						d[++k]   = tmp;
						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 (i==nc) {
				/* 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);
				}
			}
		}
	}
	
}
