// 记录缩放前的一些信息
 private void saveScaleContext(float x1, float y1, float x2, float y2) {
   mScaleBase = MathUtils.getMatrixScale(mOuterMatrix)[0] / MathUtils.getDistance(x1, y1, x2, y2);
   // 获取缩放缩放点中点在第一层变换后的图片上的坐标
   float[] center =
       MathUtils.inverseMatrixPoint(MathUtils.getCenterPoint(x1, y1, x2, y2), mOuterMatrix);
   mScaleCenter.set(center[0], center[1]);
 }
Exemple #2
0
  /**
   * * Least-square solution y = X * b where: y_i = b_0 + b_1*x_1i + b_2*x_2i + ... + b_k*x_ki
   * including intercep term y_i = b_1*x_1i + b_2*x_2i + ... + b_k*x_ki without intercep term
   *
   * @param datay
   * @param dataX
   */
  private void multipleLinearRegression(Matrix datay, Matrix dataX) {
    Matrix X, y;
    try {
      X = dataX;
      y = datay;
      b = X.solve(y);
      coeffs = new double[b.getRowDimension()];
      for (int j = 0; j < b.getRowDimension(); j++) {
        coeffs[j] = b.get(j, 0);
        // System.out.println("coeff[" + j + "]=" + coeffs[j]);
      }

      // Residuals:
      Matrix r = X.times(b).minus(y);
      residuals = r.getColumnPackedCopy();
      // root mean square error (RMSE)
      rmse = Math.sqrt(MathUtils.sumSquared(residuals) / residuals.length);

      // Predicted values
      Matrix p = X.times(b);
      predictedValues = p.getColumnPackedCopy();

      // Correlation between original values and predicted ones
      correlation = MathUtils.correlation(predictedValues, y.getColumnPackedCopy());

    } catch (RuntimeException re) {
      throw new Error("Error solving Least-square solution: y = X * b");
    }
  }
  @Test
  public void testNumericalGradient() {
    // our function is f(x,y) = x^2+y^2
    // the derivative is f'(x,y) = 2x+2y
    final CostFunction inlineFunction =
        new CostFunction() {
          @Override
          public CostGradientTuple evaluateCost(DoubleVector input) {

            double cost = Math.pow(input.get(0), 2) + Math.pow(input.get(1), 2);
            DenseDoubleVector gradient =
                new DenseDoubleVector(new double[] {input.get(0) * 2, input.get(1) * 2});

            return new CostGradientTuple(cost, gradient);
          }
        };
    DenseDoubleVector v = new DenseDoubleVector(new double[] {0, 1});
    CostGradientTuple cost = inlineFunction.evaluateCost(v);
    DoubleVector numericalGradient = MathUtils.numericalGradient(v, inlineFunction);
    assertSmallDiff(numericalGradient, cost.getGradient());

    v = new DenseDoubleVector(new double[] {-15, 100});
    cost = inlineFunction.evaluateCost(v);

    numericalGradient = MathUtils.numericalGradient(v, inlineFunction);
    assertSmallDiff(numericalGradient, cost.getGradient());
  }
  private double getValue(PeakListRow row) {
    switch (property) {
      case Area:
        ChromatographicPeak[] areaPeaks = row.getPeaks();
        double[] peakAreas = new double[areaPeaks.length];
        for (int i = 0; i < peakAreas.length; i++) peakAreas[i] = areaPeaks[i].getArea();
        double medianArea = MathUtils.calcQuantile(peakAreas, 0.5);
        return medianArea;
      case Intensity:
        ChromatographicPeak[] intensityPeaks = row.getPeaks();
        double[] peakIntensities = new double[intensityPeaks.length];
        for (int i = 0; i < intensityPeaks.length; i++)
          peakIntensities[i] = intensityPeaks[i].getArea();
        double medianIntensity = MathUtils.calcQuantile(peakIntensities, 0.5);
        return medianIntensity;
      case Height:
        ChromatographicPeak[] heightPeaks = row.getPeaks();
        double[] peakHeights = new double[heightPeaks.length];
        for (int i = 0; i < peakHeights.length; i++) peakHeights[i] = heightPeaks[i].getHeight();
        double medianHeight = MathUtils.calcQuantile(peakHeights, 0.5);
        return medianHeight;
      case MZ:
        return row.getAverageMZ();
      case RT:
        return row.getAverageRT();
      case ID:
        return row.getID();
    }

    // We should never get here, so throw exception
    throw (new IllegalStateException());
  }
