package coalescent.process;

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

/**
 *   This is the entry class for generating compatible genealogies
 *   with recombination. The newer version use Collection framework.
 *
 */

public class SimpleRecombination extends AbstractCoalescent{ //SimpleCoalescent{
	protected final String[] parameters={"Theta", "SampleSize", "Recombination.Rate", "Recombination.nLoci"};
    protected int activeLine[];
    protected int nsites;      // Recombination.nLoci
    protected int nlinks;
    protected double rate;     // Recombination.Rate
    protected int nextEvent;
    protected String[][] perc= new String[2][101];
    
    public SimpleRecombination(){
        pset.clear();
        pset.allowParameter(parameters);
        setParameter( new Theta(1.0e0));
        setParameter( new SampleSize(5) );
        setParameter( new Recombination.Rate(1.0));
        setParameter( new Recombination.nLoci(20));
        for(int i=0; i<=100; i++){
            perc[0][i]="<"+i;
            perc[1][i]=">"+i;
        }
    }
    
    public void parameterChanged(ParameterEvent e){
        
        Parameter a = (Parameter)e.getSource();
        if( a.getName().equals("Theta")){
            theta = ((Double)a.getValue()).doubleValue();
            return;
        }
        if( a.getName().equals("SampleSize")){
            nseq = ((Integer)a.getValue() ).intValue();
            Chromosome.setSampleSize(nseq);
            rates = (rates.length ==0)?(new double[nseq+1]):rates;
            return;
        }
        if( a.getName().equals("Recombination.Rate")){
            rate = ((Double)a.getValue() ).doubleValue();
            return;
        }
        if( a.getName().equals("Recombination.nLoci")){
            nsites = ((Integer)a.getValue() ).intValue();
            Chromosome.setLength(nsites);
            return;
        }
    }
    
    /**
     * override the generateGenealogy methods
     */
    protected List nodeList = new ArrayList();
    protected List allNodes = new ArrayList();
    protected String empty="";
    public Genealogy generateGenealogy() {
        int i, j, k;
        double prec, ran, total_rate, coal_prob, prob,x ;
        double t;
        
        Chromosome.resetRecombinationSites();
        releaseNode(allNodes);
        nodeList.clear();
        allNodes.clear();
        for(i=0; i<nseq; i++){
            DefaultNode node = (DefaultNode)nodePool.borrow();
            node.fastClear();
            node.setName(empty);
            node.setEventNumber(0); // sampling is treated as event 0
            ((Chromosome)node.getContent()).reset();
            nodeList.add( node );
            allNodes.add( node );
        }
        if(debug) System.out.println("\nCoalescent Process starts ... ");
        
        nlinks = nseq*(nsites-1) ;
        double r = rate/(nsites-1);
        
        nextEvent = 1;
        while( nodeList.size() > 1) {
            
            if(debug)System.out.println( "\nCurrent size="+nodeList.size()+ " nlinks="+nlinks);
            prec = nlinks*r;
            // coal_prob = (double)(nodeList.size()*(nodeList.size()-1)); // Fu's version
            coal_prob = 0.5 * (double)(nodeList.size() * (nodeList.size()-1)); // changed by haipeng
            total_rate = prec + coal_prob ;
            
            if( random.nextDouble()  < ( prec / total_rate ) ){
                recombination();
            }
            else {
                coalescence();
            }
            
            if( nextEvent == rates.length){
                double[] tmp = rates;
                rates = new double[(int)(tmp.length*1.2)];
                System.arraycopy(tmp,0,rates,0,tmp.length);
            }
            rates[nextEvent]= total_rate;
            nextEvent++;
        }
        if(debug) Chromosome.recombinationSites();
        eventCount = nextEvent-1;
        return genealogy;
    }
    
    //
    //	recombinaiton subroutine
    //
    
