Java Code Examples for org.apache.commons.math3.util.Precision#equals()

The following examples show how to use org.apache.commons.math3.util.Precision#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EigenDecomposition.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks whether the decomposed matrix is non-singular.
 *
 * @return true if the decomposed matrix is non-singular.
 */
public boolean isNonSingular() {
    double largestEigenvalueNorm = 0.0;
    // Looping over all values (in case they are not sorted in decreasing
    // order of their norm).
    for (int i = 0; i < realEigenvalues.length; ++i) {
        largestEigenvalueNorm = FastMath.max(largestEigenvalueNorm, eigenvalueNorm(i));
    }
    // Corner case: zero matrix, all exactly 0 eigenvalues
    if (largestEigenvalueNorm == 0.0) {
        return false;
    }
    for (int i = 0; i < realEigenvalues.length; ++i) {
        // Looking for eigenvalues that are 0, where we consider anything much much smaller
        // than the largest eigenvalue to be effectively 0.
        if (Precision.equals(eigenvalueNorm(i) / largestEigenvalueNorm, 0, EPSILON)) {
            return false;
        }
    }
    return true;
}
 
Example 2
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 3
Source File: jMutRepair_0042_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 4
Source File: jMutRepair_0049_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 5
Source File: Arja_0056_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 6
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 * @throws NoFeasibleSolutionException if there is no feasible solution?
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 7
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * 
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException   if the maximal iteration count has been
 *                                     exceeded
 * @throws UnboundedSolutionException  if the model is found not to have a
 *                                     bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
		throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

	// make sure we're in Phase 1
	if (tableau.getNumArtificialVariables() == 0) {
		return;
	}

	while (!tableau.isOptimal()) {
		doIteration(tableau);
	}

	// if W is not zero then we have no feasible solution
	if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
		throw new NoFeasibleSolutionException();
	}
}
 
Example 8
Source File: Arja_00167_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 9
Source File: JGenProg2017_0060_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 10
Source File: cardumen_one_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 11
Source File: JGenProg2017_0090_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 * @param tableau simple tableau for the problem
 * @throws MaxCountExceededException if the maximal iteration count has been exceeded
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution
 * @throws NoFeasibleSolutionException if there is no feasible solution
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example 12
Source File: TestUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of x.
 *
 * @param msg  message to return with failure
 * @param values double array to search
 * @param x value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, double[] values,
        double x, double epsilon) {
    for (double value : values) {
        if (Precision.equals(value, x, epsilon)) {
            return;
        }
    }
    Assert.fail(msg + " Unable to find " + x);
}
 
Example 13
Source File: TestUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of x.
 *
 * @param msg  message to return with failure
 * @param values double array to search
 * @param x value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, double[] values,
        double x, double epsilon) {
    for (double value : values) {
        if (Precision.equals(value, x, epsilon)) {
            return;
        }
    }
    Assert.fail(msg + " Unable to find " + x);
}
 
Example 14
Source File: Elixir_0024_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Checks whether the given column is basic.
 * @param col index of the column to check
 * @return the row that the variable is basic in.  null if the column is not basic
 */
protected Integer getBasicRow(final int col) {
    Integer row = null;
    for (int i = 0; i < getHeight(); i++) {
        final double entry = getEntry(i, col);
        if (Precision.equals(entry, 1d, maxUlps) && (row == null)) {
            row = i;
        } else if (!Precision.equals(entry, 0d, maxUlps)) {
            return null;
        }
    }
    return row;
}
 
Example 15
Source File: SparseGradient.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test for the equality of two sparse gradients.
 * <p>
 * Sparse gradients are considered equal if they have the same value
 * and the same derivatives.
 * </p>
 * @param other Object to test for equality to this
 * @return true if two sparse gradients are equal
 */
@Override
public boolean equals(Object other) {

    if (this == other) {
        return true;
    }

    if (other instanceof SparseGradient) {
        final SparseGradient rhs = (SparseGradient)other;
        if (!Precision.equals(value, rhs.value, 1)) {
            return false;
        }
        if (derivatives.size() != rhs.derivatives.size()) {
            return false;
        }
        for (final Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
            if (!rhs.derivatives.containsKey(entry.getKey())) {
                return false;
            }
            if (!Precision.equals(entry.getValue(), rhs.derivatives.get(entry.getKey()), 1)) {
                return false;
            }
        }
        return true;
    }

    return false;

}
 
Example 16
Source File: SimplexSolverTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon) {
    double[] vals = solution.getPoint();
    for (LinearConstraint c : constraints) {
        double[] coeffs = c.getCoefficients().toArray();
        double result = 0.0d;
        for (int i = 0; i < vals.length; i++) {
            result += vals[i] * coeffs[i];
        }
        
        switch (c.getRelationship()) {
        case EQ:
            if (!Precision.equals(result, c.getValue(), epsilon)) {
                return false;
            }
            break;
            
        case GEQ:
            if (Precision.compareTo(result, c.getValue(), epsilon) < 0) {
                return false;
            }
            break;
            
        case LEQ:
            if (Precision.compareTo(result, c.getValue(), epsilon) > 0) {
                return false;
            }
            break;
        }
    }
    
    return true;
}
 
Example 17
Source File: SimplexTableau.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks whether the given column is basic.
 * @param col index of the column to check
 * @return the row that the variable is basic in.  null if the column is not basic
 */
protected Integer getBasicRow(final int col) {
    Integer row = null;
    for (int i = 0; i < getHeight(); i++) {
        final double entry = getEntry(i, col);
        if (Precision.equals(entry, 1d, maxUlps) && (row == null)) {
            row = i;
        } else if (!Precision.equals(entry, 0d, maxUlps)) {
            return null;
        }
    }
    return row;
}
 