Exemple #5
0
 public static Dimension parseDimension(String str) {
   String[] tokenized = tokenize(str, "x,");
   if (tokenized.length != 2) return null;
   int i = MathUtils.parseInt(tokenized[0], -1);
   int j = MathUtils.parseInt(tokenized[1], -1);
   if ((i < 0) || (j < 0)) return null;
   return new Dimension(i, j);
 }
  public int acceptEnergy(int offeredAmount) {
    if (BlockUtils.isUnbreakableBlock(world, x, y, z)) {
      hasFailed = true;
      return 0;
    }

    energyRequired = BlockUtils.computeBlockBreakEnergy(world, x, y, z);

    int usedAmount =
        MathUtils.clamp(offeredAmount, 0, Math.max(0, energyRequired - energyAccepted));
    energyAccepted += usedAmount;

    if (energyAccepted >= energyRequired) {
      world.destroyBlockInWorldPartially(minerId, x, y, z, -1);

      hasMined = true;

      Block block = world.getBlock(x, y, z);
      int meta = world.getBlockMetadata(x, y, z);

      BlockEvent.BreakEvent breakEvent =
          new BlockEvent.BreakEvent(
              x,
              y,
              z,
              world,
              block,
              meta,
              CoreProxy.proxy.getBuildCraftPlayer((WorldServer) world).get());
      MinecraftForge.EVENT_BUS.post(breakEvent);

      if (!breakEvent.isCanceled()) {
        List<ItemStack> stacks = BlockUtils.getItemStackFromBlock((WorldServer) world, x, y, z);

        if (stacks != null) {
          for (ItemStack s : stacks) {
            if (s != null) {
              mineStack(s);
            }
          }
        }

        world.playAuxSFXAtEntity(null, 2001, x, y, z, Block.getIdFromBlock(block) + (meta << 12));

        world.setBlockToAir(x, y, z);
      } else {
        hasFailed = true;
      }
    } else {
      world.destroyBlockInWorldPartially(
          minerId,
          x,
          y,
          z,
          MathUtils.clamp((int) Math.floor(energyAccepted * 10 / energyRequired), 0, 9));
    }
    return usedAmount;
  }
 @Test
 public void testPolynomials() {
   DenseDoubleMatrix mat = new DenseDoubleMatrix(new double[][] {{2, 5}, {5, 1}, {7, 25}});
   DenseDoubleMatrix expected =
       new DenseDoubleMatrix(new double[][] {{2, 4, 5, 25}, {5, 25, 1, 1}, {7, 49, 25, 625}});
   DenseDoubleMatrix polys = MathUtils.createPolynomials(mat, 2);
   assertEquals(polys.subtract(expected).sum(), 0, 1E-5);
   assertEquals(mat, MathUtils.createPolynomials(mat, 1));
 }
  @Test(expected = IllegalArgumentException.class)
  public void toCachedThrowsIfGroupElementHasP1P1Representation() {
    // Arrange:
    final GroupElement g =
        MathUtils.toRepresentation(
            MathUtils.getRandomGroupElement(), GroupElement.Representation.P1P1);

    // Assert:
    g.toCached();
  }
  @Test(expected = IllegalArgumentException.class)
  public void toP3ThrowsIfGroupElementHasPrecompRepresentation() {
    // Arrange:
    final GroupElement g =
        MathUtils.toRepresentation(
            MathUtils.getRandomGroupElement(), GroupElement.Representation.PRECOMP);

    // Assert:
    g.toP3();
  }
  public int acceptEnergy(int offeredAmount) {
    energyRequired = BlockUtils.computeBlockBreakEnergy(world, x, y, z);

    int usedAmount =
        MathUtils.clamp(offeredAmount, 0, Math.max(0, energyRequired - energyAccepted));
    energyAccepted += usedAmount;

    if (energyAccepted >= energyRequired) {
      world.destroyBlockInWorldPartially(minerId, x, y, z, -1);

      hasMined = true;

      Block block = world.getBlock(x, y, z);
      int meta = world.getBlockMetadata(x, y, z);

      /* TODO gamerforEA code replace, old code:
      BlockEvent.BreakEvent breakEvent = new BlockEvent.BreakEvent(x, y, z, world, block, meta, CoreProxy.proxy.getBuildCraftPlayer((WorldServer) world).get());
      MinecraftForge.EVENT_BUS.post(breakEvent);

      if (!breakEvent.isCanceled())*/
      EntityPlayer player =
          this.owner instanceof TileBuildCraft
              ? ((TileBuildCraft) this.owner).getOwnerFake()
              : CoreProxy.proxy.getBuildCraftPlayer((WorldServer) world).get();
      if (!FakePlayerUtils.cantBreak(player, x, y, z))
      // TODO gamerforEA code end
      {
        List<ItemStack> stacks = BlockUtils.getItemStackFromBlock((WorldServer) world, x, y, z);

        if (stacks != null) {
          for (ItemStack s : stacks) {
            if (s != null) {
              mineStack(s);
            }
          }
        }

        world.playAuxSFXAtEntity(null, 2001, x, y, z, Block.getIdFromBlock(block) + (meta << 12));

        Utils.preDestroyBlock(world, x, y, z);
        world.setBlockToAir(x, y, z);
      } else {
        hasFailed = true;
      }
    } else {
      world.destroyBlockInWorldPartially(
          minerId,
          x,
          y,
          z,
          MathUtils.clamp((int) Math.floor(energyAccepted * 10 / energyRequired), 0, 9));
    }
    return usedAmount;
  }
  /** Sets the navigator to move along x and y by X and Y. */
  public void setTarget(double x, double y) {
    if (!calibrator.isCalibrated()) return;
    MathUtils.set(target, x, y);
    MathUtils.set(offtarget, target);
    calibrator.getRequiredSteps(target);
    targetSet = true;
    steps.x = (steps.x > 0) ? (int) (steps.x + 0.5) : (int) (steps.x - 0.5); // round no. of steps
    steps.y = (steps.y > 0) ? (int) (steps.y + 0.5) : (int) (steps.y - 0.5);

    calibrator.adjustBacklash(steps);
  }
  // **************************************************************************
  // Test methods
  // **************************************************************************
  public void test1D() {

    double[] buff = new double[100];
    for (int i = 0; i < 100; i++) {
      buff[i] = Math.random(); // range between 0 and 1
    }
    ArrayUtils.normalize(buff, -1, 1, 0, 100); // Buffer, Min val, Max,
    // start index, length

    assertTrue(MathUtils.isApproximatelyEqual(-1, ArrayUtils.min(buff)));
    assertTrue(MathUtils.isApproximatelyEqual(1, ArrayUtils.max(buff)));
  }