    protected Chromosome[] pc=new Chromosome[2];
    protected DefaultNode[] parent = new DefaultNode[2];
    public void recombination() {
        
        // First generate a random x-over spot,
        // then locate it as to chrom and seg.
        int breakingSpot = (int)(random.nextDouble() * nlinks);
        
        // The Chromosome (ic) in which recombinaiton will occur
        DefaultNode recombinant=null;
        Chromosome id=null;
        int ic=0, spot=breakingSpot;
        for(int i=0, ll=nodeList.size(); i<ll; i++){
            recombinant = (DefaultNode)nodeList.get(i);
            id=(Chromosome)recombinant.getContent();
            int l = id.nLinks();
            if( spot < l ) {
                ic=i;
                if(debug) System.out.println("pick="+ic+" bspot="+breakingSpot+" l="+l+" nlink="+nlinks);
                break;
            }
            spot -= l ;
        }
        if(debug) id.toString();
        
        //DefaultNode[] parent = { (DefaultNode)nodePool.borrow(), (DefaultNode)nodePool.borrow()};
        //Chromosome[] pc={(Chromosome)parent[0].getContent(), (Chromosome)parent[1].getContent()};
        parent[0]=(DefaultNode)nodePool.borrow();
        parent[1]=(DefaultNode)nodePool.borrow();
        pc[0]=(Chromosome)parent[0].getContent();
        pc[1]=(Chromosome)parent[1].getContent();
        
        Chromosome.breakAfterLocus(id.firstLocus()+spot, id, pc);
        
        int percentage = (int)((100*id.firstLocus()+spot+1)/Chromosome.length());
        for(int i=0; i<2; i++){
            parent[i].fastClear();
            parent[i].setName(perc[i][percentage]);
            parent[i].setEventNumber(nextEvent);
            parent[i].addChild( recombinant );
            recombinant.getBranch(i).setWeight( pc[i].cardinalProportion() );
            allNodes.add(parent[i]);
        }
        nlinks += (pc[0].nLinks() + pc[1].nLinks() -id.nLinks() );
        
        nodeList.set(ic, parent[0]);
        nodeList.add(parent[1]);
        
        if(debug) {
            System.out.println("Results of breaking after locus "+(id.firstLocus()+spot));
            pc[0].toString();
            pc[1].toString();
        }
    }
    
    
    
    
    //
    //	The coalescence
    //
    public void coalescence() {
        //
        //  find a pair of jointable Chromosomes
        //
        int currentSize= nodeList.size();
        int a = (int)(random.nextDouble() * currentSize);
        int b = (int)(random.nextDouble() * (currentSize - 1));
        b = (b >= a)?(b+1):b;
        
        int i=Math.min(a,b);
        int j=Math.max(a,b);
        
        DefaultNode nodeA=(DefaultNode)nodeList.get(i);
        DefaultNode nodeB=(DefaultNode)nodeList.get(j);
        DefaultNode parentNode =(DefaultNode)nodePool.borrow();
        
        Chromosome one = (Chromosome)nodeA.getContent();
        Chromosome two = (Chromosome)nodeB.getContent();
        Chromosome parent = (Chromosome)parentNode.getContent();
        parentNode.fastClear();
        
        if(debug) {
            System.out.println("Selected ="+i+" "+j +" to coalesce.  Links="+one.nLinks()+ " "+two.nLinks() );
            one.toString();
            two.toString();
        }
        
        Chromosome.coalesce(one,two, parent);
        
        if(debug){
            System.out.println("Result=");
            parent.toString();
        }
        
        parentNode.addChild( nodeA );
        parentNode.addChild( nodeB );
        parentNode.setEventNumber(nextEvent);
        nodeA.getBranch().setWeight(one.cardinalProportion());
        nodeB.getBranch().setWeight(two.cardinalProportion());
        
        
        nodeList.set(i, parentNode);
        nodeList.set(j, nodeList.get(currentSize-1));
        nodeList.remove(currentSize-1);
        allNodes.add(parentNode);
        
        nlinks += ( parent.nLinks() - one.nLinks()- two.nLinks() );
        if( nodeList.size() == 1){
            //genealogy.setRoot(parentNode);
            ((DefaultGenealogy)genealogy).setRoot(parentNode, allNodes);
        }
    }
    
    
    
    
    /**
     * Node releasing
     */
    protected void releaseTreeNode(){
        if( genealogy.getRoot() == null) return;
        releaseNode(genealogy.getRoot());
    }
    
    /**
     *	  releasing node only if it is tips.
     */
    protected  void releaseNode(Node a){
        for(int k=a.getChildCount()-1; k>=0; k--){
            releaseNode(a.getChildAt(k));
        }
        if(a.getChildCount() == 0){
            a.clear();
            nodePool.release(a);
        }
    }
    
    /**
     *	  releasing node only if it is tips.
     */
    protected  void releaseNode(List a){
        if( a instanceof LinkedList ){
            Iterator it=a.iterator();
            while( it.hasNext()){
                nodePool.release( it.next() );
            }
        }
        else{
            for(int l=a.size(), k=0; k<l; k++)
                nodePool.release(a.get(k));
        }
    }
    
    /**
     *   Node pool for the purpose of reuse
     */
    protected NodePool nodePool = new NodePool();
    public class NodePool extends ObjectPoolAdapter{
        public Object construct(){
            DefaultNode a=new DefaultNode();
            a.setContent( (Chromosome)chromosomePool.borrow() );
            return a;
        }
    }
    
    protected ChromosomePool chromosomePool = new ChromosomePool();
    public class ChromosomePool extends ObjectPoolAdapter{
        public Object construct(){
            return (new Chromosome());
        }
    }
    
}

