/*
 * BirthDeathGernhard08Model.java
 *
 * Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut
 *
 * This file is part of BEAST.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership and licensing.
 *
 * BEAST is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * BEAST 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with BEAST; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

package dr.evomodel.speciation;

import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evomodelxml.BirthDeathModelParser;
import dr.inference.model.Parameter;
import static org.apache.commons.math.special.Gamma.logGamma;

/**
 * Birth Death model based on Gernhard 2008  "The conditioned reconstructed process"
 * doi:10.1016/j.jtbi.2008.04.005 (http://dx.doi.org/10.1016/j.jtbi.2008.04.005)
 * <p/>
 * This derivation conditions directly on fixed N taxa.
 * <p/>
 * The inference is directly on b-d (strictly positive) and d/b (constrained in [0,1))
 * <p/>
 * Vefified using simulated trees generated by Klass tree sample. (http://www.klaashartmann.com/treesample/)
 * <p/>
 * Sampling proportion not verified via simulation. Proportion set by default to 1, an assignment which makes the expressions
 * identical to the ones pre change.
 *
 * @author Joseph Heled
 *         Date: 24/02/2008
 */
public class BirthDeathGernhard08Model extends UltrametricSpeciationModel {
    public enum TreeType {
        UNSCALED,     // no coefficient 
        TIMESONLY,    // n!
        ORIENTED,     // n
        LABELED,      // 2^(n-1)/(n-1)!
    }

    public static final String BIRTH_DEATH_MODEL = BirthDeathModelParser.BIRTH_DEATH_MODEL;

    private Parameter relativeDeathRateParameter;
    /**
     * mu/lambda *
     */
    private Parameter birthDiffRateParameter;
    /**
     * lambda - mu *
     */
    private Parameter sampleProbability;

    private TreeType type;

    /**
     * rho *
     */

    public BirthDeathGernhard08Model(Parameter birthDiffRateParameter,
                                     Parameter relativeDeathRateParameter,
                                     Parameter sampleProbability,
                                     TreeType type,
                                     Type units) {

        this(BIRTH_DEATH_MODEL, birthDiffRateParameter, relativeDeathRateParameter, sampleProbability, type, units);
    }

    BirthDeathGernhard08Model(String modelName,
                              Parameter birthDiffRateParameter, Parameter relativeDeathRateParameter, Parameter sampleProbability,
                              TreeType type,
                              Type units) {

        super(modelName, units);

        this.birthDiffRateParameter = birthDiffRateParameter;
        addVariable(birthDiffRateParameter);
        birthDiffRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));

        this.relativeDeathRateParameter = relativeDeathRateParameter;
        addVariable(relativeDeathRateParameter);
        relativeDeathRateParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1));

        this.sampleProbability = sampleProbability;
        if (sampleProbability != null) {
            addVariable(sampleProbability);
            sampleProbability.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1));
        }
        this.type = type;
    }

    public double getR() {
        return birthDiffRateParameter.getParameterValue(0);
    }

    public double getA() {
        return relativeDeathRateParameter.getParameterValue(0);
    }

    public double getRho() {
        return sampleProbability != null ? sampleProbability.getParameterValue(0) : 1.0;
    }

    private double logCoeff(int taxonCount) {
        switch( type ) {
            case UNSCALED: break;
            case TIMESONLY: return logGamma(taxonCount + 1);
            case ORIENTED: return Math.log(taxonCount);
            case LABELED:  return (taxonCount-1)*Math.log(2.0) - logGamma(taxonCount);
        }
        return 0.0;
    }

    public double logTreeProbability(int taxonCount) {
        return logCoeff(taxonCount) +
                (taxonCount - 1) * Math.log(getR() * getRho()) + taxonCount * Math.log(1 - getA());
    }

    public double logNodeProbability(Tree tree, NodeRef node) {
        final double height = tree.getNodeHeight(node);
        final double rho = getRho();
        final double mrh = -getR() * height;
        final double z = Math.log(rho + ((1 - rho) - getA()) * Math.exp(mrh));
        double l = -2 * z + mrh;

        if (tree.getRoot() == node) {
            l += mrh - z;
        }
        return l;
    }

    public boolean includeExternalNodesInLikelihoodCalculation() {
        return false;
    }
}