Exemple #13
0
  /**
   * Creates a unit vector from the given vector
   *
   * @param vec any vector n-dimensional
   * @return unit vector (n-dimensional) with norm = 1
   */
  public static double[] UnitVector(double[] vec) {
    int n = vec.length;
    double[] unitVect = new double[n];

    double normVec = MathUtils.norm(vec);

    unitVect = MathUtils.scale(vec, 1.0 / normVec);

    // System.out.println("Norm:" + MathUtils.norm(unitVect));

    return unitVect;
  } // UnitVector
 @Override
 public void safeRun() {
   taskPendingStats.registerSuccessfulEvent(initNanos, TimeUnit.NANOSECONDS);
   long startNanos = MathUtils.nowInNano();
   this.runnable.safeRun();
   long elapsedMicroSec = MathUtils.elapsedMicroSec(startNanos);
   taskExecutionStats.registerSuccessfulEvent(elapsedMicroSec, TimeUnit.MICROSECONDS);
   if (elapsedMicroSec >= warnTimeMicroSec) {
     logger.warn(
         "Runnable {}:{} took too long {} micros to execute.",
         new Object[] {runnable, runnable.getClass(), elapsedMicroSec});
   }
 }
  @Test
  public void dblReturnsExpectedResult() {
    for (int i = 0; i < 1000; i++) {
      // Arrange:
      final GroupElement g = MathUtils.getRandomGroupElement();

      // Act:
      final GroupElement h1 = g.dbl();
      final GroupElement h2 = MathUtils.doubleGroupElement(g);

      // Assert:
      Assert.assertThat(h2, IsEqual.equalTo(h1));
    }
  }
  @Test
  public void dblPrecomputedTableContainsExpectedGroupElements() {
    // Arrange:
    GroupElement g = ed25519.getB();
    GroupElement h = MathUtils.addGroupElements(g, g);

    // Act + Assert:
    for (int i = 0; i < 8; i++) {
      Assert.assertThat(
          MathUtils.toRepresentation(g, GroupElement.Representation.PRECOMP),
          IsEqual.equalTo(ed25519.getB().dblPrecmp[i]));
      g = MathUtils.addGroupElements(g, h);
    }
  }
  @Test
  public void subReturnsExpectedResult() {
    for (int i = 0; i < 1000; i++) {
      // Arrange:
      final GroupElement g1 = MathUtils.getRandomGroupElement();
      final GroupElement g2 = MathUtils.getRandomGroupElement();

      // Act:
      final GroupElement h1 = g1.sub(g2.toCached());
      final GroupElement h2 = MathUtils.addGroupElements(g1, MathUtils.negateGroupElement(g2));

      // Assert:
      Assert.assertThat(h2, IsEqual.equalTo(h1));
    }
  }
  @Test
  public void constructorUsingByteArrayReturnsExpectedResult() {
    for (int i = 0; i < 100; i++) {
      // Arrange:
      final GroupElement g = MathUtils.getRandomGroupElement();
      final byte[] bytes = g.toByteArray();

      // Act:
      final GroupElement h1 = new GroupElement(curve, bytes);
      final GroupElement h2 = MathUtils.toGroupElement(bytes);

      // Assert:
      Assert.assertThat(h1, IsEqual.equalTo(h2));
    }
  }
  // This test is slow (~6s) due to math utils using an inferior algorithm to calculate the result.
  @Test
  public void scalarMultiplyBasePointReturnsExpectedResult() {
    for (int i = 0; i < 100; i++) {
      // Arrange:
      final GroupElement basePoint = ed25519.getB();
      final FieldElement f = MathUtils.getRandomFieldElement();

      // Act:
      final GroupElement g = basePoint.scalarMultiply(f.toByteArray());
      final GroupElement h = MathUtils.scalarMultiplyGroupElement(basePoint, f);

      // Assert:
      Assert.assertThat(g, IsEqual.equalTo(h));
    }
  }
  @Test
  public void hashCodesAreEqualForEquivalentObjects() {
    // Arrange:
    final GroupElement g1 = MathUtils.getRandomGroupElement();
    final GroupElement g2 = MathUtils.toRepresentation(g1, GroupElement.Representation.P2);
    final GroupElement g3 = MathUtils.toRepresentation(g1, GroupElement.Representation.P1P1);
    final GroupElement g4 = MathUtils.getRandomGroupElement();

    // Assert
    Assert.assertThat(g2.hashCode(), IsEqual.equalTo(g1.hashCode()));
    Assert.assertThat(g3.hashCode(), IsEqual.equalTo(g1.hashCode()));
    Assert.assertThat(g1.hashCode(), IsNot.not(IsEqual.equalTo(g4.hashCode())));
    Assert.assertThat(g2.hashCode(), IsNot.not(IsEqual.equalTo(g4.hashCode())));
    Assert.assertThat(g3.hashCode(), IsNot.not(IsEqual.equalTo(g4.hashCode())));
  }
  /**
   * 将以 byte 为单位的文件大小转换为一个可读性更好的文件大小,最终结果精确到一位小数。
   *
   * @param size 以 byte 为单位的文件大小
   * @return 更具可读性的文件大小(包括单位:GB、MB、KB、B),例如:102 B、1.5 KB、23.8 MB、34.2 GB
   */
  public static String byteCountToDisplaySize(long size) {
    String displaySize;

    if (size / ONE_GB > 0) {
      displaySize = MathUtils.div(size * 1.0, ONE_GB, 1) + " GB";
    } else if (size / ONE_MB > 0) {
      displaySize = MathUtils.div(size * 1.0, ONE_MB, 1) + " MB";
    } else if (size / ONE_KB > 0) {
      displaySize = MathUtils.div(size * 1.0, ONE_KB, 1) + " KB";
    } else {
      displaySize = String.valueOf(size) + " B";
    }

    return displaySize;
  }
  public void test2D() {

    double[][] buff = new double[4][4];

    for (int j = 0; j < 4; j++) {

      for (int i = 0; i < 4; i++) {
        buff[j][i] = Math.random(); // range between 0 and 1
      }
    }

    ArrayUtils.normalize(buff, -10, 10, 1, 2, 1, 2);
    assertTrue(MathUtils.isApproximatelyEqual(-10, ArrayUtils.min(buff)));
    assertTrue(MathUtils.isApproximatelyEqual(10, ArrayUtils.max(buff)));
  }
  public void test3D() {

    double[][][] buff = new double[8][4][2];
    for (int k = 0; k < 8; k++) {
      for (int j = 0; j < 4; j++) {
        for (int i = 0; i < 2; i++) buff[k][j][i] = Math.random(); // range between 0 and 1
      }
    }
    ArrayUtils.normalize(buff, -1, 1); // Buffer, Min val, Max,
    // start index, length

    // ArrayUtils.print(buff);

    assertTrue(MathUtils.isApproximatelyEqual(-1, ArrayUtils.min(buff)));
    assertTrue(MathUtils.isApproximatelyEqual(1, ArrayUtils.max(buff)));
  }
