Example usage for java.lang Double POSITIVE_INFINITY

List of usage examples for java.lang Double POSITIVE_INFINITY

Introduction

In this page you can find the example usage for java.lang Double POSITIVE_INFINITY.

Prototype

double POSITIVE_INFINITY

To view the source code for java.lang Double POSITIVE_INFINITY.

Click Source Link

Document

A constant holding the positive infinity of type double .

Usage

From source file:com.genericworkflownodes.knime.config.writer.CTDConfigurationWriter.java

private void addDoubleParameterRestrictions(Parameter<?> p, StringBuffer restriction) {
    DoubleParameter dp = (DoubleParameter) p;
    boolean lbSet = Double.NEGATIVE_INFINITY != dp.getLowerBound().doubleValue();
    boolean ubSet = Double.POSITIVE_INFINITY != dp.getUpperBound().doubleValue();
    if (lbSet) {/*w  w  w. ja  v a2s  .co  m*/
        restriction.append(String.format(Locale.ENGLISH, "%f", dp.getLowerBound())
                .replaceAll(REMOVE_TRAILING_0_RE, "").replaceAll(REMOVE_TRAILING_DOT_RE, ""));
    }
    if (ubSet || lbSet) {
        restriction.append(':');
    }
    if (ubSet) {
        restriction.append(String.format(Locale.ENGLISH, "%f", dp.getUpperBound())
                .replaceAll(REMOVE_TRAILING_0_RE, "").replaceAll(REMOVE_TRAILING_DOT_RE, ""));
    }
}

From source file:mase.app.soccer.ProgSoccerAgent.java

private SoccerAgent closestInFront(double direction, double distance, double angle) {
    double min = Double.POSITIVE_INFINITY;
    SoccerAgent closest = null;//from ww  w . j a v a  2s.c o m
    for (SoccerAgent a : others) {
        double d = this.distanceTo(a);
        if (d < distance) {
            double agToOther = a.getLocation().subtract(getLocation()).angle();
            if (angleDifference(direction, agToOther) < angle) {
                if (d < min) {
                    min = d;
                    closest = a;
                }
            }
        }
    }
    return closest;
}

From source file:byps.test.TestSerializePrimitiveTypes.java

@Test
public void testSerializeDouble() throws BException {
    log.info("testSerializeDouble(");
    internalTestSerializeDouble(Double.NaN);
    internalTestSerializeDouble(Double.NEGATIVE_INFINITY);
    internalTestSerializeDouble(Double.POSITIVE_INFINITY);
    internalTestSerializeDouble(0.0);//from w ww . j av  a2 s  .  c o  m
    internalTestSerializeDouble(1.0);
    internalTestSerializeDouble(-1.0);
    internalTestSerializeDouble(1.0e7);
    internalTestSerializeDouble(1.0e-7);
    internalTestSerializeDouble(2.0E5);
    log.info(")testSerializeDouble");
}

From source file:Armadillo.Analytics.Base.Precision.java

/**
 * Rounds the given non-negative value to the "nearest" integer. Nearest is
 * determined by the rounding method specified. Rounding methods are defined
 * in {@link BigDecimal}./* ww w  .jav  a  2s .co  m*/
 *
 * @param unscaled Value to round.
 * @param sign Sign of the original, scaled value.
 * @param roundingMethod Rounding method, as defined in {@link BigDecimal}.
 * @return the rounded value.
 * @throws MathArithmeticException if an exact operation is required but result is not exact
 * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
 * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
 */
