Ejemplo n.º 1
1
 public void testAdd() {
   int num1 = 3;
   int num2 = 2;
   int total = 5;
   int sum = 0;
   sum = Math.add(num1, num2);
   assertEquals(sum, total);
 }
  public void testMinStep() {

    try {
      TestProblem5 pb = new TestProblem5();
      double minStep = 0.1 * Math.abs(pb.getFinalTime() - pb.getInitialTime());
      double maxStep = Math.abs(pb.getFinalTime() - pb.getInitialTime());
      double[] vecAbsoluteTolerance = {1.0e-20, 1.0e-21};
      double[] vecRelativeTolerance = {1.0e-20, 1.0e-21};

      FirstOrderIntegrator integ =
          new GraggBulirschStoerIntegrator(
              minStep, maxStep,
              vecAbsoluteTolerance, vecRelativeTolerance);
      TestProblemHandler handler = new TestProblemHandler(pb, integ);
      integ.addStepHandler(handler);
      integ.integrate(
          pb,
          pb.getInitialTime(),
          pb.getInitialState(),
          pb.getFinalTime(),
          new double[pb.getDimension()]);
      fail("an exception should have been thrown");
    } catch (DerivativeException de) {
      fail("wrong exception caught");
    } catch (IntegratorException ie) {
    }
  }
  /** Test of generateQAMSignal method, of class simulator.qam.FadingNoisyQAM. */
  public void testGenerateQAMSignal() {
    System.out.println("generateQAMSignal");

    FadingNoisyQAM instance = new FadingNoisyQAM();

    double[] xr = instance.getTransmittedRealQAMSignal();
    double[] xi = instance.getTransmittedImagQAMSignal();

    for (int i = 0; i < xr.length; i++) {
      assertEquals(true, Math.abs(xr[i]) <= 7);
      assertEquals(true, Math.abs(xr[i]) <= 7);
    }
  }
Ejemplo n.º 4
0
  public void testMulitply() {

    int num1 = 3;
    int num2 = 7;
    int total = 14;
    int sum = 0;
    sum = Math.multiply(num1, num2);
    assertEquals("Problem with multiply", sum, total);

    num1 = 5;
    num2 = 4;
    total = 20;
    sum = Math.multiply(num1, num2);
    assertEquals("Problem with multiply", sum, total);
  }