Exemple #24
0
 public void addAll(T[] array, int start, int count) {
   T[] items = this.items;
   int sizeNeeded = size + count;
   if (sizeNeeded > items.length) items = resize(MathUtils.max(8, (int) (sizeNeeded * 1.75f)));
   System.arraycopy(array, start, items, size, count);
   size += count;
 }
Exemple #25
0
 protected T[] resize(int newSize) {
   T[] items = this.items;
   T[] newItems = (T[]) new Object[newSize];
   System.arraycopy(items, 0, newItems, 0, MathUtils.min(size, newItems.length));
   this.items = newItems;
   return newItems;
 }
Exemple #26
0
  @Override
  public boolean evaluate(InvocationContext context) {
    Object left = ((AbstractExpression) jjtGetChild(0)).value(context);
    Object right = ((AbstractExpression) jjtGetChild(1)).value(context);
    if (left instanceof Number && right instanceof Number) {
      return MathUtils.compare((Number) left, (Number) right) != 0;
    }

    // 都不为null,一个是另一个的子类,则使用equals操作
    if (left != null
        && right != null
        && (left.getClass().isAssignableFrom(right.getClass())
            || right.getClass().isAssignableFrom(left.getClass()))) {
      return !left.equals(right);
    }

    if (left == null && right == null) { // 都为null
      return false;
    } else if (left == null || right == null) { // 一个为null,一个不为null
      return true;
    } else { // 都不为null
      left = left.toString();
      right = right.toString();
      return !left.equals(right);
    }
  }
  private long getThreadID(Object orderingKey) {
    // skip hashcode generation in this special case
    if (threadIds.length == 1) {
      return threadIds[0];
    }

    return threadIds[MathUtils.signSafeMod(orderingKey.hashCode(), threadIds.length)];
  }