private static double roundUnscaled(double unscaled, double sign, int roundingMethod)
        throws MathArithmeticException, MathIllegalArgumentException {
    switch (roundingMethod) {
    case BigDecimal.ROUND_CEILING:
        if (sign == -1) {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        } else {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_DOWN:
        unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        break;
    case BigDecimal.ROUND_FLOOR:
        if (sign == -1) {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        } else {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_HALF_DOWN: {
        unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_HALF_EVEN: {
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else if (fraction < 0.5) {
            unscaled = FastMath.floor(unscaled);
        } else {
            // The following equality test is intentional and needed for rounding purposes
            if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math.floor(unscaled) / 2.0)) { // even
                unscaled = FastMath.floor(unscaled);
            } else { // odd
                unscaled = FastMath.ceil(unscaled);
            }
        }
        break;
    }
    case BigDecimal.ROUND_HALF_UP: {
        unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction >= 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_UNNECESSARY:
        if (unscaled != FastMath.floor(unscaled)) {
            throw new MathArithmeticException();
        }
        break;
    case BigDecimal.ROUND_UP:
        unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        break;
    default:
        throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD, roundingMethod,
                "ROUND_CEILING", BigDecimal.ROUND_CEILING, "ROUND_DOWN", BigDecimal.ROUND_DOWN, "ROUND_FLOOR",
                BigDecimal.ROUND_FLOOR, "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, "ROUND_HALF_EVEN",
                BigDecimal.ROUND_HALF_EVEN, "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, "ROUND_UNNECESSARY",
                BigDecimal.ROUND_UNNECESSARY, "ROUND_UP", BigDecimal.ROUND_UP);
    }
    return unscaled;
}

From source file:com.opengamma.analytics.financial.interestrate.future.method.BondFutureHullWhiteMethod.java

/**
 * Computes the future price curve sensitivity.
 * @param future The future security.//  w  w w  .ja  va  2 s .com
 * @param hwData The curve and Hull-White parameters.
 * @param nbPoint The number of point in the numerical cross estimation.
 * @return The curve sensitivity.
 */
public InterestRateCurveSensitivity priceCurveSensitivity(final BondFuture future,
        final HullWhiteOneFactorPiecewiseConstantDataBundle hwData, final int nbPoint) {
    Validate.notNull(future, "Future");
    Validate.notNull(hwData, "Hull-White data bundle");
    final int nbBond = future.getDeliveryBasket().length;
    final YieldAndDiscountCurve bndCurve = hwData
            .getCurve(future.getDeliveryBasket()[0].getDiscountingCurveName());
    final double expiry = future.getNoticeLastTime();
    final double delivery = future.getDeliveryLastTime();
    final double dfdelivery = bndCurve.getDiscountFactor(delivery);
    // Constructing non-homogeneous point series for the numerical estimations.
    final int nbPtWing = ((int) Math.floor(nbPoint / 20.)); // Number of point on each wing.
    final int nbPtCenter = nbPoint - 2 * nbPtWing;
    final double prob = 1.0 / (2.0 * nbPtCenter);
    final double xStart = NORMAL.getInverseCDF(prob);
    final double[] x = new double[nbPoint];
    for (int loopwing = 0; loopwing < nbPtWing; loopwing++) {
        x[loopwing] = xStart * (1.0 + (nbPtWing - loopwing) / 2.0);
        x[nbPoint - 1 - loopwing] = -xStart * (1.0 + (nbPtWing - loopwing) / 2.0);
    }
    for (int loopcent = 0; loopcent < nbPtCenter; loopcent++) {
        x[nbPtWing + loopcent] = xStart + loopcent * (-2.0 * xStart) / (nbPtCenter - 1);
    }
    // Figures for each bond
    final double[][] cfTime = new double[nbBond][];
    final double[][] df = new double[nbBond][];
    final double[][] alpha = new double[nbBond][];
    final double[][] beta = new double[nbBond][];
    final double[][] cfaAdjusted = new double[nbBond][];
    final double[] e = new double[nbBond];
    final double[][] pv = new double[nbPoint][nbBond];
    final AnnuityPaymentFixed[] cf = new AnnuityPaymentFixed[nbBond];
    for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) {
        cf[loopbnd] = future.getDeliveryBasket()[loopbnd].accept(CFEC, hwData);
        final int nbCf = cf[loopbnd].getNumberOfPayments();
        cfTime[loopbnd] = new double[nbCf];
        df[loopbnd] = new double[nbCf];
        alpha[loopbnd] = new double[nbCf];
        beta[loopbnd] = new double[nbCf];
        cfaAdjusted[loopbnd] = new double[nbCf];
        for (int loopcf = 0; loopcf < nbCf; loopcf++) {
            cfTime[loopbnd][loopcf] = cf[loopbnd].getNthPayment(loopcf).getPaymentTime();
            df[loopbnd][loopcf] = bndCurve.getDiscountFactor(cfTime[loopbnd][loopcf]);
            alpha[loopbnd][loopcf] = MODEL.alpha(hwData.getHullWhiteParameter(), 0.0, expiry, delivery,
                    cfTime[loopbnd][loopcf]);
            beta[loopbnd][loopcf] = MODEL.futuresConvexityFactor(hwData.getHullWhiteParameter(), expiry,
                    cfTime[loopbnd][loopcf], delivery);
            cfaAdjusted[loopbnd][loopcf] = df[loopbnd][loopcf] / dfdelivery * beta[loopbnd][loopcf]
                    * cf[loopbnd].getNthPayment(loopcf).getAmount() / future.getConversionFactor()[loopbnd];
            for (int looppt = 0; looppt < nbPoint; looppt++) {
                pv[looppt][loopbnd] += cfaAdjusted[loopbnd][loopcf]
                        * Math.exp(-alpha[loopbnd][loopcf] * alpha[loopbnd][loopcf] / 2.0
                                - alpha[loopbnd][loopcf] * x[looppt]);
            }
        }
        e[loopbnd] = future.getDeliveryBasket()[loopbnd].getAccruedInterest()
                / future.getConversionFactor()[loopbnd];
        for (int looppt = 0; looppt < nbPoint; looppt++) {
            pv[looppt][loopbnd] -= e[loopbnd];
        }
    }
    // Minimum: create a list of index of the CTD in each interval and a first estimate of the crossing point (x[]).
    final double[] pvMin = new double[nbPoint];
    final int[] indMin = new int[nbPoint];
    for (int looppt = 0; looppt < nbPoint; looppt++) {
        pvMin[looppt] = Double.POSITIVE_INFINITY;
        for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) {
            if (pv[looppt][loopbnd] < pvMin[looppt]) {
                pvMin[looppt] = pv[looppt][loopbnd];
                indMin[looppt] = loopbnd;
            }
        }
    }
    final ArrayList<Double> refx = new ArrayList<>();
    final ArrayList<Integer> ctd = new ArrayList<>();
    int lastInd = indMin[0];
    ctd.add(indMin[0]);
    for (int looppt = 1; looppt < nbPoint; looppt++) {
        if (indMin[looppt] != lastInd) {
            ctd.add(indMin[looppt]);
            lastInd = indMin[looppt];
            refx.add(x[looppt]);
        }
    }
    // Sum on each interval
    final int nbInt = ctd.size();
    final double[] kappa = new double[nbInt - 1];
    //    double price = 0.0;
    if (nbInt != 1) {
        // The intersections
        final BracketRoot bracketer = new BracketRoot();
        final double accuracy = 1.0E-8;
        final RidderSingleRootFinder rootFinder = new RidderSingleRootFinder(accuracy);
        for (int loopint = 1; loopint < nbInt; loopint++) {
            final BondDifference cross = new BondDifference(cfaAdjusted[ctd.get(loopint - 1)],
                    alpha[ctd.get(loopint - 1)], e[ctd.get(loopint - 1)], cfaAdjusted[ctd.get(loopint)],
                    alpha[ctd.get(loopint)], e[ctd.get(loopint)]);
            final double[] range = bracketer.getBracketedPoints(cross, refx.get(loopint - 1) - 0.01,
                    refx.get(loopint - 1) + 0.01);
            kappa[loopint - 1] = rootFinder.getRoot(cross, range[0], range[1]);
        }
    }

    // === Backward Sweep ===
    final double priceBar = 1.0;
    final double[][] cfaAdjustedBar = new double[nbBond][];
    final double[][] dfBar = new double[nbBond][];
    for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) {
        final int nbCf = cf[loopbnd].getNumberOfPayments();
        cfaAdjustedBar[loopbnd] = new double[nbCf];
        dfBar[loopbnd] = new double[nbCf];
    }
    double dfdeliveryBar = 0.0;
    final Map<String, List<DoublesPair>> resultMap = new HashMap<>();
    final List<DoublesPair> listCredit = new ArrayList<>();
    if (nbInt == 1) {
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(0)].length; loopcf++) {
            cfaAdjustedBar[ctd.get(0)][loopcf] = priceBar;
            dfBar[ctd.get(0)][loopcf] = beta[ctd.get(0)][loopcf] / dfdelivery
                    * cf[ctd.get(0)].getNthPayment(loopcf).getAmount()
                    / future.getConversionFactor()[ctd.get(0)] * cfaAdjustedBar[ctd.get(0)][loopcf];
            listCredit.add(new DoublesPair(cfTime[ctd.get(0)][loopcf],
                    -cfTime[ctd.get(0)][loopcf] * df[ctd.get(0)][loopcf] * dfBar[ctd.get(0)][loopcf]));
            dfdeliveryBar += -cfaAdjusted[ctd.get(0)][loopcf] / dfdelivery * cfaAdjustedBar[ctd.get(0)][loopcf];
        }
        listCredit.add(new DoublesPair(delivery, -delivery * dfdelivery * dfdeliveryBar));
    } else {
        // From -infinity to first cross.
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(0)].length; loopcf++) {
            cfaAdjustedBar[ctd.get(0)][loopcf] = NORMAL.getCDF(kappa[0] + alpha[ctd.get(0)][loopcf]) * priceBar;
        }
        // Between cross
        for (int loopint = 1; loopint < nbInt - 1; loopint++) {
            for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(loopint)].length; loopcf++) {
                cfaAdjustedBar[ctd.get(
                        loopint)][loopcf] = (NORMAL.getCDF(kappa[loopint] + alpha[ctd.get(loopint)][loopcf])
                                - NORMAL.getCDF(kappa[loopint - 1] + alpha[ctd.get(loopint)][loopcf]))
                                * priceBar;
            }
        }
        // From last cross to +infinity
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(nbInt - 1)].length; loopcf++) {
            cfaAdjustedBar[ctd.get(nbInt - 1)][loopcf] = (1.0
                    - NORMAL.getCDF(kappa[nbInt - 2] + alpha[ctd.get(nbInt - 1)][loopcf])) * priceBar;
        }
        for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) { // Could be reduced to only the ctd intervals.
            for (int loopcf = 0; loopcf < cfaAdjusted[loopbnd].length; loopcf++) {
                dfBar[loopbnd][loopcf] = beta[loopbnd][loopcf] / dfdelivery
                        * cf[loopbnd].getNthPayment(loopcf).getAmount() / future.getConversionFactor()[loopbnd]
                        * cfaAdjustedBar[loopbnd][loopcf];
                listCredit.add(new DoublesPair(cfTime[loopbnd][loopcf],
                        -cfTime[loopbnd][loopcf] * df[loopbnd][loopcf] * dfBar[loopbnd][loopcf]));
                dfdeliveryBar += -cfaAdjusted[loopbnd][loopcf] / dfdelivery * cfaAdjustedBar[loopbnd][loopcf];
            }
        }
        listCredit.add(new DoublesPair(delivery, -delivery * dfdelivery * dfdeliveryBar));
    }
    resultMap.put(future.getDeliveryBasket()[0].getDiscountingCurveName(), listCredit);
    final InterestRateCurveSensitivity result = new InterestRateCurveSensitivity(resultMap);
    return result;
}

