| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
package dr.inference.model; |
| 27 |
|
| 28 |
import dr.math.matrixAlgebra.Matrix; |
| 29 |
import dr.xml.*; |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
public class MatrixInverseStatistic extends Statistic.Abstract implements VariableListener { |
| 35 |
|
| 36 |
public static final String INVERSE_STATISTIC = "matrixInverse"; |
| 37 |
|
| 38 |
public MatrixInverseStatistic(MatrixParameter matrix) { |
| 39 |
this.matrix = matrix; |
| 40 |
matrix.addParameterListener(this); |
| 41 |
} |
| 42 |
|
| 43 |
public int getDimension() { |
| 44 |
return matrix.getDimension(); |
| 45 |
} |
| 46 |
|
| 47 |
public double getStatisticValue(int dim) { |
| 48 |
|
| 49 |
if (!inverseKnown) { |
| 50 |
inverse = (new Matrix(matrix.getParameterAsMatrix()).inverse().toComponents()); |
| 51 |
inverseKnown = true; |
| 52 |
} |
| 53 |
|
| 54 |
int x = dim / matrix.getColumnDimension(); |
| 55 |
int y = dim - x * matrix.getColumnDimension(); |
| 56 |
|
| 57 |
return inverse[x][y]; |
| 58 |
} |
| 59 |
|
| 60 |
public String getDimensionName(int dim) { |
| 61 |
return getStatisticName() + "." + matrix.getDimensionName(dim); |
| 62 |
} |
| 63 |
|
| 64 |
public void variableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { |
| 65 |
inverseKnown = false; |
| 66 |
} |
| 67 |
|
| 68 |
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { |
| 69 |
|
| 70 |
public String getParserName() { |
| 71 |
return INVERSE_STATISTIC; |
| 72 |
} |
| 73 |
|
| 74 |
public Object parseXMLObject(XMLObject xo) throws XMLParseException { |
| 75 |
|
| 76 |
MatrixParameter matrix = (MatrixParameter) xo.getChild(MatrixParameter.class); |
| 77 |
|
| 78 |
if (matrix.getColumnDimension() != matrix.getRowDimension()) |
| 79 |
throw new XMLParseException("Only square matrices can be inverted"); |
| 80 |
|
| 81 |
return new MatrixInverseStatistic(matrix); |
| 82 |
|
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
public String getParserDescription() { |
| 90 |
return "This element returns a statistic that is the matrix inverse of the child statistic."; |
| 91 |
} |
| 92 |
|
| 93 |
public Class getReturnType() { |
| 94 |
return MatrixInverseStatistic.class; |
| 95 |
} |
| 96 |
|
| 97 |
public XMLSyntaxRule[] getSyntaxRules() { |
| 98 |
return rules; |
| 99 |
} |
| 100 |
|
| 101 |
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ |
| 102 |
new ElementRule(MatrixParameter.class) |
| 103 |
}; |
| 104 |
}; |
| 105 |
|
| 106 |
private boolean inverseKnown = false; |
| 107 |
private double[][] inverse; |
| 108 |
private MatrixParameter matrix; |
| 109 |
} |