Ejemplo n.º 5
0
 private double computeFitness(IGPProgram a_program, Variable vx) {
   double error = 0.0f;
   Object[] noargs = new Object[0];
   // Initialize local stores.
   // ------------------------
   a_program.getGPConfiguration().clearStack();
   a_program.getGPConfiguration().clearMemory();
   // Compute fitness for each program.
   // ---------------------------------
   for (int i = 2; i < 15; i++) {
     for (int j = 0; j < a_program.size(); j++) {
       vx.set(new Integer(i));
       try {
         try {
           // Only evaluate after whole GP program was run.
           // ---------------------------------------------
           if (j == a_program.size() - 1) {
             double result = a_program.execute_int(j, noargs);
             error += Math.abs(result - fib_iter(i));
           } else {
             a_program.execute_void(j, noargs);
           }
         } catch (IllegalStateException iex) {
           error = Double.MAX_VALUE / 2;
           break;
         }
       } catch (ArithmeticException ex) {
         System.out.println("Arithmetic Exception with x = " + i);
         System.out.println(a_program.getChromosome(j));
         throw ex;
       }
     }
   }
   return error;
 }
  public void testModelsMerging() throws DerivativeException, IntegratorException {

    // theoretical solution: y[0] = cos(t), y[1] = sin(t)
    FirstOrderDifferentialEquations problem =
        new FirstOrderDifferentialEquations() {
          public void computeDerivatives(double t, double[] y, double[] dot)
              throws DerivativeException {
            dot[0] = -y[1];
            dot[1] = y[0];
          }

          public int getDimension() {
            return 2;
          }
        };

    // integrate backward from &pi; to 0;
    ContinuousOutputModel cm1 = new ContinuousOutputModel();
    FirstOrderIntegrator integ1 = new DormandPrince853Integrator(0, 1.0, 1.0e-8, 1.0e-8);
    integ1.setStepHandler(cm1);
    integ1.integrate(problem, Math.PI, new double[] {-1.0, 0.0}, 0, new double[2]);

    // integrate backward from 2&pi; to &pi;
    ContinuousOutputModel cm2 = new ContinuousOutputModel();
    FirstOrderIntegrator integ2 = new DormandPrince853Integrator(0, 0.1, 1.0e-12, 1.0e-12);
    integ2.setStepHandler(cm2);
    integ2.integrate(problem, 2.0 * Math.PI, new double[] {1.0, 0.0}, Math.PI, new double[2]);

    // merge the two half circles
    ContinuousOutputModel cm = new ContinuousOutputModel();
    cm.append(cm2);
    cm.append(new ContinuousOutputModel());
    cm.append(cm1);

    // check circle
    assertEquals(2.0 * Math.PI, cm.getInitialTime(), 1.0e-12);
    assertEquals(0, cm.getFinalTime(), 1.0e-12);
    assertEquals(cm.getFinalTime(), cm.getInterpolatedTime(), 1.0e-12);
    for (double t = 0; t < 2.0 * Math.PI; t += 0.1) {
      cm.setInterpolatedTime(t);
      double[] y = cm.getInterpolatedState();
      assertEquals(Math.cos(t), y[0], 1.0e-7);
      assertEquals(Math.sin(t), y[1], 1.0e-7);
    }
  }
    public void handleStep(StepInterpolator interpolator, boolean isLast) {

      double step = Math.abs(interpolator.getCurrentTime() - interpolator.getPreviousTime());
      if (firstTime) {
        minStep = Math.abs(step);
        maxStep = minStep;
        firstTime = false;
      } else {
        if (step < minStep) {
          minStep = step;
        }
        if (step > maxStep) {
          maxStep = step;
        }
      }

      if (isLast) {
        assertTrue(minStep < 8.2e-3);
        assertTrue(maxStep > 1.7);
      }
    }
  protected void setUp() throws AWTException {
    // set up the kRobot for grabbing colors
    if (kRobot == null) {
      kRobot = new Robot();
    }

    // Set up probe points just off the test lines
    if (kProbePoints == null) {
      kProbePoints = new Point[kRects.length * 2];

      for (int i = 0; i < kRects.length; i++) {
        int midW = (int) Math.rint(kRects[i].width / 2.0);
        int midH = (int) Math.rint(kRects[i].height / 2.0);

        if (kRects[i].width > kRects[i].height) {
          kProbePoints[2 * i] = new Point(kRects[i].x + midW + 1, kRects[i].y + midH);
          kProbePoints[2 * i + 1] = new Point(kRects[i].x + midW, kRects[i].y + midH + 1);
        } else {
          kProbePoints[2 * i] = new Point(kRects[i].x + midW - 1, kRects[i].y + midH);
          kProbePoints[2 * i + 1] = new Point(kRects[i].x + midW, kRects[i].y + midH - 1);
        }
      }
    }
  }
  // test offset only gets applied once
  public void testWrapOnce() throws IOException {
    String filename = TestAll.cdmUnitTestDir + "ncml/coords/testCoordScaling.ncml";
    System.out.printf("%s%n", filename);
    NetcdfDataset ncd = ucar.nc2.dataset.NetcdfDataset.openDataset(filename);
    Variable v = ncd.findCoordinateAxis("Longitude");
    assert v != null;
    assert v instanceof CoordinateAxis1D;

    // if offset is applied twice, the result is not in +-180 range
    Array data = v.read();
    NCdumpW.printArray(data);
    IndexIterator ii = data.getIndexIterator();
    while (ii.hasNext()) {
      assert Math.abs(ii.getDoubleNext()) < 180 : ii.getDoubleCurrent();
    }
  }
  public void testIncreasingTolerance() throws DerivativeException, IntegratorException {

    int previousCalls = Integer.MAX_VALUE;
    for (int i = -12; i < -4; ++i) {
      TestProblem1 pb = new TestProblem1();
      double minStep = 0;
      double maxStep = pb.getFinalTime() - pb.getInitialTime();
      double absTolerance = Math.pow(10.0, i);
      double relTolerance = absTolerance;

      FirstOrderIntegrator integ =
          new GraggBulirschStoerIntegrator(
              minStep, maxStep,
              absTolerance, relTolerance);
      TestProblemHandler handler = new TestProblemHandler(pb, integ);
      integ.addStepHandler(handler);
      integ.integrate(
          pb,
          pb.getInitialTime(),
          pb.getInitialState(),
          pb.getFinalTime(),
          new double[pb.getDimension()]);

      // the coefficients are only valid for this test
      // and have been obtained from trial and error
      // there is no general relation between local and global errors
      double ratio = handler.getMaximalValueError() / absTolerance;
      assertTrue(ratio < 2.4);
      assertTrue(ratio > 0.02);
      assertEquals(0, handler.getMaximalTimeError(), 1.0e-12);

      int calls = pb.getCalls();
      assertEquals(integ.getEvaluations(), calls);
      assertTrue(calls <= previousCalls);
      previousCalls = calls;
    }
  }
 public void checkValue(double value, double reference) {
   assertTrue(Math.abs(value - reference) < 1.0e-10);
 }
 boolean close(double d1, double d2) {
   return Math.abs(d1 - d2) < TOLERENCE;
 }
