| 9 | import com.winvector.opt.impl.NormPenalty; |
| 10 | |
| 11 | public class TestOpt extends TestCase { |
| 12 | |
| 13 | private static VEval numericlyBuildGradientAndHessian(final VectorFn f, final double[] x, final double epsilon) { |
| 14 | final VEval ret = new VEval(x,true,true); |
| 15 | final VEval fx = f.eval(x,false,false); |
| 16 | ret.fx = fx.fx; |
| 17 | final int dim = f.dim(); |
| 18 | final double[] xp = LinUtil.copy(x); |
| 19 | final double[] fxp = new double[dim]; |
| 20 | for(int i=0;i<dim;++i) { |
| 21 | xp[i] = x[i]+epsilon; |
| 22 | final VEval fxpi = f.eval(xp,false,false); |
| 23 | xp[i] = x[i]; |
| 24 | fxp[i] = fxpi.fx; |
| 25 | final double gi = (fxpi.fx - fx.fx)/epsilon; |
| 26 | ret.gx[i] = gi; |
| 27 | } |
| 28 | for(int i=0;i<dim;++i) { |
| 29 | final double fxpi = fxp[i]; |
| 30 | for(int j=0;j<dim;++j) { |
| 31 | final double fxpj = fxp[j]; |
| 32 | if(i==j) { |
| 33 | xp[i] = x[i]+2.0*epsilon; |
| 34 | } else { |
| 35 | xp[i] = x[i]+epsilon; |
| 36 | xp[j] = x[j]+epsilon; |
| 37 | } |
| 38 | final VEval fxpij = f.eval(xp,false,false); |
| 39 | xp[i] = x[i]; |
| 40 | xp[j] = x[j]; |
| 41 | final double hij = (fxpij.fx + fx.fx - (fxpi + fxpj))/(epsilon*epsilon); |
| 42 | ret.hx[i][j] = hij; |
| 43 | } |
| 44 | } |
| 45 | return ret; |
| 46 | } |
| 47 | |
| 48 | public static void testGradAndHessian(final VectorFn f, final double[] x, final double epsilon, final double tol) { |
| 49 | final VEval fx = f.eval(x,true,true); |
| 50 | //System.out.println("fx: " + fx); |
| 51 | final VEval fn = numericlyBuildGradientAndHessian(f,x,epsilon); |
| 52 | //System.out.println("fn: " + fn); |
| 53 | final int dim = f.dim(); |
| 54 | for(int i=0;i<dim;++i) { |
| 55 | if(Math.abs(fx.gx[i]-fn.gx[i])>=tol) { //extra if lets us set a breakpoint |
| 56 | assertTrue(Math.abs(fx.gx[i]-fn.gx[i])<tol); |
| 57 | } |
| 58 | for(int j=0;j<dim;++j) { |
| 59 | if(Math.abs(fx.hx[i][j]-fn.hx[i][j])>=tol) { //extra if lets us set a breakpoint |
| 60 | assertTrue(Math.abs(fx.hx[i][j]-fn.hx[i][j])<tol); |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | |
| 67 | public void testNormV() { |
| 68 | // norm penalty should put max at 0 (and max value should be 0) |
nothing calls this directly
no outgoing calls
no test coverage detected