Example usage for java.lang Double NEGATIVE_INFINITY

List of usage examples for java.lang Double NEGATIVE_INFINITY

Introduction

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

Prototype

double NEGATIVE_INFINITY

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

Click Source Link

Document

A constant holding the negative infinity of type double .

Usage

From source file:ch.algotrader.simulation.SimulationExecutorImpl.java

private void reportStatisticsToFile(SimulationResultVO resultVO) {

    if (!this.commonConfig.isDisableReports()) {

        try {/*  w  ww  .j  a  v  a2s .  com*/

            File reportLocation = this.commonConfig.getReportLocation();
            File reportFile = new File(reportLocation != null ? reportLocation : new File("."),
                    "BackTestReport.csv");
            BackTestReport backTestReport = new BackTestReport(reportFile);

            backTestReport.write("dateTime", DateTimePatterns.LOCAL_DATE_TIME.format(LocalDateTime.now()));
            backTestReport.write("executionTime", resultVO.getMins());
            backTestReport.write("dataSet", this.commonConfig.getDataSet());

            if (resultVO.getAllTrades().getCount() == 0) {
                backTestReport.write("allTradesCount", 0);
                backTestReport.close();
                return;
            }

            double netLiqValue = resultVO.getNetLiqValue();
            backTestReport.write("netLiqValue", twoDigitFormat.format(netLiqValue));

            // monthlyPerformances
            Collection<PeriodPerformanceVO> monthlyPerformances = resultVO.getMonthlyPerformances();
            double maxDrawDownM = 0d;
            double bestMonthlyPerformance = Double.NEGATIVE_INFINITY;
            int positiveMonths = 0;
            int negativeMonths = 0;
            if ((monthlyPerformances != null)) {
                for (PeriodPerformanceVO monthlyPerformance : monthlyPerformances) {
                    maxDrawDownM = Math.min(maxDrawDownM, monthlyPerformance.getValue());
                    bestMonthlyPerformance = Math.max(bestMonthlyPerformance, monthlyPerformance.getValue());
                    if (monthlyPerformance.getValue() > 0) {
                        positiveMonths++;
                    } else {
                        negativeMonths++;
                    }
                }
            }

            // yearlyPerformances
            int positiveYears = 0;
            int negativeYears = 0;
            Collection<PeriodPerformanceVO> yearlyPerformances = resultVO.getYearlyPerformances();
            if ((yearlyPerformances != null)) {
                for (PeriodPerformanceVO yearlyPerformance : yearlyPerformances) {
                    if (yearlyPerformance.getValue() > 0) {
                        positiveYears++;
                    } else {
                        negativeYears++;
                    }
                }
            }

            if ((monthlyPerformances != null)) {
                backTestReport.write("posMonths", positiveMonths);
                backTestReport.write("negMonths", negativeMonths);
                if ((yearlyPerformances != null)) {
                    backTestReport.write("posYears", positiveYears);
                    backTestReport.write("negYears", negativeYears);
                }
            }

            PerformanceKeysVO performanceKeys = resultVO.getPerformanceKeys();
            MaxDrawDownVO maxDrawDownVO = resultVO.getMaxDrawDown();
            if (performanceKeys != null && maxDrawDownVO != null) {
                backTestReport.write("avgM", performanceKeys.getAvgM());
                backTestReport.write("stdM", performanceKeys.getStdM());
                backTestReport.write("avgY", performanceKeys.getAvgY());
                backTestReport.write("stdY", performanceKeys.getStdY());
                backTestReport.write("sharpeRatio", performanceKeys.getSharpeRatio());

                backTestReport.write("maxMonthlyDrawDown", -maxDrawDownM);
                backTestReport.write("bestMonthlyPerformance", bestMonthlyPerformance);
                backTestReport.write("maxDrawDown", maxDrawDownVO.getAmount());
                backTestReport.write("maxDrawDownPeriod", maxDrawDownVO.getPeriod() / 86400000);
                backTestReport.write("colmarRatio", performanceKeys.getAvgY() / maxDrawDownVO.getAmount());
            }

            reportTrades(backTestReport, "winningTrades", resultVO.getWinningTrades(),
                    resultVO.getAllTrades().getCount());
            reportTrades(backTestReport, "losingTrades", resultVO.getLoosingTrades(),
                    resultVO.getAllTrades().getCount());
            reportTrades(backTestReport, "allTrades", resultVO.getAllTrades(),
                    resultVO.getAllTrades().getCount());

            backTestReport.write("returns");
            if ((monthlyPerformances != null)) {
                for (PeriodPerformanceVO monthlyPerformance : monthlyPerformances) {
                    backTestReport.write(
                            DateTimePatterns.LOCAL_DATE
                                    .format(DateTimeLegacy.toLocalDate(monthlyPerformance.getDate())),
                            monthlyPerformance.getValue());
                }
            }

            backTestReport.close();

            // make sure BackTestReport.xlsx exists
            File excelReportFile = new File(reportLocation != null ? reportLocation : new File("."),
                    "BackTestReport.xlsm");
            if (!excelReportFile.exists()) {
                InputStream is = getClass().getResourceAsStream("/BackTestReport.xlsm");
                FileUtils.copyInputStreamToFile(is, excelReportFile);
            }

            if (this.commonConfig.isOpenBackTestReport()) {
                if (Desktop.isDesktopSupported()) {
                    try {
                        Desktop.getDesktop().open(excelReportFile);
                    } catch (IOException e) {
                        // no application registered to .xlsm files
                        RESULT_LOGGER.info("BackTestReport available at: " + excelReportFile);
                    }
                } else {
                    RESULT_LOGGER.info("BackTestReport available at: " + excelReportFile);
                }
            }

        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}

From source file:com.joptimizer.util.ColtUtils.java

/**
 * Returns a lower and an upper bound for the condition number
 * <br>kp(A) = Norm[A, p] / Norm[A^-1, p]   
 * <br>where//ww  w .  j a v  a2  s.c  om
 * <br>      Norm[A, p] = sup ( Norm[A.x, p]/Norm[x, p] , x !=0 )
 * <br>for a matrix and
 * <br>      Norm[x, 1]  := Sum[Math.abs(x[i]), i]             
 * <br>      Norm[x, 2]  := Math.sqrt(Sum[Math.pow(x[i], 2), i])
 * <br>   Norm[x, 00] := Max[Math.abs(x[i]), i]
 * <br>for a vector.
 *  
 * @param A matrix you want the condition number of
 * @param p norm order (2 or Integer.MAX_VALUE)
 * @return an array with the two bounds (lower and upper bound)
 * 
 * @see Ravindra S. Gajulapalli, Leon S. Lasdon "Scaling Sparse Matrices for Optimization Algorithms"
 */
public static double[] getConditionNumberRange(RealMatrix A, int p) {
    double infLimit = Double.NEGATIVE_INFINITY;
    double supLimit = Double.POSITIVE_INFINITY;
    List<Double> columnNormsList = new ArrayList<Double>();
    switch (p) {
    case 2:
        for (int j = 0; j < A.getColumnDimension(); j++) {
            columnNormsList.add(A.getColumnVector(j).getL1Norm());
        }
        Collections.sort(columnNormsList);
        //kp >= Norm[Ai, p]/Norm[Aj, p], for each i, j = 0,1,...,n, Ak columns of A
        infLimit = columnNormsList.get(columnNormsList.size() - 1) / columnNormsList.get(0);
        break;

    case Integer.MAX_VALUE:
        double normAInf = A.getNorm();
        for (int j = 0; j < A.getColumnDimension(); j++) {
            columnNormsList.add(A.getColumnVector(j).getLInfNorm());
        }
        Collections.sort(columnNormsList);
        //k1 >= Norm[A, +oo]/min{ Norm[Aj, +oo], for each j = 0,1,...,n }, Ak columns of A
        infLimit = normAInf / columnNormsList.get(0);
        break;

    default:
        throw new IllegalArgumentException("p must be 2 or Integer.MAX_VALUE");
    }
    return new double[] { infLimit, supLimit };
}

From source file:malware_classification.Malware_Classification.java

private double[][] svm_rescale(double[][] data_orig) {
    int num_features = data_orig[0].length;
    double[][] data_scaled = new double[data_orig.length][num_features];
    double[] max_vals = new double[num_features];
    double[] min_vals = new double[num_features];

    // find max and min vals of all features. Feature 0 is the true class.
    for (int curr_feature = 1; curr_feature < num_features; curr_feature++) {
        double max_val = Double.NEGATIVE_INFINITY;
        double min_val = Double.POSITIVE_INFINITY;
        for (int curr_vec = 0; curr_vec < data_orig.length; curr_vec++) {
            double curr_val = data_orig[curr_vec][curr_feature];
            if (curr_val > max_val) {
                max_val = curr_val;
            }//from   w  w  w  .jav  a  2 s. c o  m
            if (curr_val < min_val) {
                min_val = curr_val;
            }
        }
        max_vals[curr_feature] = max_val;
        min_vals[curr_feature] = min_val;
        if (Double.compare(max_vals[curr_feature], min_vals[curr_feature]) == 0) {
            logger.info("All data for feature " + curr_feature + " are the same");
        }

    }

    //rescale
    for (int curr_vec = 0; curr_vec < data_orig.length; curr_vec++) {
        data_scaled[curr_vec][0] = data_orig[curr_vec][0];
        data_scaled[curr_vec][1] = data_orig[curr_vec][1];
        for (int curr_feature = 2; curr_feature < num_features; curr_feature++) {
            if (Double.compare(max_vals[curr_feature], min_vals[curr_feature]) != 0) {
                data_scaled[curr_vec][curr_feature] = (data_orig[curr_vec][curr_feature]
                        - min_vals[curr_feature]) / (max_vals[curr_feature] - min_vals[curr_feature]);
            } else {
                data_scaled[curr_vec][curr_feature] = 0;
            }
        }
    }

    return data_scaled;
}

From source file:gdsc.core.ij.AlignImagesFFT.java

private static double[] performCubicFit(FloatProcessor fp, double x, double y, double range) {
    double[] centre = new double[2];
    double peakValue = Double.NEGATIVE_INFINITY;
    for (double x0 : new double[] { x - range, x, x + range }) {
        for (double y0 : new double[] { y - range, y, y + range }) {
            double v = fp.getBicubicInterpolatedPixel(x0, y0, fp);
            if (peakValue < v) {
                peakValue = v;//from   ww  w .  jav a2  s. c o  m
                centre[0] = x0;
                centre[1] = y0;
            }
        }
    }
    return centre;
}

From source file:de.bund.bfr.knime.pmm.common.chart.ChartCreator.java

private void plotBothStrict(XYPlot plot, Plotable plotable, String id, double minX, double maxX)
        throws ConvertException {
    String legend = shortLegend.get(id);
    List<Color> colorList = colorLists.get(id);
    List<Shape> shapeList = shapeLists.get(id);
    ColorAndShapeCreator creator = new ColorAndShapeCreator(plotable.getNumberOfCombinations());
    int index = 0;

    if (addInfoInLegend) {
        legend = longLegend.get(id);/*from w ww .ja  va 2 s .  c o m*/
    }

    if (colorList == null || colorList.isEmpty()) {
        colorList = creator.getColorList();
    }

    if (shapeList == null || shapeList.isEmpty()) {
        shapeList = creator.getShapeList();
    }

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

        if (dataPoints == null) {
            continue;
        }

        double[][] modelPoints = plotable.getFunctionPoints(paramX, paramY, unitX, unitY, transformX,
                transformY, minX, maxX, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, choiceMap);

        if (modelPoints == null) {
            continue;
        }

        double[][] modelErrors = null;

        if (showConfidenceInterval) {
            modelErrors = plotable.getFunctionErrors(paramX, paramY, unitX, unitY, transformX, transformY, minX,
                    maxX, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, choiceMap);
        }

        int i;

        if (plot.getDataset(0) == null) {
            i = 0;
        } else {
            i = plot.getDatasetCount();
        }

        String addLegend = "";

        for (String arg : choiceMap.keySet()) {
            if (!arg.equals(paramX)) {
                addLegend += " (" + arg + "=" + plotable.getFunctionArguments().get(arg).get(choiceMap.get(arg))
                        + ")";
            }
        }

        if (modelErrors != null) {
            YIntervalSeriesCollection modelSet = new YIntervalSeriesCollection();
            DeviationRenderer modelRenderer = new DeviationRenderer(true, false);
            YIntervalSeries series = new YIntervalSeries(legend);

            for (int j = 0; j < modelPoints[0].length; j++) {
                double error = Double.isNaN(modelErrors[1][j]) ? 0.0 : modelErrors[1][j];

                series.add(modelPoints[0][j], modelPoints[1][j], modelPoints[1][j] - error,
                        modelPoints[1][j] + error);
            }

            modelSet.addSeries(series);
            modelRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
            modelRenderer.setSeriesPaint(0, colorList.get(index));
            modelRenderer.setSeriesFillPaint(0, colorList.get(index));
            modelRenderer.setSeriesShape(0, shapeList.get(index));

            if (dataPoints != null) {
                modelRenderer.setBaseSeriesVisibleInLegend(false);
            }

            plot.setDataset(i, modelSet);
            plot.setRenderer(i, modelRenderer);
        } else {
            DefaultXYDataset modelSet = new DefaultXYDataset();
            XYLineAndShapeRenderer modelRenderer = new XYLineAndShapeRenderer(true, false);

            modelSet.addSeries(legend + addLegend, modelPoints);
            modelRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
            modelRenderer.setBaseSeriesVisibleInLegend(false);
            modelRenderer.setSeriesPaint(0, colorList.get(index));
            modelRenderer.setSeriesShape(0, shapeList.get(index));

            plot.setDataset(i, modelSet);
            plot.setRenderer(i, modelRenderer);
        }

        DefaultXYDataset dataSet = new DefaultXYDataset();
        XYLineAndShapeRenderer dataRenderer = new XYLineAndShapeRenderer(drawLines, true);

        dataSet.addSeries(legend + addLegend, dataPoints);
        dataRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        dataRenderer.setSeriesPaint(0, colorList.get(index));
        dataRenderer.setSeriesShape(0, shapeList.get(index));
        plot.setDataset(i + 1, dataSet);
        plot.setRenderer(i + 1, dataRenderer);

        index++;
    }
}

From source file:net.myrrix.online.ServerRecommender.java

private static IDCluster findClosestCentroid(float[] vector, Iterable<IDCluster> clusters) {
    double vectorNorm = SimpleVectorMath.norm(vector);
    IDCluster closestCentroid = null;/*w w  w .j av a 2  s .  c  o  m*/
    double highestDot = Double.NEGATIVE_INFINITY;
    for (IDCluster cluster : clusters) {
        double dot = SimpleVectorMath.dot(cluster.getCentroid(), vector) / cluster.getCentroidNorm()
                / vectorNorm;
        if (LangUtils.isFinite(dot) && dot > highestDot) {
            highestDot = dot;
            closestCentroid = cluster;
        }
    }
    return closestCentroid;
}

From source file:aprofplot.jfreechart.SamplingXYLineAndShapeRenderer.java

protected void drawSeriesLine(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
        PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
        int series, CrosshairState crosshairState, int pass) {

    State s = (State) state;
    PlotOrientation orientation = plot.getOrientation();
    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    double lowestVisibleX = domainAxis.getLowerBound();
    double highestVisibleX = domainAxis.getUpperBound();
    double width = (orientation == PlotOrientation.HORIZONTAL) ? dataArea.getHeight() : dataArea.getWidth();
    double dX = (highestVisibleX - lowestVisibleX) / width * lineWidth;
    double lowestVisibleY = rangeAxis.getLowerBound();
    double highestVisibleY = rangeAxis.getUpperBound();

    double lastX = Double.NEGATIVE_INFINITY;
    double lastY = 0.0;
    double highY = 0.0;
    double lowY = 0.0;
    double closeY = 0.0;
    boolean lastIntervalDone = false;
    boolean currentPointVisible = false;
    boolean lastPointVisible = false;
    boolean lastPointGood = false;
    boolean lastPointInInterval = false;
    int intervalCount = 0;
    int badPoints = 0;
    for (int itemIndex = state.getFirstItemIndex(); itemIndex <= state.getLastItemIndex(); itemIndex++) {
        double x = dataset.getXValue(series, itemIndex);
        double y = dataset.getYValue(series, itemIndex);
        if (!Double.isNaN(x) && !Double.isNaN(y)) {
            if ((Math.abs(x - lastX) > dX)) {
                //System.out.println("Breakpoint 1: leaving interval");
                //in any case, add the interval that we are about to leave to the intervalPath
                float intervalStartX = 0.0f;
                float intervalEndX = 0.0f;
                float intervalStartY = 0.0f;
                float intervalEndY = 0.0f;
                float currentX = 0.0f;
                float currentY = 0.0f;
                float lastFX = 0.0f;
                float lastFY = 0.0f;

                //first set some variables
                if (orientation == PlotOrientation.VERTICAL) {
                    intervalStartX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                    intervalEndX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                    intervalStartY = (float) rangeAxis.valueToJava2D(lowY, dataArea, yAxisLocation);
                    intervalEndY = (float) rangeAxis.valueToJava2D(highY, dataArea, yAxisLocation);
                    currentX = (float) domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
                    lastFX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                    currentY = (float) rangeAxis.valueToJava2D(y, dataArea, yAxisLocation);
                    lastFY = (float) rangeAxis.valueToJava2D(closeY, dataArea, yAxisLocation);
                } else {
                    intervalStartX = (float) rangeAxis.valueToJava2D(lowY, dataArea, yAxisLocation);
                    intervalEndX = (float) rangeAxis.valueToJava2D(highY, dataArea, yAxisLocation);
                    intervalStartY = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                    intervalEndY = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                    currentX = (float) rangeAxis.valueToJava2D(y, dataArea, yAxisLocation);
                    lastFX = (float) rangeAxis.valueToJava2D(closeY, dataArea, yAxisLocation);
                    currentY = (float) domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
                    lastFY = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                }// ww  w  .j  ava2 s.  c o m
                if ((lowY - highY) < 1) {
                    //System.out.println("Breakpoint 2: setting lastPointInInterval");
                    lastPointInInterval = false;
                }
                //System.out.println("Breakpoint 3: lastPointInInterval: " +lastPointInInterval);
                if ((lowY < highY)) {
                    intervalCount++;
                    //System.out.println("Breakpoint 4: adding segment to interval path:" );
                    //System.out.println("xStart" + intervalStartX + ", yStart " + intervalStartY + ", xEnd " + intervalEndX + ", yEnd " + intervalEndY);
                    s.intervalPath.moveTo(intervalStartX, intervalStartY);
                    s.intervalPath.lineTo(intervalEndX, intervalEndY);
                    lastIntervalDone = true;
                }

                //now the series path
                currentPointVisible = ((x >= lowestVisibleX) && (x <= highestVisibleX) && (y >= lowestVisibleY)
                        && (y <= highestVisibleY));
                if (!lastPointGood) {//last point not valid --
                    badPoints++;
                    if (currentPointVisible) {//--> if the current position is visible move seriesPath cursor to the current position
                        s.seriesPath.moveTo(currentX, currentY);
                    }
                } else {//last point valid
                    //if the last point was visible and not part of an interval,
                    //we have already moved the seriesPath cursor to the last point, either with or without drawingh a line
                    //thus we only need to draw a line to the current position
                    if (lastPointVisible && !lastPointInInterval) {
                        s.seriesPath.lineTo(currentX, currentY);
                    } //if the last point was not visible or part of an interval, we have just stored the y values of the last point
                      //and not yet moved the seriesPath cursor. Thus, we need to move the cursor to the last point without drawing
                      //and draw a line to the current position.
                    else {
                        s.seriesPath.moveTo(lastFX, lastFY);
                        s.seriesPath.lineTo(currentX, currentY);
                    }
                }
                lastPointVisible = currentPointVisible;
                lastX = x;
                lastY = y;
                highY = y;
                lowY = y;
                closeY = y;
                lastPointInInterval = false;
            } else {
                lastIntervalDone = false;
                lastPointInInterval = true;
                highY = Math.max(highY, y);
                lowY = Math.min(lowY, y);
                closeY = y;
            }
            lastPointGood = true;
        } else {
            lastPointGood = false;
        }
    }
    // if this is the last item, draw the path ...
    // draw path, but first check whether we need to complete an interval
    if (!lastIntervalDone) {
        if (lowY < highY) {
            float intervalStartX = 0.0f;
            float intervalEndX = 0.0f;
            float intervalStartY = 0.0f;
            float intervalEndY = 0.0f;
            if (orientation == PlotOrientation.VERTICAL) {
                intervalStartX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                intervalEndX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                intervalStartY = (float) rangeAxis.valueToJava2D(lowY, dataArea, yAxisLocation);
                intervalEndY = (float) rangeAxis.valueToJava2D(highY, dataArea, yAxisLocation);
            } else {
                intervalStartX = (float) rangeAxis.valueToJava2D(lowY, dataArea, yAxisLocation);
                intervalEndX = (float) rangeAxis.valueToJava2D(highY, dataArea, yAxisLocation);
                intervalStartY = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
                intervalEndY = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation);
            }
            intervalCount++;
            s.intervalPath.moveTo(intervalStartX, intervalStartY);
            s.intervalPath.lineTo(intervalEndX, intervalEndY);
        }
    }
    PathIterator pi = s.seriesPath.getPathIterator(null);
    g2.setStroke(getItemStroke(series, 0));
    g2.setPaint(getItemPaint(series, 0));
    g2.draw(s.seriesPath);
    g2.draw(s.intervalPath);
    //System.out.println("Interval count " + intervalCount);
    //System.out.println("Bad points " + badPoints);
}