Ejemplo n.º 13
0
  public static double testCostAndGradientCurrentParameters(Minimizable.ByGradient minable) {
    Matrix parameters = minable.getParameters(minable.getNewMatrix());
    double cost = minable.getCost();
    // the gradient from the minimizable function
    Matrix analyticGradient = minable.getCostGradient(minable.getNewMatrix());
    // the gradient calculate from the slope of the cost
    Matrix empiricalGradient = (Matrix) analyticGradient.cloneMatrix();
    // This setting of epsilon should make the individual elements of
    // the analytical gradient and the empirical gradient equal.  This
    // simplifies the comparison of the individual dimensions of the
    // gradient and thus makes debugging easier.
    double epsilon = 0.1 / analyticGradient.twoNorm();
    double tolerance = epsilon * 5;
    System.out.println("epsilon = " + epsilon + " tolerance=" + tolerance);

    // Check each direction, perturb it, measure new cost,
    // and make sure it agrees with the gradient from minable.getCostGradient()
    for (int i = 0; i < parameters.singleSize(); i++) {
      double param = parameters.singleValue(i);
      parameters.setSingleValue(i, param + epsilon);
      // logger.fine ("Parameters:"); parameters.print();
      minable.setParameters(parameters);
      double epsCost = minable.getCost();
      double slope = (epsCost - cost) / epsilon;
      System.out.println(
          "cost="
              + cost
              + " epsCost="
              + epsCost
              + " slope["
              + i
              + "] = "
              + slope
              + " gradient[]="
              + analyticGradient.singleValue(i));
      assert (!Double.isNaN(slope));
      logger.fine(
          "TestMinimizable checking singleIndex "
              + i
              + ": gradient slope = "
              + analyticGradient.singleValue(i)
              + ", cost+epsilon slope = "
              + slope
              + ": slope difference = "
              + Math.abs(slope - analyticGradient.singleValue(i)));
      // No negative below because the gradient points in the direction
      // of maximizing the function.
      empiricalGradient.setSingleValue(i, slope);
      parameters.setSingleValue(i, param);
    }
    // Normalize the matrices to have the same L2 length
    System.out.println("empiricalGradient.twoNorm = " + empiricalGradient.twoNorm());
    analyticGradient.timesEquals(1.0 / analyticGradient.twoNorm());
    empiricalGradient.timesEquals(1.0 / empiricalGradient.twoNorm());
    // logger.info ("AnalyticGradient:"); analyticGradient.print();
    // logger.info ("EmpiricalGradient:"); empiricalGradient.print();
    // Return the angle between the two vectors, in radians
    double angle = Math.acos(analyticGradient.dotProduct(empiricalGradient));
    logger.info("TestMinimizable angle = " + angle);
    if (Math.abs(angle) > tolerance)
      throw new IllegalStateException("Gradient/Cost mismatch: angle=" + angle);
    if (Double.isNaN(angle)) throw new IllegalStateException("Gradient/Cost error: angle is NaN!");
    return angle;
  }
Ejemplo n.º 14
0
 private void checkValue(double value, double expected) {
   assertTrue(Math.abs(value - expected) < 1.0e-10);
 }