Example 18
Source File: RandomForestClassificationExample.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Run example.
 */
public static void main(String[] args) throws IOException {
    System.out.println();
    System.out.println(">>> Random Forest multi-class classification algorithm over cached dataset usage example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Ignite grid started.");

        IgniteCache<Integer, Vector> dataCache = null;
        try {
            dataCache = new SandboxMLCache(ignite).fillCacheWith(MLSandboxDatasets.WINE_RECOGNITION);

            AtomicInteger idx = new AtomicInteger(0);
            RandomForestClassifierTrainer classifier = new RandomForestClassifierTrainer(
                IntStream.range(0, dataCache.get(1).size() - 1).mapToObj(
                    x -> new FeatureMeta("", idx.getAndIncrement(), false)).collect(Collectors.toList())
            ).withAmountOfTrees(101)
                .withFeaturesCountSelectionStrgy(FeaturesCountSelectionStrategies.ONE_THIRD)
                .withMaxDepth(4)
                .withMinImpurityDelta(0.)
                .withSubSampleSize(0.3)
                .withSeed(0);

            System.out.println(">>> Configured trainer: " + classifier.getClass().getSimpleName());

            Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>()
                .labeled(Vectorizer.LabelCoordinate.FIRST);
            ModelsComposition randomForestMdl = classifier.fit(ignite, dataCache, vectorizer);

            System.out.println(">>> Trained model: " + randomForestMdl.toString(true));

            int amountOfErrors = 0;
            int totalAmount = 0;

            try (QueryCursor<Cache.Entry<Integer, Vector>> observations = dataCache.query(new ScanQuery<>())) {
                for (Cache.Entry<Integer, Vector> observation : observations) {
                    Vector val = observation.getValue();
                    Vector inputs = val.copyOfRange(1, val.size());
                    double groundTruth = val.get(0);

                    double prediction = randomForestMdl.predict(inputs);

                    totalAmount++;
                    if (!Precision.equals(groundTruth, prediction, Precision.EPSILON))
                        amountOfErrors++;
                }

                System.out.println("\n>>> Evaluated model on " + totalAmount + " data points.");

                System.out.println("\n>>> Absolute amount of errors " + amountOfErrors);
                System.out.println("\n>>> Accuracy " + (1 - amountOfErrors / (double)totalAmount));
                System.out.println(">>> Random Forest multi-class classification algorithm over cached dataset usage example completed.");
            }

        }
        finally {
            if (dataCache != null)
                dataCache.destroy();
        }
    }
    finally {
        System.out.flush();
    }
}
 
Example 19
Source File: ANNClassificationExample.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> ANN multi-class classification algorithm over cached dataset usage example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Ignite grid started.");

        IgniteCache<Integer, double[]> dataCache = null;
        try {
            dataCache = getTestCache(ignite);

            ANNClassificationTrainer trainer = new ANNClassificationTrainer()
                .withDistance(new ManhattanDistance())
                .withK(50)
                .withMaxIterations(1000)
                .withEpsilon(1e-2);

            long startTrainingTime = System.currentTimeMillis();

            NNClassificationModel knnMdl = trainer.fit(
                ignite,
                dataCache,
                new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST)
            ).withK(5)
                .withDistanceMeasure(new EuclideanDistance())
                .withWeighted(true);

            long endTrainingTime = System.currentTimeMillis();

            System.out.println(">>> ---------------------------------");
            System.out.println(">>> | Prediction\t| Ground Truth\t|");
            System.out.println(">>> ---------------------------------");

            int amountOfErrors = 0;
            int totalAmount = 0;

            long totalPredictionTime = 0L;

            try (QueryCursor<Cache.Entry<Integer, double[]>> observations = dataCache.query(new ScanQuery<>())) {
                for (Cache.Entry<Integer, double[]> observation : observations) {
                    double[] val = observation.getValue();
                    double[] inputs = Arrays.copyOfRange(val, 1, val.length);
                    double groundTruth = val[0];

                    long startPredictionTime = System.currentTimeMillis();
                    double prediction = knnMdl.predict(new DenseVector(inputs));
                    long endPredictionTime = System.currentTimeMillis();

                    totalPredictionTime += (endPredictionTime - startPredictionTime);

                    totalAmount++;
                    if (!Precision.equals(groundTruth, prediction, Precision.EPSILON))
                        amountOfErrors++;

                    System.out.printf(">>> | %.4f\t\t| %.4f\t\t|\n", prediction, groundTruth);
                }

                System.out.println(">>> ---------------------------------");

                System.out.println("Training costs = " + (endTrainingTime - startTrainingTime));
                System.out.println("Prediction costs = " + totalPredictionTime);

                System.out.println("\n>>> Absolute amount of errors " + amountOfErrors);
                System.out.println("\n>>> Accuracy " + (1 - amountOfErrors / (double)totalAmount));
                System.out.println(totalAmount);

                System.out.println(">>> ANN multi-class classification algorithm over cached dataset usage example completed.");
            }
        }
        finally {
            dataCache.destroy();
        }
    }
    finally {
        System.out.flush();
    }
}
 
Example 20
Source File: DiagonalMatrix.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** Ensure a value is zero.
 * @param value value to check
 * @exception NumberIsTooLargeException if value is not zero
 */
private void ensureZero(final double value) throws NumberIsTooLargeException {
    if (!Precision.equals(0.0, value, 1)) {
        throw new NumberIsTooLargeException(FastMath.abs(value), 0, true);
    }
}