From source file:org.jfree.data.general.DatasetUtilities.java

/**
 * Iterates over the data item of the category dataset to find
 * the range bounds./*from  w  ww .j av a  2 s .  c o  m*/
 *
 * @param dataset  the dataset (<code>null</code> not permitted).
 * @param includeInterval  a flag that determines whether or not the
 *                         y-interval is taken into account.
 *
 * @return The range (possibly <code>null</code>).
 *
 * @since 1.0.10
 */
public static Range iterateRangeBounds(CategoryDataset dataset, boolean includeInterval) {
    double minimum = Double.POSITIVE_INFINITY;
    double maximum = Double.NEGATIVE_INFINITY;
    int rowCount = dataset.getRowCount();
    int columnCount = dataset.getColumnCount();
    if (includeInterval && dataset instanceof IntervalCategoryDataset) {
        // handle the special case where the dataset has y-intervals that
        // we want to measure
        IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
        Number value, lvalue, uvalue;
        for (int row = 0; row < rowCount; row++) {
            for (int column = 0; column < columnCount; column++) {
                value = icd.getValue(row, column);
                double v;
                if ((value != null) && !Double.isNaN(v = value.doubleValue())) {
                    minimum = Math.min(v, minimum);
                    maximum = Math.max(v, maximum);
                }
                lvalue = icd.getStartValue(row, column);
                if (lvalue != null && !Double.isNaN(v = lvalue.doubleValue())) {
                    minimum = Math.min(v, minimum);
                    maximum = Math.max(v, maximum);
                }
                uvalue = icd.getEndValue(row, column);
                if (uvalue != null && !Double.isNaN(v = uvalue.doubleValue())) {
                    minimum = Math.min(v, minimum);
                    maximum = Math.max(v, maximum);
                }
            }
        }
    } else {
        // handle the standard case (plain CategoryDataset)
        for (int row = 0; row < rowCount; row++) {
            for (int column = 0; column < columnCount; column++) {
                Number value = dataset.getValue(row, column);
                if (value != null) {
                    double v = value.doubleValue();
                    if (!Double.isNaN(v)) {
                        minimum = Math.min(minimum, v);
                        maximum = Math.max(maximum, v);
                    }
                }
            }
        }
    }
    if (minimum == Double.POSITIVE_INFINITY) {
        return null;
    } else {
        return new Range(minimum, maximum);
    }
}

