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:de.bund.bfr.knime.pmm.common.chart.ChartCreator.java

public JFreeChart getChart(List<String> idsToPaint) {
    if (paramX == null || paramY == null) {
        return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, new XYPlot(), showLegend);
    }/*  ww  w . ja v  a2s .c  o  m*/

    NumberAxis xAxis = new NumberAxis(AttributeUtilities.getNameWithUnit(paramX, unitX, transformX));
    NumberAxis yAxis = new NumberAxis(AttributeUtilities.getNameWithUnit(paramY, unitY, transformY));
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    double usedMinX = Double.POSITIVE_INFINITY;
    double usedMaxX = Double.NEGATIVE_INFINITY;
    int index = 0;
    ColorAndShapeCreator colorAndShapeCreator = new ColorAndShapeCreator(idsToPaint.size());

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        try {
            if (plotable != null) {
                if (plotable.getType() == Plotable.BOTH || plotable.getType() == Plotable.BOTH_STRICT) {
                    Double minArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMinArguments().get(paramX), unitX),
                            transformX);
                    Double maxArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMaxArguments().get(paramX), unitX),
                            transformX);

                    if (isValid(minArg)) {
                        usedMinX = Math.min(usedMinX, minArg);
                    }

                    if (isValid(maxArg)) {
                        usedMaxX = Math.max(usedMaxX, maxArg);
                    }

                    for (Map<String, Integer> choice : plotable.getAllChoices()) {
                        double[][] points = plotable.getPoints(paramX, paramY, unitX, unitY, transformX,
                                transformY, choice);

                        if (points != null) {
                            for (int i = 0; i < points[0].length; i++) {
                                if (isValid(points[0][i])) {
                                    usedMinX = Math.min(usedMinX, points[0][i]);
                                    usedMaxX = Math.max(usedMaxX, points[0][i]);
                                }
                            }
                        }
                    }
                } else if (plotable.getType() == Plotable.DATASET
                        || plotable.getType() == Plotable.DATASET_STRICT) {
                    double[][] points = plotable.getPoints(paramX, paramY, unitX, unitY, transformX,
                            transformY);

                    if (points != null) {
                        for (int i = 0; i < points[0].length; i++) {
                            if (isValid(points[0][i])) {
                                usedMinX = Math.min(usedMinX, points[0][i]);
                                usedMaxX = Math.max(usedMaxX, points[0][i]);
                            }
                        }
                    }
                } else if (plotable.getType() == Plotable.FUNCTION) {
                    Double minArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMinArguments().get(paramX), unitX),
                            transformX);
                    Double maxArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMaxArguments().get(paramX), unitX),
                            transformX);

                    if (isValid(minArg)) {
                        usedMinX = Math.min(usedMinX, minArg);
                    }

                    if (isValid(maxArg)) {
                        usedMaxX = Math.max(usedMaxX, maxArg);
                    }
                } else if (plotable.getType() == Plotable.FUNCTION_SAMPLE) {
                    Double minArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMinArguments().get(paramX), unitX),
                            transformX);
                    Double maxArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMaxArguments().get(paramX), unitX),
                            transformX);

                    if (isValid(minArg)) {
                        usedMinX = Math.min(usedMinX, minArg);
                    }

                    if (isValid(maxArg)) {
                        usedMaxX = Math.max(usedMaxX, maxArg);
                    }

                    for (Double x : plotable.getSamples()) {
                        Double xx = Plotable.transform(plotable.convertToUnit(paramX, x, unitX), transformX);

                        if (isValid(xx)) {
                            usedMinX = Math.min(usedMinX, xx);
                            usedMaxX = Math.max(usedMaxX, xx);
                        }
                    }
                }
            }
        } catch (ConvertException e) {
        }
    }

    if (Double.isInfinite(usedMinX)) {
        usedMinX = 0.0;
    }

    if (Double.isInfinite(usedMaxX)) {
        usedMaxX = 100.0;
    }

    if (paramX.equals(AttributeUtilities.TIME) || paramX.equals(AttributeUtilities.CONCENTRATION)) {
        usedMinX = Math.min(usedMinX, 0.0);
        xAxis.setAutoRangeIncludesZero(true);
    } else {
        xAxis.setAutoRangeIncludesZero(false);
    }

    if (paramY.equals(AttributeUtilities.TIME) || paramY.equals(AttributeUtilities.CONCENTRATION)) {
        yAxis.setAutoRangeIncludesZero(true);
    } else {
        yAxis.setAutoRangeIncludesZero(false);
    }

    if (usedMinX == usedMaxX) {
        usedMinX -= 1.0;
        usedMaxX += 1.0;
    }

    if (useManualRange && minX < maxX && minY < maxY) {
        usedMinX = minX;
        usedMaxX = maxX;
        xAxis.setRange(new Range(minX, maxX));
        yAxis.setRange(new Range(minY, maxY));
    }

    Set<ConvertException> convertExceptions = new LinkedHashSet<>();

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable != null && plotable.getType() == Plotable.DATASET) {
            try {
                plotDataSet(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index));
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable != null && plotable.getType() == Plotable.DATASET_STRICT) {
            try {
                plotDataSetStrict(plot, plotable, id);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable != null && plotable.getType() == Plotable.FUNCTION) {
            try {
                plotFunction(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index), usedMinX, usedMaxX);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    warnings = new ArrayList<>();

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable != null && plotable.getType() == Plotable.FUNCTION_SAMPLE) {
            try {
                plotFunctionSample(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index), usedMinX, usedMaxX, warnings);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable != null && plotable.getType() == Plotable.BOTH) {
            try {
                plotBoth(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index), usedMinX, usedMaxX);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable != null && plotable.getType() == Plotable.BOTH_STRICT) {
            try {
                plotBothStrict(plot, plotable, id, usedMinX, usedMaxX);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    if (!convertExceptions.isEmpty()) {
        String warning = "Some datasets/functions cannot be converted to the desired unit\n";

        warning += "Uncovertable units: ";

        for (ConvertException e : convertExceptions) {
            warning += e.getFromUnit() + "->" + e.getToUnit() + ", ";
        }

        warning = warning.substring(0, warning.length() - 2);

        JOptionPane.showMessageDialog(this, warning, "Warning", JOptionPane.WARNING_MESSAGE);
    }

    return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, showLegend);
}

From source file:com.rapidminer.operator.preprocessing.NoiseOperator.java

@Override
public List<ParameterType> getParameterTypes() {
    List<ParameterType> types = super.getParameterTypes();

    ParameterType type = new ParameterTypeInt(PARAMETER_RANDOM_ATTRIBUTES,
            "Adds this number of random attributes.", 0, Integer.MAX_VALUE, 0);
    type.setExpert(false);/*from ww  w  . j  a  v  a2 s  . c o  m*/
    types.add(type);
    type = new ParameterTypeDouble(PARAMETER_LABEL_NOISE,
            "Add this percentage of a numerical label range as a normal distributed noise or probability for a nominal label change.",
            0.0d, Double.POSITIVE_INFINITY, 0.05d);
    type.setExpert(false);
    types.add(type);
    types.add(new ParameterTypeDouble(PARAMETER_DEFAULT_ATTRIBUTE_NOISE,
            "The standard deviation of the default attribute noise.", 0.0d, Double.POSITIVE_INFINITY, 0.0d));
    types.add(new ParameterTypeList(PARAMETER_NOISE, "List of noises for each attributes.",
            new ParameterTypeAttribute("attribute", "To this attribute noise is added.",
                    getExampleSetInputPort()),
            new ParameterTypeDouble(PARAMETER_NOISE,
                    "The strength of gaussian noise, which is added to this attribute.", 0.0d,
                    Double.POSITIVE_INFINITY, 0.05d)));
    type = new ParameterTypeDouble(PARAMETER_OFFSET, "Offset added to the values of each random attribute",
            Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 0.0d);
    types.add(type);
    type = new ParameterTypeDouble(PARAMETER_LINEAR_FACTOR,
            "Linear factor multiplicated with the values of each random attribute", 0.0d,
            Double.POSITIVE_INFINITY, 1.0d);
    types.add(type);
    types.addAll(RandomGenerator.getRandomGeneratorParameters(this));
    return types;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.AdaptiveGridArchive.java

/**
 * Computes new lower and upper bounds and recalculates the densities of
 * each grid cell./*from  w ww .jav  a  2s.c  o  m*/
 */
protected void adaptGrid() {
    Arrays.fill(minimum, Double.POSITIVE_INFINITY);
    Arrays.fill(maximum, Double.NEGATIVE_INFINITY);
    Arrays.fill(density, 0);

    for (Solution solution : this) {
        for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
            minimum[i] = Math.min(minimum[i], solution.getObjective(i));
            maximum[i] = Math.max(maximum[i], solution.getObjective(i));
        }
    }

    for (Solution solution : this) {
        density[findIndex(solution)]++;
    }
}

From source file:com.uphyca.stetho_realm.Database.java

private List<Object> flattenRows(Table table, int limit, boolean addRowIndex) {
    Util.throwIfNot(limit >= 0);
    final List<Object> flatList = new ArrayList<>();
    long numColumns = table.getColumnCount();

    final RowFetcher rowFetcher = RowFetcher.getInstance();
    for (long row = 0; row < limit && row < table.size(); row++) {
        final RowWrapper rowData = RowWrapper.wrap(rowFetcher.getRow(table, row));
        if (addRowIndex) {
            flatList.add(rowData.getIndex());
        }//  ww  w  . j a v a  2s  .c o m
        for (int column = 0; column < numColumns; column++) {
            switch (rowData.getColumnType(column)) {
            case INTEGER:
                flatList.add(rowData.getLong(column));
                break;
            case BOOLEAN:
                flatList.add(rowData.getBoolean(column));
                break;
            case STRING:
                flatList.add(rowData.getString(column));
                break;
            case BINARY:
                flatList.add(rowData.getBinaryByteArray(column));
                break;
            case FLOAT:
                final float aFloat = rowData.getFloat(column);
                if (Float.isNaN(aFloat)) {
                    flatList.add("NaN");
                } else if (aFloat == Float.POSITIVE_INFINITY) {
                    flatList.add("Infinity");
                } else if (aFloat == Float.NEGATIVE_INFINITY) {
                    flatList.add("-Infinity");
                } else {
                    flatList.add(aFloat);
                }
                break;
            case DOUBLE:
                final double aDouble = rowData.getDouble(column);
                if (Double.isNaN(aDouble)) {
                    flatList.add("NaN");
                } else if (aDouble == Double.POSITIVE_INFINITY) {
                    flatList.add("Infinity");
                } else if (aDouble == Double.NEGATIVE_INFINITY) {
                    flatList.add("-Infinity");
                } else {
                    flatList.add(aDouble);
                }
                break;
            case DATE:
                flatList.add(rowData.getDate(column));
                break;
            case LINK:
                flatList.add(rowData.getLink(column));
                break;
            case LINK_LIST:
                flatList.add(rowData.getLinkList(column));
                break;
            default:
                flatList.add("unknown column type: " + rowData.getColumnType(column));
                break;
            }
        }
    }

    if (limit < table.size()) {
        for (int column = 0; column < numColumns; column++) {
            flatList.add("{truncated}");
        }
    }

    return flatList;
}

From source file:de.uni_erlangen.lstm.modelaccess.Model.java

/**
 * Run the model using set parameters/*from  w  w w.j av a  2s.  c  o m*/
 */
public void simulate() {
    finished = false;
    /*
     * Integrator selection 
     */
    //FirstOrderIntegrator integrator = new HighamHall54Integrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10);
    //FirstOrderIntegrator integrator = new DormandPrince54Integrator(1.0e-12, 100.0, 1.0e-12, 1.0e-12);
    //FirstOrderIntegrator integrator = new DormandPrince853Integrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10);
    //FirstOrderIntegrator integrator = new GraggBulirschStoerIntegrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10);
    FirstOrderIntegrator integrator = new AdamsBashforthIntegrator(2, 1.0e-14, 100.0, 1.0e-10, 1.0e-10);
    //FirstOrderIntegrator integrator = new AdamsMoultonIntegrator(2, 1.0e-8, 100.0, 1.0e-10, 1.0e-10);

    // influent values, digester parameters, S_H_ion, dae system
    final DAEModel ode = new DAEModel(u, param, S_H_ion, dae, fix_pH);
    //FirstOrderDifferentialEquations ode = model; 

    // Records progress
    StepHandler progHandler = new StepHandler() {
        public void init(double t0, double[] y0, double t) {
        }

        public void handleStep(StepInterpolator interpolator, boolean isLast) {
            progress = interpolator.getCurrentTime();
        }
    };
    integrator.addStepHandler(progHandler);

    /*
     * Continuous model recorded in CSV
     */
    if (onlineRecord) {
        final CSVWriter writer = new CSVWriter();
        StepHandler stepHandler = new StepHandler() {
            double prevT = 0.0;

            public void init(double t0, double[] y0, double t) {
            }

            public void handleStep(StepInterpolator interpolator, boolean isLast) {
                double t = interpolator.getCurrentTime();
                if (t - prevT > resolution) {
                    // Add time to the beginning of the array
                    double[] timemodel = new double[ode.getDimensions().length + 1];
                    timemodel[0] = t;

                    // We need to pull variables (S_h2 and acid-base) directly from the model if using DAE
                    for (int i = 1; i < timemodel.length; i++) {
                        timemodel[i] = ode.getDimensions()[i - 1];
                    }

                    writer.WriteArray(output_file, timemodel, true);
                    prevT = t;
                }
            }
        };
        integrator.addStepHandler(stepHandler);
    }

    /*
     * Add event handlers for discrete events
     * maxCheck - maximal time interval between switching function checks (this interval prevents missing sign changes in case the integration steps becomes very large)
      * conv - convergence threshold in the event time search
      * maxIt - upper limit of the iteration count in the event time search
     */
    if (events.size() > 0) {
        for (DiscreteEvent event : events) {
            double maxCheck = Double.POSITIVE_INFINITY;
            double conv = 1.0e-20;
            int maxIt = 100;
            integrator.addEventHandler(event, maxCheck, conv, maxIt);
        }
    }

    integrator.integrate(ode, start, x, end, x);

    /*
     * Return the time that the discrete event occurred
     */
    if (events.size() > 0) {
        for (DiscreteEvent event : events) {
            if (event.getTime() < end) {
                end = event.getTime();
            }
        }
    }

    // We need to pull variables (S_h2 and acid-base) directly from the model
    x = ode.getDimensions();

    finished = true;
}

From source file:edu.isi.misd.scanner.network.modules.worker.processors.oceans.OceansLogisticRegressionProcessor.java

/**
 * Formats a double to a fixed (currently three) number of decimal places.
 *///w w  w.j ava2 s.  c o  m
public static double df(double a) {
    DecimalFormat f = new DecimalFormat(".000");
    Double input = Double.valueOf(a);
    // check for special values so that they are not parsed
    if (input.equals(Double.NEGATIVE_INFINITY) || input.equals(Double.POSITIVE_INFINITY)
            || input.equals(Double.NaN)) {
        return input.doubleValue();
    }
    return Double.parseDouble(f.format(input));
}

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

/**
 * Computes the future price from the curves used to price the underlying bonds and a Hull-White one factor model.
 * @param future The future security.//from   w  ww.  ja  v a2 s  .  c  om
 * @param hwData The curve and Hull-White parameters.
 * @param nbPoint The number of point in the numerical cross estimation.
 * @return The future price.
 */
public double price(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) {
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(0)].length; loopcf++) {
            price += cfaAdjusted[ctd.get(0)][loopcf];
        }
        price -= e[ctd.get(0)];
    } else {
        // 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]);
        }
        // From -infinity to first cross.
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(0)].length; loopcf++) {
            price += cfaAdjusted[ctd.get(0)][loopcf] * NORMAL.getCDF(kappa[0] + alpha[ctd.get(0)][loopcf]);
        }
        price -= e[ctd.get(0)] * NORMAL.getCDF(kappa[0]);
        // Between cross
        for (int loopint = 1; loopint < nbInt - 1; loopint++) {
            for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(loopint)].length; loopcf++) {
                price += cfaAdjusted[ctd.get(loopint)][loopcf]
                        * (NORMAL.getCDF(kappa[loopint] + alpha[ctd.get(loopint)][loopcf])
                                - NORMAL.getCDF(kappa[loopint - 1] + alpha[ctd.get(loopint)][loopcf]));
            }
            price -= e[ctd.get(loopint)] * (NORMAL.getCDF(kappa[loopint]) - NORMAL.getCDF(kappa[loopint - 1]));
        }
        // From last cross to +infinity
        for (int loopcf = 0; loopcf < cfaAdjusted[ctd.get(nbInt - 1)].length; loopcf++) {
            price += cfaAdjusted[ctd.get(nbInt - 1)][loopcf]
                    * (1.0 - NORMAL.getCDF(kappa[nbInt - 2] + alpha[ctd.get(nbInt - 1)][loopcf]));
        }
        price -= e[ctd.get(nbInt - 1)] * (1 - NORMAL.getCDF(kappa[nbInt - 2]));
    }

    return price;
}

