/*
 * DiscreteTraitBranchRateDelegate.java
 *
 * Copyright (c) 2002-2017 Alexei Drummond, Andrew Rambaut and Marc Suchard
 *
 * 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.treedatalikelihood.discrete;

import dr.evolution.tree.Tree;
import dr.evomodel.substmodel.SubstitutionModel;
import dr.evomodel.treedatalikelihood.BeagleDataLikelihoodDelegate;
import dr.evomodel.treedatalikelihood.preorder.AbstractDiscreteTraitDelegate;

/**
 * @author Xiang Ji
 * @author Marc A. Suchard
 */
public class DiscreteTraitBranchRateDelegate extends AbstractDiscreteTraitDelegate {

    public static String GRADIENT_TRAIT_NAME = "BranchRateGradient";
    public static String HESSIAN_TRAIT_NAME = "BranchRateHessian";

    public DiscreteTraitBranchRateDelegate(String name, Tree tree, BeagleDataLikelihoodDelegate likelihoodDelegate) {
        super(name, tree, likelihoodDelegate);
    }

    protected void cacheDifferentialMassMatrix(Tree tree, boolean cacheSquaredMatrix) {
        for (int i = 0; i < evolutionaryProcessDelegate.getSubstitutionModelCount(); i++) {
            double[] infinitesimalMatrix = new double[stateCount * stateCount];
            SubstitutionModel substitutionModel = evolutionaryProcessDelegate.getSubstitutionModel(i);
            substitutionModel.getInfinitesimalMatrix(infinitesimalMatrix);
            evolutionaryProcessDelegate.cacheInfinitesimalMatrix(beagle, i, infinitesimalMatrix);
            if (cacheSquaredMatrix) {
                double[] infinitesimalMatrixSquared = new double[stateCount * stateCount];
                for (int l = 0; l < stateCount; l++) {
                    for (int j = 0; j < stateCount; j++) {
                        double sumOverState = 0.0;
                        for (int k = 0; k < stateCount; k++) {
                            sumOverState += infinitesimalMatrix[l * stateCount + k] * infinitesimalMatrix[k * stateCount + j];
                        }
                        infinitesimalMatrixSquared[l * stateCount + j] = sumOverState;
                    }
                }
                evolutionaryProcessDelegate.cacheInfinitesimalSquaredMatrix(beagle, i, infinitesimalMatrixSquared);
            }
        }
    }

    public static String getName(String name) {
        return GRADIENT_TRAIT_NAME;
    }

    protected String getGradientTraitName() {
        return GRADIENT_TRAIT_NAME;
    }

    protected String getHessianTraitName() {
        return HESSIAN_TRAIT_NAME;
    }

}

@@ -2160,32 +2160,164 @@
 tesimalMatrix);%0A
+            double%5B%5D scaledInfinitesimalMatrix = scaleInfinitesimalMatrixByRates(infinitesimalMatrix, DifferentialChoice.GRADIENT);%0A
             evol
@@ -2368,33 +2368,39 @@
 trix(beagle, i, 
-i
+scaledI
 nfinitesimalMatr
@@ -3033,32 +3033,181 @@
               %7D%0A
+                double%5B%5D scaledInfinitesimalMatrixSquared = scaleInfinitesimalMatrixByRates(infinitesimalMatrixSquared, DifferentialChoice.HESSIAN);%0A
                 
@@ -3277,17 +3277,23 @@
 gle, i, 
-i
+scaledI
 nfinites
@@ -3339,24 +3339,1293 @@
    %7D%0A    %7D%0A%0A
+    private double%5B%5D scaleInfinitesimalMatrixByRates(double%5B%5D infinitesimalMatrix, DifferentialChoice differentialChoice) %7B%0A%0A        final int matrixSize = stateCount * stateCount;%0A%0A        if (infinitesimalMatrix.length != matrixSize) %7B%0A            throw new RuntimeException(%22Dimension mismatch when preparing scaled differential matrix for branchRateGradient calculations.%22);%0A        %7D%0A%0A        double%5B%5D scaledInfinitesimalMatrix = new double%5BmatrixSize * siteRateModel.getCategoryCount()%5D;%0A%0A        for (int i = 0; i %3C siteRateModel.getCategoryCount(); i++) %7B%0A%0A            final double rate = siteRateModel.getRateForCategory(i);%0A%0A            for (int j = 0; j %3C matrixSize; j++) %7B%0A%0A                scaledInfinitesimalMatrix%5BmatrixSize * i + j%5D = infinitesimalMatrix%5Bj%5D * differentialChoice.getRateScale(rate);%0A%0A            %7D%0A        %7D%0A%0A        return scaledInfinitesimalMatrix;%0A    %7D%0A%0A    enum DifferentialChoice %7B%0A        GRADIENT %7B%0A            @Override%0A            double getRateScale(double rate) %7B%0A                return rate;%0A            %7D%0A        %7D,%0A        HESSIAN %7B%0A            @Override%0A            double getRateScale(double rate) %7B%0A                return rate * rate;%0A            %7D%0A        %7D;%0A%0A        abstract double getRateScale(double rate);%0A    %7D%0A%0A
     public s

scale Q matrix for gradient calculation before parsing to BEAGLE