From source file:com.bazaarvoice.jackson.rison.RisonParser.java

/**
 * Method called if expected numeric value (due to leading sign) does not
 * look like a number/*from   w  w  w .  j a v  a  2  s.  c  o m*/
 */
protected JsonToken _handleInvalidNumberStart(int ch, boolean negative) throws IOException, JsonParseException {
    if (ch == 'I') {
        if (_inputPtr >= _inputEnd) {
            if (!loadMore()) {
                _reportInvalidEOFInValue();
            }
        }
        ch = _inputBuffer[_inputPtr++];
        if (ch == 'N') {
            String match = negative ? "-INF" : "+INF";
            _matchToken(match, 3);
            if (isEnabled(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS)) {
                return resetAsNaN(match, negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);
            }
            _reportError("Non-standard token '" + match
                    + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow");
        } else if (ch == 'n') {
            String match = negative ? "-Infinity" : "+Infinity";
            _matchToken(match, 3);
            if (isEnabled(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS)) {
                return resetAsNaN(match, negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);
            }
            _reportError("Non-standard token '" + match
                    + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow");
        }
    }
    reportUnexpectedNumberChar(ch, "expected digit (0-9) to follow minus sign, for valid numeric value");
    return null;
}

From source file:edu.cmu.tetrad.search.Lofs2.java

private void optimizeRow(final int rowIndex, final TetradMatrix data, final double range,
        final List<List<Integer>> rows, final List<List<Double>> parameters) {
    System.out.println("A");

    final int numParams = rows.get(rowIndex).size();

    final double[] dLeftMin = new double[numParams];
    final double[] dRightMin = new double[numParams];

    double[] values = new double[numParams];
    double delta = 0.1;

    if (false) { //isEdgeCorrected()) {
        double min = -2;
        double max = 2;

        int[] dims = new int[values.length];

        int numBins = 5;
        for (int i = 0; i < values.length; i++)
            dims[i] = numBins;/*from  w  w w . j  av  a 2s.co m*/

        CombinationGenerator gen = new CombinationGenerator(dims);
        int[] comb;
        List<Double> maxParams = new ArrayList<Double>();

        for (int i = 0; i < values.length; i++)
            maxParams.add(0.0);

        double maxV = Double.NEGATIVE_INFINITY;

        while ((comb = gen.next()) != null) {
            List<Double> params = new ArrayList<Double>();

            for (int i = 0; i < values.length; i++) {
                params.add(min + (max - min) * (comb[i] / (double) numBins));
            }

            parameters.set(rowIndex, params);

            double v = scoreRow(rowIndex, data, rows, parameters);

            if (v > maxV) {
                maxV = v;
                maxParams = params;
            }
        }

        System.out.println("maxparams = " + maxParams);

        parameters.set(rowIndex, maxParams);

        for (int i = 0; i < values.length; i++) {
            dLeftMin[i] = -range;
            dRightMin[i] = range;
            values[i] = maxParams.get(i);
        }
    } else if (false) {
        for (int i = 0; i < numParams; i++) {
            parameters.get(rowIndex).set(i, -range);
            double vLeft = scoreRow(rowIndex, data, rows, parameters);
            double dLeft = -range;

            // Search from the left for the first valley; mark that as dleft.
            for (double d = -range + delta; d < range; d += delta) {
                parameters.get(rowIndex).set(i, d);
                double v = scoreRow(rowIndex, data, rows, parameters);
                if (Double.isNaN(v))
                    continue;
                if (v > vLeft)
                    break;
                vLeft = v;
                dLeft = d;
            }

            parameters.get(rowIndex).set(i, range);
            double vRight = scoreRow(rowIndex, data, rows, parameters);
            double dRight = range;

            // Similarly for dright. Will take dleft and dright to be bounds for the parameter,
            // to avoid high scores at the boundaries.
            for (double d = range - delta; d > -range; d -= delta) {
                parameters.get(rowIndex).set(i, d);
                double v = scoreRow(rowIndex, data, rows, parameters);
                if (Double.isNaN(v))
                    continue;
                if (v > vRight)
                    break;
                vRight = v;
                dRight = d;
            }

            // If dleft dright ended up reversed, re-reverse them.
            if (dLeft > dRight) {
                double temp = dRight;
                dLeft = dRight;
                dRight = temp;
            }

            System.out.println("dLeft = " + dLeft + " dRight = " + dRight);

            dLeftMin[i] = dLeft;
            dRightMin[i] = dRight;

            values[i] = (dLeft + dRight) / 2.0;
        }
    } else {

        System.out.println("B");

        // Default case: search for the maximum score over the entire range.
        for (int i = 0; i < numParams; i++) {
            dLeftMin[i] = -range;
            dRightMin[i] = range;

            values[i] = 0;
        }
    }

    MultivariateFunction function = new MultivariateFunction() {
        public double value(double[] values) {
            System.out.println(Arrays.toString(values));

            for (int i = 0; i < values.length; i++) {
                parameters.get(rowIndex).set(i, values[i]);
            }

            double v = scoreRow(rowIndex, data, rows, parameters);

            if (Double.isNaN(v)) {
                return Double.POSITIVE_INFINITY; // was 10000
            }

            return -v;
        }
    };

    try {
        MultivariateOptimizer search = new PowellOptimizer(1e-7, 1e-7);

        PointValuePair pair = search.optimize(new InitialGuess(values), new ObjectiveFunction(function),
                GoalType.MINIMIZE, new MaxEval(100000));

        values = pair.getPoint();
    } catch (Exception e) {
        e.printStackTrace();

        for (int i = 0; i < values.length; i++) {
            parameters.get(rowIndex).set(i, Double.NaN);
        }
    }
}