Exemple #28
0
  /**
   * Converts this vector into a unit vector by dividing it internally by its length. If the length
   * is 0, (ie, if the vector is 0, 0, 0, 0) then no action is taken.
   *
   * @return this vector for chaining
   */
  public Vector4 normalizeLocal() {
    final double lengthSq = lengthSquared();
    if (Math.abs(lengthSq) > MathUtils.EPSILON) {
      return multiplyLocal(MathUtils.inverseSqrt(lengthSq));
    }

    return this;
  }
  @Test
  public void toByteArrayReturnsExpectedResult() {
    for (int i = 0; i < 100; i++) {
      // Arrange:
      final GroupElement g = MathUtils.getRandomGroupElement();

      // Act:
      final byte[] gBytes = g.toByteArray();
      final byte[] bytes = MathUtils.toByteArray(MathUtils.toBigInteger(g.getY()));
      if (MathUtils.toBigInteger(g.getX()).mod(new BigInteger("2")).equals(BigInteger.ONE)) {
        bytes[31] |= 0x80;
      }

      // Assert:
      Assert.assertThat(Arrays.equals(gBytes, bytes), IsEqual.equalTo(true));
    }
  }
  ExecutorService chooseThread(Object orderingKey) {
    // skip hashcode generation in this special case
    if (threads.length == 1) {
      return threads[0];
    }

    return threads[MathUtils.signSafeMod(orderingKey.hashCode(), threads.length)];
  }