use of uk.ac.sussex.gdsc.smlm.function.FastLog in project GDSC-SMLM by aherbert.
the class LvmGradientProcedureTest method gradientProcedureIsNotSlowerThanGradientCalculator.
private void gradientProcedureIsNotSlowerThanGradientCalculator(RandomSeed seed, final int nparams, final Type type) {
Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MEDIUM));
final int iter = 1000;
final double[][] alpha = new double[nparams][nparams];
final double[] beta = new double[nparams];
final ArrayList<double[]> paramsList = new ArrayList<>(iter);
final ArrayList<double[]> yList = new ArrayList<>(iter);
final int[] x = createFakeData(RngUtils.create(seed.getSeed()), nparams, iter, paramsList, yList);
final int n = x.length;
final FakeGradientFunction func = new FakeGradientFunction(blockWidth, nparams);
final boolean mle = type != Type.LSQ;
final FastLog fastLog = (type == Type.FAST_LOG_MLE) ? getFastLog() : null;
final GradientCalculator calc = GradientCalculatorUtils.newCalculator(nparams, mle);
for (int i = 0; i < paramsList.size(); i++) {
calc.findLinearised(n, yList.get(i), paramsList.get(i), alpha, beta, func);
}
for (int i = 0; i < paramsList.size(); i++) {
final LvmGradientProcedure p = LvmGradientProcedureUtils.create(yList.get(i), func, type, fastLog);
p.gradient(paramsList.get(i));
}
// Realistic loops for an optimisation
final int loops = 15;
// Run till stable timing
final Timer t1 = new Timer() {
@Override
void run() {
for (int i = 0, k = 0; i < iter; i++) {
final GradientCalculator calc = GradientCalculatorUtils.newCalculator(nparams, mle);
for (int j = loops; j-- > 0; ) {
calc.findLinearised(n, yList.get(i), paramsList.get(k++ % iter), alpha, beta, func);
}
}
}
};
final long time1 = t1.getTime();
final Timer t2 = new Timer(t1.loops) {
@Override
void run() {
for (int i = 0, k = 0; i < iter; i++) {
final LvmGradientProcedure p = LvmGradientProcedureUtils.create(yList.get(i), func, type, fastLog);
for (int j = loops; j-- > 0; ) {
p.gradient(paramsList.get(k++ % iter));
}
}
}
};
final long time2 = t2.getTime();
logger.log(TestLogUtils.getTimingRecord(new TimingResult("GradientCalculator", time1), new TimingResult(() -> String.format("LVMGradientProcedure %d %s", nparams, type), time2)));
}
use of uk.ac.sussex.gdsc.smlm.function.FastLog in project GDSC-SMLM by aherbert.
the class LvmGradientProcedureTest method gradientProcedureComputesSameAsGradientCalculator.
private void gradientProcedureComputesSameAsGradientCalculator(RandomSeed seed, int nparams, Type type, double error) {
final int iter = 10;
final double[][] alpha = new double[nparams][nparams];
final double[] beta = new double[nparams];
final ArrayList<double[]> paramsList = new ArrayList<>(iter);
final ArrayList<double[]> yList = new ArrayList<>(iter);
final int[] x = createFakeData(RngUtils.create(seed.getSeed()), nparams, iter, paramsList, yList);
final int n = x.length;
final FakeGradientFunction func = new FakeGradientFunction(blockWidth, nparams);
final boolean mle = type != Type.LSQ;
final FastLog fastLog = (type == Type.FAST_LOG_MLE) ? getFastLog() : null;
final GradientCalculator calc = GradientCalculatorUtils.newCalculator(nparams, mle);
final String name = String.format("[%d] %b", nparams, mle);
// Create messages
final IndexSupplier msgR = new IndexSupplier(1, name + "Result: Not same ", null);
final IndexSupplier msgOb = new IndexSupplier(1, name + "Observations: Not same beta ", null);
final IndexSupplier msgOal = new IndexSupplier(1, name + "Observations: Not same alpha linear ", null);
final IndexSupplier msgOam = new IndexSupplier(1, name + "Observations: Not same alpha matrix ", null);
final DoubleDoubleBiPredicate predicate = (error == 0) ? TestHelper.doublesEqual() : TestHelper.doublesAreClose(error, 0);
for (int i = 0; i < paramsList.size(); i++) {
// Reference implementation
final double s = calc.findLinearised(n, yList.get(i), paramsList.get(i), alpha, beta, func);
// Procedure
final LvmGradientProcedure p = LvmGradientProcedureUtils.create(yList.get(i), func, type, fastLog);
p.gradient(paramsList.get(i));
final double s2 = p.value;
// Value may be different depending on log implementation
msgR.set(0, i);
TestAssertions.assertTest(s, s2, predicate, msgR);
// Exactly the same ...
Assertions.assertArrayEquals(p.beta, beta, msgOb.set(0, i));
final double[] al = p.getAlphaLinear();
Assertions.assertArrayEquals(al, new DenseMatrix64F(alpha).data, msgOal.set(0, i));
final double[][] am = p.getAlphaMatrix();
Assertions.assertArrayEquals(am, alpha, msgOam.set(0, i));
}
}
use of uk.ac.sussex.gdsc.smlm.function.FastLog in project GDSC-SMLM by aherbert.
the class LvmGradientProcedureTest method gradientProcedureSupportsPrecomputed.
private void gradientProcedureSupportsPrecomputed(RandomSeed seed, final Type type, boolean checkGradients) {
final int iter = 10;
final UniformRandomProvider rng = RngUtils.create(seed.getSeed());
final SharedStateContinuousSampler gs = SamplerUtils.createGaussianSampler(rng, 0, noise);
final ArrayList<double[]> paramsList = new ArrayList<>(iter);
final ArrayList<double[]> yList = new ArrayList<>(iter);
// 3 peaks
createData(rng, 3, iter, paramsList, yList, true);
for (int i = 0; i < paramsList.size(); i++) {
final double[] y = yList.get(i);
// Add Gaussian read noise so we have negatives
final double min = MathUtils.min(y);
for (int j = 0; j < y.length; j++) {
y[j] = y[i] - min + gs.sample();
}
}
// We want to know that:
// y|peak1+peak2+peak3 == y|peak1+peak2+peak3(precomputed)
// We want to know when:
// y|peak1+peak2+peak3 != y-peak3|peak1+peak2
// i.e. we cannot subtract a precomputed peak from the data, it must be included in the fit
// E.G. LSQ - subtraction is OK, MLE/WLSQ - subtraction is not allowed
final Gaussian2DFunction f123 = GaussianFunctionFactory.create2D(3, blockWidth, blockWidth, GaussianFunctionFactory.FIT_ERF_FREE_CIRCLE, null);
final Gaussian2DFunction f12 = GaussianFunctionFactory.create2D(2, blockWidth, blockWidth, GaussianFunctionFactory.FIT_ERF_FREE_CIRCLE, null);
final Gaussian2DFunction f3 = GaussianFunctionFactory.create2D(1, blockWidth, blockWidth, GaussianFunctionFactory.FIT_ERF_FREE_CIRCLE, null);
final FastLog fastLog = type == Type.FAST_LOG_MLE ? getFastLog() : null;
final int nparams = f12.getNumberOfGradients();
final int[] indices = f12.gradientIndices();
final double[] b = new double[f12.size()];
// for checking strict equivalence
final DoubleEquality eq = new DoubleEquality(1e-8, 1e-16);
// for the gradients
final double delta = 1e-4;
final DoubleEquality eq2 = new DoubleEquality(5e-2, 1e-16);
final double[] a1peaks = new double[1 + Gaussian2DFunction.PARAMETERS_PER_PEAK];
final double[] y_b = new double[b.length];
// Count the number of failures for each gradient
final int failureLimit = TestCounter.computeFailureLimit(iter, 0.1);
final TestCounter failCounter = new TestCounter(failureLimit, nparams * 2);
for (int i = 0; i < paramsList.size(); i++) {
final int ii = i;
final double[] y = yList.get(i);
final double[] a3peaks = paramsList.get(i);
// logger.fine(FunctionUtils.getSupplier("[%d] a=%s", i, Arrays.toString(a3peaks));
final double[] a2peaks = Arrays.copyOf(a3peaks, 1 + 2 * Gaussian2DFunction.PARAMETERS_PER_PEAK);
final double[] a2peaks2 = a2peaks.clone();
for (int j = 1; j < a1peaks.length; j++) {
a1peaks[j] = a3peaks[j + 2 * Gaussian2DFunction.PARAMETERS_PER_PEAK];
}
// Evaluate peak 3 to get the background and subtract it from the data to get the new data
f3.initialise0(a1peaks);
f3.forEach(new ValueProcedure() {
int index = 0;
@Override
public void execute(double value) {
b[index] = value;
// Remove negatives for MLE
if (type.isMle()) {
y[index] = Math.max(0, y[index]);
y_b[index] = Math.max(0, y[index] - value);
} else {
y_b[index] = y[index] - value;
}
index++;
}
});
final LvmGradientProcedure p123 = LvmGradientProcedureUtils.create(y, f123, type, fastLog);
// ///////////////////////////////////
// These should be the same
// ///////////////////////////////////
final LvmGradientProcedure p12b3 = LvmGradientProcedureUtils.create(y, OffsetGradient1Function.wrapGradient1Function(f12, b), type, fastLog);
// Check they are the same
p123.gradient(a3peaks);
final double[][] m123 = p123.getAlphaMatrix();
p12b3.gradient(a2peaks);
double value = p12b3.value;
final double[] beta = p12b3.beta.clone();
double[][] alpha = p12b3.getAlphaMatrix();
if (!eq.almostEqualRelativeOrAbsolute(p123.value, value)) {
Assertions.fail(FunctionUtils.getSupplier("p12b3 Not same value @ %d (error=%s) : %s == %s", i, DoubleEquality.relativeError(p123.value, value), p123.value, value));
}
if (!almostEqualRelativeOrAbsolute(eq, beta, p123.beta)) {
Assertions.fail(FunctionUtils.getSupplier("p12b3 Not same gradient @ %d (error=%s) : %s vs %s", i, relativeError(beta, p123.beta), Arrays.toString(beta), Arrays.toString(p123.beta)));
}
for (int j = 0; j < alpha.length; j++) {
// Arrays.toString(m123[j]));
if (!almostEqualRelativeOrAbsolute(eq, alpha[j], m123[j])) {
Assertions.fail(FunctionUtils.getSupplier("p12b3 Not same alpha @ %d,%d (error=%s) : %s vs %s", i, j, relativeError(alpha[j], m123[j]), Arrays.toString(alpha[j]), Arrays.toString(m123[j])));
}
}
// Check actual gradients are correct
if (checkGradients) {
for (int j = 0; j < nparams; j++) {
final int jj = j;
final int k = indices[j];
// double d = Precision.representableDelta(a2peaks[k], (a2peaks[k] == 0) ? 1e-3 :
// a2peaks[k] * delta);
final double d = Precision.representableDelta(a2peaks[k], delta);
a2peaks2[k] = a2peaks[k] + d;
p12b3.value(a2peaks2);
final double s1 = p12b3.value;
a2peaks2[k] = a2peaks[k] - d;
p12b3.value(a2peaks2);
final double s2 = p12b3.value;
a2peaks2[k] = a2peaks[k];
// Apply a factor of -2 to compute the actual gradients:
// See Numerical Recipes in C++, 2nd Ed. Equation 15.5.6 for Nonlinear Models
beta[j] *= -2;
final double gradient = (s1 - s2) / (2 * d);
// logger.fine(FunctionUtils.getSupplier("[%d,%d] %f (%s %f+/-%f) %f ?= %f (%f)", i, k, s,
// Gaussian2DFunction.getName(k), a2peaks[k], d, beta[j], gradient,
// DoubleEquality.relativeError(gradient, beta[j]));
failCounter.run(j, () -> eq2.almostEqualRelativeOrAbsolute(beta[jj], gradient), () -> {
Assertions.fail(() -> String.format("Not same gradient @ %d,%d: %s != %s (error=%s)", ii, jj, beta[jj], gradient, DoubleEquality.relativeError(beta[jj], gradient)));
});
}
}
// ///////////////////////////////////
// This may be different
// ///////////////////////////////////
final LvmGradientProcedure p12m3 = LvmGradientProcedureUtils.create(y_b, f12, type, fastLog);
// Check these may be different.
// Sometimes they are not different.
p12m3.gradient(a2peaks);
value = p12m3.value;
System.arraycopy(p12m3.beta, 0, beta, 0, p12m3.beta.length);
alpha = p12m3.getAlphaMatrix();
if (type != Type.LSQ) {
if (eq.almostEqualRelativeOrAbsolute(p123.value, value)) {
logger.log(TestLogUtils.getFailRecord("p12b3 Same value @ %d (error=%s) : %s == %s", i, DoubleEquality.relativeError(p123.value, value), p123.value, value));
}
if (almostEqualRelativeOrAbsolute(eq, beta, p123.beta)) {
logger.log(TestLogUtils.getFailRecord("p12b3 Same gradient @ %d (error=%s) : %s vs %s", i, relativeError(beta, p123.beta), Arrays.toString(beta), Arrays.toString(p123.beta)));
}
// Note: Test the matrix is different by finding 1 different column
int dj = -1;
for (int j = 0; j < alpha.length; j++) {
// Arrays.toString(m123[j]));
if (!almostEqualRelativeOrAbsolute(eq, alpha[j], m123[j])) {
// Different column
dj = j;
break;
}
}
if (dj == -1) {
// Find biggest error for reporting. This helps set the test tolerance.
double error = 0;
dj = -1;
for (int j = 0; j < alpha.length; j++) {
final double e = relativeError(alpha[j], m123[j]);
if (error <= e) {
error = e;
dj = j;
}
}
logger.log(TestLogUtils.getFailRecord("p12b3 Same alpha @ %d,%d (error=%s) : %s vs %s", i, dj, error, Arrays.toString(alpha[dj]), Arrays.toString(m123[dj])));
}
} else {
if (!eq.almostEqualRelativeOrAbsolute(p123.value, value)) {
logger.log(TestLogUtils.getFailRecord("p12b3 Not same value @ %d (error=%s) : %s == %s", i, DoubleEquality.relativeError(p123.value, value), p123.value, value));
}
if (!almostEqualRelativeOrAbsolute(eq, beta, p123.beta)) {
logger.log(TestLogUtils.getFailRecord("p12b3 Not same gradient @ %d (error=%s) : %s vs %s", i, relativeError(beta, p123.beta), Arrays.toString(beta), Arrays.toString(p123.beta)));
}
for (int j = 0; j < alpha.length; j++) {
// Arrays.toString(m123[j]));
if (!almostEqualRelativeOrAbsolute(eq, alpha[j], m123[j])) {
logger.log(TestLogUtils.getFailRecord("p12b3 Not same alpha @ %d,%d (error=%s) : %s vs %s", i, j, relativeError(alpha[j], m123[j]), Arrays.toString(alpha[j]), Arrays.toString(m123[j])));
}
}
}
// Check actual gradients are correct
if (!checkGradients) {
continue;
}
for (int j = 0; j < nparams; j++) {
final int jj = j;
final int k = indices[j];
// double d = Precision.representableDelta(a2peaks[k], (a2peaks[k] == 0) ? 1e-3 : a2peaks[k]
// * delta);
final double d = Precision.representableDelta(a2peaks[k], delta);
a2peaks2[k] = a2peaks[k] + d;
p12m3.value(a2peaks2);
final double s1 = p12m3.value;
a2peaks2[k] = a2peaks[k] - d;
p12m3.value(a2peaks2);
final double s2 = p12m3.value;
a2peaks2[k] = a2peaks[k];
// Apply a factor of -2 to compute the actual gradients:
// See Numerical Recipes in C++, 2nd Ed. Equation 15.5.6 for Nonlinear Models
beta[j] *= -2;
final double gradient = (s1 - s2) / (2 * d);
// logger.fine(FunctionUtils.getSupplier("[%d,%d] %f (%s %f+/-%f) %f ?= %f (%f)", i, k, s,
// Gaussian2DFunction.getName(k), a2peaks[k], d, beta[j], gradient,
// DoubleEquality.relativeError(gradient, beta[j]));
failCounter.run(nparams + j, () -> eq2.almostEqualRelativeOrAbsolute(beta[jj], gradient), () -> {
Assertions.fail(() -> String.format("Not same gradient @ %d,%d: %s != %s (error=%s)", ii, jj, beta[jj], gradient, DoubleEquality.relativeError(beta[jj], gradient)));
});
}
}
}
use of uk.ac.sussex.gdsc.smlm.function.FastLog in project GDSC-SMLM by aherbert.
the class LvmGradientProcedureTest method gradientProcedureComputesGradient.
@SuppressWarnings("null")
private void gradientProcedureComputesGradient(RandomSeed seed, ErfGaussian2DFunction func, Type type, boolean precomputed) {
final int nparams = func.getNumberOfGradients();
final int[] indices = func.gradientIndices();
final int iter = 100;
final ArrayList<double[]> paramsList = new ArrayList<>(iter);
final ArrayList<double[]> yList = new ArrayList<>(iter);
createData(RngUtils.create(seed.getSeed()), 1, iter, paramsList, yList, true);
// for the gradients
final double delta = 1e-4;
final DoubleEquality eq = new DoubleEquality(5e-2, 1e-16);
final double[] b = (precomputed) ? new double[func.size()] : null;
final FastLog fastLog = type == Type.FAST_LOG_MLE ? getFastLog() : null;
// Must compute most of the time
final int failureLimit = TestCounter.computeFailureLimit(iter, 0.1);
final TestCounter failCounter = new TestCounter(failureLimit, nparams);
for (int i = 0; i < paramsList.size(); i++) {
final int ii = i;
final double[] y = yList.get(i);
final double[] a = paramsList.get(i);
final double[] a2 = a.clone();
LvmGradientProcedure gp;
if (precomputed) {
// Mock fitting part of the function already
for (int j = 0; j < b.length; j++) {
b[j] = y[j] * 0.5;
}
gp = LvmGradientProcedureUtils.create(y, OffsetGradient1Function.wrapGradient1Function(func, b), type, fastLog);
} else {
gp = LvmGradientProcedureUtils.create(y, func, type, fastLog);
}
gp.gradient(a);
// double s = p.value;
final double[] beta = gp.beta.clone();
for (int j = 0; j < nparams; j++) {
final int jj = j;
final int k = indices[j];
// double d = Precision.representableDelta(a[k], (a[k] == 0) ? 1e-3 : a[k] * delta);
final double d = Precision.representableDelta(a[k], delta);
a2[k] = a[k] + d;
gp.value(a2);
final double s1 = gp.value;
a2[k] = a[k] - d;
gp.value(a2);
final double s2 = gp.value;
a2[k] = a[k];
// Apply a factor of -2 to compute the actual gradients:
// See Numerical Recipes in C++, 2nd Ed. Equation 15.5.6 for Nonlinear Models
beta[j] *= -2;
final double gradient = (s1 - s2) / (2 * d);
// logger.fine(FunctionUtils.getSupplier("[%d,%d] %f (%s %f+/-%f) %f ?= %f", i, k, s,
// Gaussian2DFunction.getName(k),
// a[k], d, beta[j], gradient);
failCounter.run(j, () -> eq.almostEqualRelativeOrAbsolute(beta[jj], gradient), () -> {
Assertions.fail(() -> String.format("Not same gradient @ %d,%d: %s != %s (error=%s)", ii, jj, beta[jj], gradient, DoubleEquality.relativeError(beta[jj], gradient)));
});
}
}
}
use of uk.ac.sussex.gdsc.smlm.function.FastLog in project GDSC-SMLM by aherbert.
the class LvmGradientProcedureTest method gradientProcedureIsFasterUnrolledThanGradientProcedure.
private void gradientProcedureIsFasterUnrolledThanGradientProcedure(RandomSeed seed, final int nparams, final Type type, final boolean precomputed) {
Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MEDIUM));
final int iter = 100;
final ArrayList<double[]> paramsList = new ArrayList<>(iter);
final ArrayList<double[]> yList = new ArrayList<>(iter);
createData(RngUtils.create(seed.getSeed()), 1, iter, paramsList, yList);
// Remove the timing of the function call by creating a dummy function
final FakeGradientFunction fgf = new FakeGradientFunction(blockWidth, nparams);
final Gradient1Function func;
if (precomputed) {
final double[] b = SimpleArrayUtils.newArray(fgf.size(), 0.1, 1.3);
func = OffsetGradient1Function.wrapGradient1Function(fgf, b);
} else {
func = fgf;
}
final FastLog fastLog = type == Type.FAST_LOG_MLE ? getFastLog() : null;
final IntArrayFormatSupplier msgA = new IntArrayFormatSupplier("A [%d]", 1);
final IntArrayFormatSupplier msgB = new IntArrayFormatSupplier("B [%d]", 1);
for (int i = 0; i < paramsList.size(); i++) {
final LvmGradientProcedure p1 = createProcedure(type, yList.get(i), func, fastLog);
p1.gradient(paramsList.get(i));
p1.gradient(paramsList.get(i));
final LvmGradientProcedure p2 = LvmGradientProcedureUtils.create(yList.get(i), func, type, fastLog);
p2.gradient(paramsList.get(i));
p2.gradient(paramsList.get(i));
// Check they are the same
Assertions.assertArrayEquals(p1.getAlphaLinear(), p2.getAlphaLinear(), msgA.set(0, i));
Assertions.assertArrayEquals(p1.beta, p2.beta, msgB.set(0, i));
}
// Realistic loops for an optimisation
final int loops = 15;
// Run till stable timing
final Timer t1 = new Timer() {
@Override
void run() {
for (int i = 0, k = 0; i < paramsList.size(); i++) {
final LvmGradientProcedure p1 = createProcedure(type, yList.get(i), func, fastLog);
for (int j = loops; j-- > 0; ) {
p1.gradient(paramsList.get(k++ % iter));
}
}
}
};
final long time1 = t1.getTime();
final Timer t2 = new Timer(t1.loops) {
@Override
void run() {
for (int i = 0, k = 0; i < paramsList.size(); i++) {
final LvmGradientProcedure p2 = LvmGradientProcedureUtils.create(yList.get(i), func, type, fastLog);
for (int j = loops; j-- > 0; ) {
p2.gradient(paramsList.get(k++ % iter));
}
}
}
};
final long time2 = t2.getTime();
logger.log(TestLogUtils.getTimingRecord(new TimingResult(() -> String.format("%s, Precomputed=%b : Standard", type, precomputed), time1), new TimingResult(() -> String.format("Unrolled %d", nparams), time2)));
}
Aggregations