From source file:com.rapidminer.operator.preprocessing.discretization.MinimalEntropyDiscretization.java

private Double getMinEntropySplitpoint(LinkedList<double[]> truncatedExamples, Attribute label) {
    HashSet<Double> candidateSplitpoints = new HashSet<Double>();
    Iterator<double[]> it = truncatedExamples.iterator();
    int[] totalLabelDistribution = new int[label.getMapping().size()]; // Label distribution for
    // all examples.
    while (it.hasNext()) { // Get splitpoint candidates and total label distribution.
        double[] attributeLabelPair = it.next();
        candidateSplitpoints.add(attributeLabelPair[0]);
        int labelIndex = (int) attributeLabelPair[1];
        totalLabelDistribution[labelIndex]++;
    }/*from w w w .j  a v  a  2s .c  o m*/
    double[] totalFrequencies = new double[label.getMapping().size()];
    for (int i = 0; i < label.getMapping().size(); i++) {
        totalFrequencies[i] = (double) totalLabelDistribution[i] / (double) truncatedExamples.size();
    }
    double totalEntropy = 0.0d;
    for (int i = 0; i < label.getMapping().size(); i++) {
        totalEntropy -= totalFrequencies[i] * MathFunctions.ld(totalFrequencies[i]);
    }

    double minClassInformationEntropy = totalEntropy;
    double bestSplitpoint = Double.NaN;
    double bestSplitpointEntropy1 = Double.POSITIVE_INFINITY;
    double bestSplitpointEntropy2 = Double.POSITIVE_INFINITY;
    int k1 = 0; // Number of different class labels in class 1.
    int k2 = 0; // Number of different class labels in class 2.

    for (double currentSplitpoint : candidateSplitpoints) {
        // Test every value as splitpoint
        // Initialize.
        int s1 = 0; // Instances in partition 1.
        int s2 = 0; // Instances in partition 2.
        k1 = 0;
        k2 = 0;
        int[] labelDistribution1 = new int[label.getMapping().size()]; // Label distribution in
        // class 1.
        int[] labelDistribution2 = new int[label.getMapping().size()]; // Label distribution in
        // class 2.

        // Determine the class of each instance and the corresponding label distribution.
        for (double[] attributeLabelPair : truncatedExamples) {
            double valueToCompare = attributeLabelPair[0];
            int labelIndex = (int) attributeLabelPair[1];
            if (valueToCompare <= currentSplitpoint) {
                // Partition 1 gets all instances with values less or equal to the current
                // splitpoint.
                s1++;
                labelDistribution1[labelIndex]++;
            } else { // Partition 2 gets all instances with values
                // greater than the current split point.
                s2++;
                labelDistribution2[labelIndex]++;
            }
        }

        // Calculate frequencies and number of different labels for this
        // splitpoint each class.
        double[] frequencies1 = new double[label.getMapping().size()];
        double[] frequencies2 = new double[label.getMapping().size()];
        for (int i = 0; i < label.getMapping().size(); i++) {
            frequencies1[i] = (double) labelDistribution1[i] / (double) s1;
            frequencies2[i] = (double) labelDistribution2[i] / (double) s2;
            if (labelDistribution1[i] > 0) { // Label value i exists in
                // class 1.
                k1++;
            }
            if (labelDistribution2[i] > 0) { // Label value i exists in
                // class 2.
                k2++;
            }
        }

        /*
         * Calculate entropies.
         * 
         * In the case of p(x_i) = 0 for some i, the value of the corresponding summand 0 *
         * ld(0) is taken to be 0, which is consistent with the well-known limit:
         * 
         * lim_(p -> 0+) p*log(p) = 0
         */
        double entropy1 = 0.0d;
        for (int i = 0; i < label.getMapping().size(); i++) {
            double frequency = frequencies1[i];
            // if frequency is zero, skip label
            if (frequency != 0.0d) {
                entropy1 -= frequency * MathFunctions.ld(frequency);
            }
        }
        double entropy2 = 0.0d;
        for (int i = 0; i < label.getMapping().size(); i++) {
            double frequency = frequencies2[i];
            // if frequency is zero, skip label
            if (frequency != 0.0d) {
                entropy2 -= frequency * MathFunctions.ld(frequency);
            }
        }

        double classInformationEntropy = ((double) s1 / (double) truncatedExamples.size()) * entropy1
                + ((double) s2 / (double) truncatedExamples.size()) * entropy2;
        if (classInformationEntropy < minClassInformationEntropy) {
            minClassInformationEntropy = classInformationEntropy;
            bestSplitpoint = currentSplitpoint;
            bestSplitpointEntropy1 = entropy1;
            bestSplitpointEntropy2 = entropy2;
        }
    }

    // Calculate the termination criterion. Return null if termination
    // criterion is met.
    double gain = totalEntropy - minClassInformationEntropy;
    double delta = MathFunctions.ld(Math.pow(3.0, label.getMapping().size()) - 2)
            - (label.getMapping().size() * totalEntropy - k1 * bestSplitpointEntropy1
                    - k2 * bestSplitpointEntropy2);
    if (gain >= MathFunctions.ld(truncatedExamples.size() - 1) / truncatedExamples.size()
            + delta / truncatedExamples.size()) {
        return Double.valueOf(bestSplitpoint);
    } else {
        return null;
    }
}