From source file:io.github.karols.hocr4j.Page.java

@Nullable
private Line findLineMinimizingImpl(@Nonnull Function<Line, Double> scoreFunction, @Nullable Bounded header,
        boolean slightlyBelow) {
    Line result = null;/*w  w w.  j a v a  2 s  .c  o  m*/
    double minScore = Double.POSITIVE_INFINITY;
    for (Area a : areas) {
        for (Paragraph p : a) {
            for (Line l : p) {
                Double thisScore = scoreFunction.apply(l);
                if (thisScore == null || thisScore < 0) {
                    continue;
                }
                if (header != null) {
                    thisScore += 0.1;
                    double multiplier = header.getBounds().distance(l.bounds) + bounds.getHeight() / 10.0;
                    multiplier = Math.sqrt(multiplier);
                    multiplier = Math.sqrt(multiplier);
                    thisScore *= multiplier;
                    if (slightlyBelow && header.getBounds().isBelow(l.bounds)) {
                        thisScore *= 2;
                    }
                }
                if (thisScore < minScore) {
                    result = l;
                    minScore = thisScore;
                }
            }
        }
    }
    return result;
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

private static String toXmlString(double value) {
    if (Double.isNaN(value)) {
        return "NaN";
    } else if (value == Double.POSITIVE_INFINITY) {
        return "INF";
    } else if (value == Double.NEGATIVE_INFINITY) {
        return "-INF";
    } else {/*from   w  w  w.j a  va  2  s .  co m*/
        return Double.toString(value);
    }
}

From source file:it.units.malelab.ege.util.Utils.java

public static <T> Set<T> maximallySparseSubset(Map<T, MultiObjectiveFitness<Double>> points, int n) {
    Set<T> remainingPoints = new LinkedHashSet<>(points.keySet());
    Set<T> selectedPoints = new LinkedHashSet<>();
    Distance<MultiObjectiveFitness<Double>> d = new Distance<MultiObjectiveFitness<Double>>() {
        @Override/*ww  w.  ja v  a2 s.c  om*/
        public double d(MultiObjectiveFitness<Double> mof1, MultiObjectiveFitness<Double> mof2) {
            double d = 0;
            for (int i = 0; i < Math.min(mof1.getValue().length, mof2.getValue().length); i++) {
                d = d + Math.pow(mof1.getValue()[i] - mof2.getValue()[i], 2d);
            }
            return Math.sqrt(d);
        }
    };
    while (!remainingPoints.isEmpty() && (selectedPoints.size() < n)) {
        T selected = remainingPoints.iterator().next();
        ;
        if (!selectedPoints.isEmpty()) {
            //add point with max distance from closest point
            double maxMinD = Double.NEGATIVE_INFINITY;
            for (T t : remainingPoints) {
                double minD = Double.POSITIVE_INFINITY;
                for (T otherT : selectedPoints) {
                    minD = Math.min(minD, d.d(points.get(t), points.get(otherT)));
                }
                if (minD > maxMinD) {
                    maxMinD = minD;
                    selected = t;
                }
            }
            //sort
        }
        remainingPoints.remove(selected);
        selectedPoints.add(selected);
    }
    return selectedPoints;
}

From source file:gov.nasa.jpf.constraints.solvers.cw.CWSolver.java

private Result solveWithAdaptiveVariableSearch(Expression<Boolean> linearConstraint, Valuation linearSolution,
        Expression<Boolean> nonlinearConstraint, Valuation result) {

    // Partially based on the paper "Yet Another Local Search Method for Constraint Solving"
    // by Philippe Codognet and Daniel Diaz, 2001.

    // NOTE: End-of-line comments give the variable names and line numbers
    //       used in Algorithms 1 and 2 of the paper.

    // Interpret every variable in the path condition as a dimension
    // in a real-valued vector space.
    Set<Variable<?>> vars = union(ExpressionUtil.freeVariables(linearConstraint),
            ExpressionUtil.freeVariables(nonlinearConstraint));
    RealVectorSpace vectorSpace = RealVectorSpace.forDimensions(vars);
    int numberOfVariables = vectorSpace.dimensions().size();

    RealVector p = makeVectorFromSolutions(vectorSpace, linearSolution); // Alg. 1: \alpha, line 4

    printDebug(CWSolver.class, "Linear PC: ", linearConstraint);
    printDebug(CWSolver.class, "Linear PC solution: ", p);
    printDebug(CWSolver.class, "Solving non-linear PC\n", nonlinearConstraint);

    List<Expression<Boolean>> nonLinearConstraintsLst = ExpressionClassifier
            .splitToConjuncts(nonlinearConstraint);

    // Initialize lookup tables and local variables
    Map<Expression<Boolean>, BitSet> variableIndicesByConstraint = new IdentityHashMap<>(
            nonLinearConstraintsLst.size());
    @SuppressWarnings("unchecked")
    List<Expression<Boolean>>[] constraintsByVariableIndex = new List[numberOfVariables];
    populateLookupTables(vectorSpace, nonLinearConstraintsLst, constraintsByVariableIndex,
            variableIndicesByConstraint);

    double[] errorByVariables = new double[numberOfVariables]; // Alg. 1: \epsilon
    int[] tabuVariables = new int[numberOfVariables]; // Alg. 1: \tau

    int iterationCount = 1; // i
    int iterationLimit = nonLinearConstraintsLst.size() * ITERATIONS_PER_CONSTRAINT; // Alg. 1: I

    //iterate as long as non linear constraint is not satisfied
    while (!nonlinearConstraint.evaluate(p.convertToJconstraintsValuation())) { // Alg. 1: line 7
        if (iterationCount > iterationLimit) { // Alg. 1: line 8
            printDebug(CWSolver.class, "Could not find solution within ", iterationLimit, " iterations");
            return Result.DONT_KNOW;
        }//from w  w w  .  ja  v a 2 s  . c o  m
        ++iterationCount; // Alg. 1: line 9

        // Compute errors
        double errorAtP = 0.0; // Alg. 1: e_\alpha
        Arrays.fill(errorByVariables, 0.0); // Alg. 1: line 14
        for (Expression<Boolean> c : nonLinearConstraintsLst) { // Alg. 1: lines 15--20
            if (c instanceof PropositionalCompound) {
                System.out.println("propositional compound. Skipping");
                continue;
            }

            //TODO: fix the list; it must be composed of NumericBooleanExpressions (stronger type)
            if (!(c instanceof NumericBooleanExpression))
                throw new IllegalStateException("constraint must be " + NumericBooleanExpression.class.getName()
                        + " and not of type " + c.getClass().getName());

            NumericBooleanExpression nc = (NumericBooleanExpression) c;

            double e = computeError(nc, p.convertToJconstraintsValuation());
            errorAtP += e;
            incrementElements(errorByVariables, variableIndicesByConstraint.get(c), e);
        }
        printDebug(CWSolver.class, "p = ", p, " -> error ", errorAtP);

        // Try to find a better solution by modifying the "worst" non-tabu variable
        int wiggleVarIndex = indexOfMaxIgnoringTabu(errorByVariables, tabuVariables);
        if (wiggleVarIndex == -1) { // All variables might be tabu,  Alg. 1: lines 10--13
            for (int i = 0; i < tabuVariables.length; ++i) {
                p = makeRandomNeighborInPolytope(p, linearConstraint, vectorSpace.dimensions().get(i));
                if (p == null) { //no point could be found, so dont_know?
                    return Result.DONT_KNOW;
                }
                tabuVariables[i] = 0;
            }
            printDebug(CWSolver.class, "All variables are tabu.  Took random step to ", p);
            continue;
        }
        Variable<?> wiggleVar = vectorSpace.dimensions().get(wiggleVarIndex); // Alg. 1: x, line 21
        printDebug(CWSolver.class, "Wiggling ", wiggleVar);

        // Find best neighbor (Algorithm 3)

        double minError = Double.POSITIVE_INFINITY; // Alg. 3: e_\mu
        RealVector minNeighbor = null;
        for (int i = 0; i < NEIGHBORS_GENERATED_PER_ITERATION; ++i) {
            RealVector q = makeRandomNeighborInPolytope(p, linearConstraint, wiggleVar); // Alg. 3: \beta
            RealVector r = null; // Alg. 3: \gamma

            if (q == null) { // No random neighbor could be found
                break;
            }

            double errorAtQ = computeError(nonLinearConstraintsLst, q.convertToJconstraintsValuation()); // Alg. 3: e_\beta, line 7
            double errorAtR = Double.POSITIVE_INFINITY; // Alg. 3: e_\gamma

            if (ENABLE_BISECTION && constraintsByVariableIndex[wiggleVarIndex] != null) { // Alg. 3: line 5
                // Pick a random unsatisfied constraint
                List<Expression<Boolean>> constraintsForVar = new ArrayList<>(
                        constraintsByVariableIndex[wiggleVarIndex]);
                Collections.shuffle(constraintsForVar);
                Expression<Boolean> constraint = null;
                for (int k = 0; k < constraintsForVar.size(); ++k) {
                    constraint = constraintsForVar.get(k);

                    boolean sat = constraint.evaluate(p.convertToJconstraintsValuation());
                    if (!sat) {
                        break;
                    }
                }
                Number valueAtP = evaluateAndSubtractSides((NumericBooleanExpression) constraint,
                        p.convertToJconstraintsValuation());
                Number valueAtQ = evaluateAndSubtractSides((NumericBooleanExpression) constraint,
                        q.convertToJconstraintsValuation());
                r = linearlyEstimateZero(p, valueAtP, q, valueAtQ,
                        ((NumericBooleanExpression) constraint).getComparator()); // Alg. 3: line 6

                boolean sat = linearConstraint.evaluate(r.convertToJconstraintsValuation());

                if (sat) {
                    errorAtR = computeError(nonLinearConstraintsLst, r.convertToJconstraintsValuation());
                }
            }

            printDebug(CWSolver.class, "Random neighbors");
            printDebug(CWSolver.class, "    q = ", q, " -> error ", errorAtQ);
            printDebug(CWSolver.class, "    r = ", r, " -> error ", errorAtR);

            if (errorAtQ < minError) { // Alg. 3: lines 9--12
                minError = errorAtQ;
                minNeighbor = q;
            }
            if (errorAtR < minError) { // Alg. 3: lines 13--16
                minError = errorAtR;
                minNeighbor = r;
            }
        }

        if (ENABLE_SEEDING) {
            for (double seed : SEEDED_VALUES) {
                RealVector s = vectorSpace.makeVector(p).set(wiggleVar, seed).build();
                double errorAtS = computeError(nonLinearConstraintsLst, s.convertToJconstraintsValuation());

                boolean sat = linearConstraint.evaluate(s.convertToJconstraintsValuation());
                if (sat && errorAtS < minError) {
                    minError = errorAtS;
                    minNeighbor = s;
                }
            }
        }

        if (minError < errorAtP) { // Alg. 1: lines 23--27
            printDebug(CWSolver.class, "Found new neighbor");
            p = minNeighbor;
            decrementElements(tabuVariables);
        } else { // Alg 1: lines 27--29
            printDebug(CWSolver.class, "Could not find better neighbor");
            tabuVariables[wiggleVarIndex] = Math.max(
                    Math.round(TABU_ITERATIONS_PER_VARIABLE * vectorSpace.dimensions().size()),
                    MIN_TABU_ITERATIONS);
            printDebug(CWSolver.class, "Tabu ", Arrays.toString(tabuVariables));
        }
    }
    printDebug(CWSolver.class, "Found solution: ", p);
    for (Variable<?> v : vars) {
        double vectorVal = p.get(v);
        if (v.getType() instanceof IntegerType<?>) {
            result.setValue((Variable<Integer>) v, (int) vectorVal);
        } else if (v.getType() instanceof RealType<?>) {
            result.setValue((Variable<Double>) v, vectorVal);
        }
    }
    System.out.println("cwsolver solution: " + result.toString());
    return Result.SAT;
}

From source file:com.opengamma.analytics.financial.interestrate.future.provider.BondFutureHullWhiteMethod.java

/**
 * Computes the future price curve sensitivity.
 * @param future The future security./*  w w w .j  av  a 2  s. co  m*/
 * @param data The curve and Hull-White parameters.
 * @param nbPoint The number of point in the numerical cross estimation.
 * @return The curve sensitivity.
 */
public MulticurveSensitivity priceCurveSensitivity(final BondFuture future,
        final HullWhiteIssuerProviderInterface data, final int nbPoint) {
    ArgumentChecker.notNull(future, "Future");
    ArgumentChecker.notNull(data, "Hull-White data bundle");
    final Currency ccy = future.getCurrency();
    final Pair<String, Currency> issuerCcy = future.getDeliveryBasket()[0].getIssuerCcy();
    ArgumentChecker.isTrue(data.getHullWhiteIssuerCurrency().equals(issuerCcy),
            "Incompatible data and futures");
    final int nbBond = future.getDeliveryBasket().length;
    final String issuerName = future.getDeliveryBasket()[0].getIssuer();
    final HullWhiteOneFactorPiecewiseConstantParameters parameters = data.getHullWhiteParameters();
    final IssuerProviderInterface issuer = data.getIssuerProvider();
    final MulticurveProviderInterface multicurvesDecorated = new MulticurveProviderDiscountingDecoratedIssuer(
            issuer, future.getCurrency(), issuerName);

    final double expiry = future.getNoticeLastTime();
    final double delivery = future.getDeliveryLastTime();
    final double dfdelivery = data.getIssuerProvider().getDiscountFactor(issuerCcy, delivery);
    // Constructing non-homogeneous point series for the numerical estimations.
    final int nbPtWing = ((int) Math.floor(nbPoint / 20.)); // Number of point on each wing.
    final int nbPtCenter = nbPoint - 2 * nbPtWing;
    final double prob = 1.0 / (2.0 * nbPtCenter);
    final double xStart = NORMAL.getInverseCDF(prob);
    final double[] x = new double[nbPoint];
    for (int loopwing = 0; loopwing < nbPtWing; loopwing++) {
        x[loopwing] = xStart * (1.0 + (nbPtWing - loopwing) / 2.0);
        x[nbPoint - 1 - loopwing] = -xStart * (1.0 + (nbPtWing - loopwing) / 2.0);
    }
    for (int loopcent = 0; loopcent < nbPtCenter; loopcent++) {
        x[nbPtWing + loopcent] = xStart + loopcent * (-2.0 * xStart) / (nbPtCenter - 1);
    }
    // Figures for each bond
    final double[][] cfTime = new double[nbBond][];
    final double[][] df = new double[nbBond][];
    final double[][] alpha = new double[nbBond][];
    final double[][] beta = new double[nbBond][];
    final double[][] cfaAdjusted = new double[nbBond][];
    final double[] e = new double[nbBond];
    final double[][] pv = new double[nbPoint][nbBond];
    final AnnuityPaymentFixed[] cf = new AnnuityPaymentFixed[nbBond];
    for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) {
        cf[loopbnd] = future.getDeliveryBasket()[loopbnd].accept(CFEC, multicurvesDecorated);
        final int nbCf = cf[loopbnd].getNumberOfPayments();
        cfTime[loopbnd] = new double[nbCf];
        df[loopbnd] = new double[nbCf];
        alpha[loopbnd] = new double[nbCf];
        beta[loopbnd] = new double[nbCf];
        cfaAdjusted[loopbnd] = new double[nbCf];
        for (int loopcf = 0; loopcf < nbCf; loopcf++) {
            cfTime[loopbnd][loopcf] = cf[loopbnd].getNthPayment(loopcf).getPaymentTime();
            df[loopbnd][loopcf] = issuer.getDiscountFactor(issuerCcy, cfTime[loopbnd][loopcf]);
            alpha[loopbnd][loopcf] = MODEL.alpha(parameters, 0.0, expiry, delivery, cfTime[loopbnd][loopcf]);
            beta[loopbnd][loopcf] = MODEL.futuresConvexityFactor(parameters, expiry, cfTime[loopbnd][loopcf],
                    delivery);
            cfaAdjusted[loopbnd][loopcf] = df[loopbnd][loopcf] / dfdelivery * beta[loopbnd][loopcf]
                    * cf[loopbnd].getNthPayment(loopcf).getAmount() / future.getConversionFactor()[loopbnd];
            for (int looppt = 0; looppt < nbPoint; looppt++) {
                pv[looppt][loopbnd] += cfaAdjusted[loopbnd][loopcf]
                        * Math.exp(-alpha[loopbnd][loopcf] * alpha[loopbnd][loopcf] / 2.0
                                - alpha[loopbnd][loopcf] * x[looppt]);
            }
        }
        e[loopbnd] = future.getDeliveryBasket()[loopbnd].getAccruedInterest()
                / future.getConversionFactor()[loopbnd];
        for (int looppt = 0; looppt < nbPoint; looppt++) {
            pv[looppt][loopbnd] -= e[loopbnd];
        }
    }
    // Minimum: create a list of index of the CTD in each interval and a first estimate of the crossing point (x[]).
    final double[] pvMin = new double[nbPoint];
    final int[] indMin = new int[nbPoint];
    for (int looppt = 0; looppt < nbPoint; looppt++) {
        pvMin[looppt] = Double.POSITIVE_INFINITY;
        for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) {
            if (pv[looppt][loopbnd] < pvMin[looppt]) {
                pvMin[looppt] = pv[looppt][loopbnd];
                indMin[looppt] = loopbnd;
            }
        }
    }
    final ArrayList<Double> refx = new ArrayList<>();
    final ArrayList<Integer> ctd = new ArrayList<>();
    int lastInd = indMin[0];
    ctd.add(indMin[0]);
    for (int looppt = 1; looppt < nbPoint; looppt++) {
        if (indMin[looppt] != lastInd) {
            ctd.add(indMin[looppt]);
            lastInd = indMin[looppt];
            refx.add(x[looppt]);
        }
    }
    // Sum on each interval
    final int nbInt = ctd.size();
    final double[] kappa = new double[nbInt - 1];
    //    double price = 0.0;
    if (nbInt != 1) {
        // The intersections
        final BracketRoot bracketer = new BracketRoot();
        final double accuracy = 1.0E-8;
        final RidderSingleRootFinder rootFinder = new RidderSingleRootFinder(accuracy);
        for (int loopint = 1; loopint < nbInt; loopint++) {
            final BondDifference cross = new BondDifference(cfaAdjusted[ctd.get(loopint - 1)],
                    alpha[ctd.get(loopint - 1)], e[ctd.get(loopint - 1)], cfaAdjusted[ctd.get(loopint)],
                    alpha[ctd.get(loopint)], e[ctd.get(loopint)]);
            final double[] range = bracketer.getBracketedPoints(cross, refx.get(loopint - 1) - 0.01,
                    refx.get(loopint - 1) + 0.01);
            kappa[loopint - 1] = rootFinder.getRoot(cross, range[0], range[1]);
        }
    }

    // === Backward Sweep ===
    final double priceBar = 1.0;
    final double[][] cfaAdjustedBar = new double[nbBond][];
    final double[][] dfBar = new double[nbBond][];
    for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) {
        final int nbCf = cf[loopbnd].getNumberOfPayments();
        cfaAdjustedBar[loopbnd] = new double[nbCf];
        dfBar[loopbnd] = new double[nbCf];
    }
    double dfdeliveryBar = 0.0;
    final Map<String, List<DoublesPair>> resultMap = new HashMap<>();
    final List<DoublesPair> listCredit = new ArrayList<>();
    if (nbInt == 1) {
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(0)].length; loopcf++) {
            cfaAdjustedBar[ctd.get(0)][loopcf] = priceBar;
            dfBar[ctd.get(0)][loopcf] = beta[ctd.get(0)][loopcf] / dfdelivery
                    * cf[ctd.get(0)].getNthPayment(loopcf).getAmount()
                    / future.getConversionFactor()[ctd.get(0)] * cfaAdjustedBar[ctd.get(0)][loopcf];
            listCredit.add(new DoublesPair(cfTime[ctd.get(0)][loopcf],
                    -cfTime[ctd.get(0)][loopcf] * df[ctd.get(0)][loopcf] * dfBar[ctd.get(0)][loopcf]));
            dfdeliveryBar += -cfaAdjusted[ctd.get(0)][loopcf] / dfdelivery * cfaAdjustedBar[ctd.get(0)][loopcf];
        }
        listCredit.add(new DoublesPair(delivery, -delivery * dfdelivery * dfdeliveryBar));
    } else {
        // From -infinity to first cross.
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(0)].length; loopcf++) {
            cfaAdjustedBar[ctd.get(0)][loopcf] = NORMAL.getCDF(kappa[0] + alpha[ctd.get(0)][loopcf]) * priceBar;
        }
        // Between cross
        for (int loopint = 1; loopint < nbInt - 1; loopint++) {
            for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(loopint)].length; loopcf++) {
                cfaAdjustedBar[ctd.get(
                        loopint)][loopcf] = (NORMAL.getCDF(kappa[loopint] + alpha[ctd.get(loopint)][loopcf])
                                - NORMAL.getCDF(kappa[loopint - 1] + alpha[ctd.get(loopint)][loopcf]))
                                * priceBar;
            }
        }
        // From last cross to +infinity
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(nbInt - 1)].length; loopcf++) {
            cfaAdjustedBar[ctd.get(nbInt - 1)][loopcf] = (1.0
                    - NORMAL.getCDF(kappa[nbInt - 2] + alpha[ctd.get(nbInt - 1)][loopcf])) * priceBar;
        }
        for (int loopbnd = 0; loopbnd < nbBond; loopbnd++) { // Could be reduced to only the ctd intervals.
            for (int loopcf = 0; loopcf < cfaAdjusted[loopbnd].length; loopcf++) {
                dfBar[loopbnd][loopcf] = beta[loopbnd][loopcf] / dfdelivery
                        * cf[loopbnd].getNthPayment(loopcf).getAmount() / future.getConversionFactor()[loopbnd]
                        * cfaAdjustedBar[loopbnd][loopcf];
                listCredit.add(new DoublesPair(cfTime[loopbnd][loopcf],
                        -cfTime[loopbnd][loopcf] * df[loopbnd][loopcf] * dfBar[loopbnd][loopcf]));
                dfdeliveryBar += -cfaAdjusted[loopbnd][loopcf] / dfdelivery * cfaAdjustedBar[loopbnd][loopcf];
            }
        }
        listCredit.add(new DoublesPair(delivery, -delivery * dfdelivery * dfdeliveryBar));
    }
    resultMap.put(multicurvesDecorated.getName(ccy), listCredit);
    return MulticurveSensitivity.ofYieldDiscounting(resultMap);
}