From source file:mase.app.allocation.AllocationProblem.java

private DescriptiveStatistics pairDistances(RealMatrix distMatrix) {
    DescriptiveStatistics ds = new DescriptiveStatistics();
    distMatrix = distMatrix.copy();//w  w w  .j av a  2s . c o  m

    for (int k = 0; k < numAgents; k++) {
        // find closest pair
        double min = Double.POSITIVE_INFINITY;
        int minI = -1, minJ = -1;
        for (int i = 0; i < numAgents; i++) {
            for (int j = 0; j < numAgents; j++) {
                double d = distMatrix.getEntry(i, j);
                if (!Double.isNaN(d) && d < min) {
                    min = d;
                    minI = i;
                    minJ = j;
                }
            }
        }
        ds.addValue(min);
        distMatrix.setRow(minI, nulify);
        distMatrix.setColumn(minJ, nulify);
    }
    return ds;
}

From source file:org.jax.maanova.madata.gui.ArrayScatterPlotPanel.java

private void mouseMoved(MouseEvent e) {
    if (this.showTooltip) {
        Point2D chartPoint = this.chartPanel.toChartPoint(e.getPoint());

        // find the nearest probe
        XYProbeData xyProbeData = this.getXYData();
        double nearestDistance = Double.POSITIVE_INFINITY;
        int nearestDotIndex = -1;
        double[] xData = xyProbeData.getXData();
        double[] yData = xyProbeData.getYData();
        for (int dotIndex = 0; dotIndex < xData.length; dotIndex++) {
            double currDist = chartPoint.distanceSq(xData[dotIndex], yData[dotIndex]);
            if (currDist < nearestDistance) {
                nearestDistance = currDist;
                nearestDotIndex = dotIndex;
            }//from w  w w .  ja  va2  s . c  om
        }

        if (nearestDotIndex == -1) {
            this.clearProbePopup();
        } else {
            Point2D probeJava2DCoord = this.getJava2DCoordinates(xData[nearestDotIndex],
                    yData[nearestDotIndex]);
            double java2DDist = probeJava2DCoord.distance(e.getX(), e.getY());

            // is the probe close enough to be worth showing (in pixel distance)
            if (java2DDist <= PlotUtil.SCATTER_PLOT_DOT_SIZE_PIXELS * 2) {
                this.showProbePopup(xyProbeData.getProbeIndices()[nearestDotIndex], xData[nearestDotIndex],
                        yData[nearestDotIndex], e.getX(), e.getY());
            } else {
                this.clearProbePopup();
            }
        }
    }
}