Example usage for java.lang Double MAX_VALUE

List of usage examples for java.lang Double MAX_VALUE

Introduction

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

Prototype

double MAX_VALUE

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

Click Source Link

Document

A constant holding the largest positive finite value of type double , (2-2-52)·21023.

Usage

From source file:org.jfree.data.statistics.HistogramDataset.java

/**
 * Returns the maximum value in an array of values.
 *
 * @param values  the values (<code>null</code> not permitted and
 *                zero-length array not permitted).
 *
 * @return The maximum value./*w  w w .j  a va 2 s .  c  o  m*/
 */
private double getMaximum(double[] values) {
    if (values == null || values.length < 1) {
        throw new IllegalArgumentException("Null or zero length 'values' argument.");
    }
    double max = -Double.MAX_VALUE;
    for (int i = 0; i < values.length; i++) {
        if (values[i] > max) {
            max = values[i];
        }
    }
    return max;
}

From source file:org.fhcrc.cpl.viewer.ms2.Fractionation2DUtilities.java

public static void showHeatMapChart(FractionatedAMTDatabaseStructure amtDatabaseStructure,
        double[] dataForChart, String chartName, boolean showLegend) {
    int chartWidth = 1000;
    int chartHeight = 1000;

    double globalMinValue = Double.MAX_VALUE;
    double globalMaxValue = Double.MIN_VALUE;

    for (double value : dataForChart) {
        if (value < globalMinValue)
            globalMinValue = value;//w  ww  .  j a  va 2s. c  o  m
        if (value > globalMaxValue)
            globalMaxValue = value;
    }

    _log.debug("showHeatMapChart: experiment structures:");
    List<double[][]> amtPeptidesInExperiments = new ArrayList<double[][]>();
    for (int i = 0; i < amtDatabaseStructure.getNumExperiments(); i++) {
        int experimentWidth = amtDatabaseStructure.getExperimentStructure(i).columns;
        int experimentHeight = amtDatabaseStructure.getExperimentStructure(i).rows;
        _log.debug("\t" + amtDatabaseStructure.getExperimentStructure(i));
        amtPeptidesInExperiments.add(new double[experimentWidth][experimentHeight]);
    }
    for (int i = 0; i < dataForChart.length; i++) {
        Pair<Integer, int[]> positionInExperiments = amtDatabaseStructure.calculateExperimentAndPosition(i);
        int xpos = positionInExperiments.second[0];
        int ypos = positionInExperiments.second[1];
        int experimentIndex = positionInExperiments.first;
        //System.err.println("i, xpos, ypos: " + i + ", " + xpos + ", " + ypos);            
        amtPeptidesInExperiments.get(experimentIndex)[xpos][ypos] = dataForChart[i];

    }

    JDialog cd = new JDialog(ApplicationContext.getFrame(), "Heat Map(s)");
    cd.setSize(chartWidth, chartHeight);
    cd.setPreferredSize(new Dimension(chartWidth, chartHeight));
    cd.setLayout(new FlowLayout());

    int nextPerfectSquareRoot = 0;
    while (true) {
        nextPerfectSquareRoot++;
        if ((nextPerfectSquareRoot * nextPerfectSquareRoot) >= amtPeptidesInExperiments.size()) {
            break;
        }
    }

    int plotWidth = (int) ((double) (chartWidth - 20) / (double) nextPerfectSquareRoot);
    int plotHeight = (int) ((double) (chartHeight - 20) / (double) nextPerfectSquareRoot);

    _log.debug("Rescaled chart dimensions: " + plotWidth + "x" + plotHeight);

    LookupPaintScale paintScale = PanelWithHeatMap.createPaintScale(globalMinValue, globalMaxValue, Color.BLUE,
            Color.RED);

    for (int i = 0; i < amtPeptidesInExperiments.size(); i++) {
        PanelWithHeatMap pwhm = new PanelWithHeatMap(amtPeptidesInExperiments.get(i), "Experiment " + (i + 1));
        //            pwhm.setPalette(PanelWithHeatMap.PALETTE_BLUE_RED);
        pwhm.setPaintScale(paintScale);
        pwhm.setPreferredSize(new Dimension(plotWidth, plotHeight));
        pwhm.setAxisLabels("AX Fraction", "RP Fraction");
        if (!showLegend)
            pwhm.getChart().removeLegend();
        cd.add(pwhm);
    }
    cd.setTitle(chartName);
    cd.setVisible(true);
}

From source file:com.compomics.util.experiment.identification.psm_scoring.psm_scores.HyperScore.java

/**
 * Returns the e-value corresponding to a list of scores in a map. If not
 * enough scores are present or if they are not spread the method returns
 * null./*  w w  w  .j  a  va  2s . c o m*/
 *
 * @param hyperScores the different scores
 * @param useCache if true the interpolation values will be stored in the
 * histograms in cache
 *
 * @return the e-values corresponding to the given scores
 */
public HashMap<Double, Double> getEValueMap(ArrayList<Double> hyperScores, boolean useCache) {
    HashMap<Integer, Integer> histogram = new HashMap<Integer, Integer>();
    Double maxScore = 0.0;
    Double minScore = Double.MAX_VALUE;
    for (Double score : hyperScores) {
        Integer intValue = score.intValue();
        if (intValue > 0) {
            Integer nScores = histogram.get(intValue);
            if (nScores == null) {
                nScores = 1;
            } else {
                nScores++;
            }
            histogram.put(intValue, nScores);
            if (score > maxScore) {
                maxScore = score;
            }
            if (score < minScore) {
                minScore = score;
            }
        }
    }
    Integer lowestBin = minScore.intValue();
    Integer highestBin = maxScore.intValue();
    Integer secondEmptybin = highestBin;
    Integer firstEmptybin = highestBin;
    boolean emptyBin = false;
    for (Integer bin = lowestBin; bin <= highestBin; bin++) {
        if (!histogram.containsKey(bin)) {
            if (!emptyBin) {
                emptyBin = true;
                firstEmptybin = bin;
            } else {
                secondEmptybin = bin;
                break;
            }
        }
    }
    ArrayList<Integer> bins = new ArrayList<Integer>(histogram.keySet());
    for (Integer bin : bins) {
        if (bin > secondEmptybin) {
            histogram.remove(bin);
        } else if (bin > firstEmptybin) {
            histogram.put(bin, 1);
        }
    }
    double[] ab = getInterpolationValues(histogram, useCache);
    if (ab == null) {
        return null;
    }
    return getInterpolation(hyperScores, ab[0], ab[1]);
}

From source file:com.elex.dmp.lda.InMemoryCollapsedVariationalBayes0.java

public double iterateUntilConvergence(double minFractionalErrorChange, int maxIterations, int minIter,
        double testFraction) {
    int iter = 0;
    double oldPerplexity = 0;
    while (iter < minIter) {
        trainDocuments(testFraction);/*from w ww .  j a v a  2 s. c o  m*/
        if (verbose) {
            log.info("model after: " + iter + ": " + modelTrainer.getReadModel().toString());
        }
        log.info("iteration " + iter + " complete");
        oldPerplexity = modelTrainer.calculatePerplexity(corpusWeights, docTopicCounts, testFraction);
        log.info(oldPerplexity + " = perplexity");
        iter++;
    }
    double newPerplexity = 0;
    double fractionalChange = Double.MAX_VALUE;
    while (iter < maxIterations && fractionalChange > minFractionalErrorChange) {
        trainDocuments();
        if (verbose) {
            log.info("model after: " + iter + ": " + modelTrainer.getReadModel().toString());
        }
        newPerplexity = modelTrainer.calculatePerplexity(corpusWeights, docTopicCounts, testFraction);
        log.info(newPerplexity + " = perplexity");
        iter++;
        fractionalChange = Math.abs(newPerplexity - oldPerplexity) / oldPerplexity;
        log.info(fractionalChange + " = fractionalChange");
        oldPerplexity = newPerplexity;
    }
    if (iter < maxIterations) {
        log.info(String.format("Converged! fractional error change: %f, error %f", fractionalChange,
                newPerplexity));
    } else {
        log.info(String.format("Reached max iteration count (%d), fractional error change: %f, error: %f",
                maxIterations, fractionalChange, newPerplexity));
    }
    return newPerplexity;
}

From source file:mil.tatrc.physiology.utilities.csv.plots.ActionEventPlotter.java

public void createGraph(PlotJob job, List<List<Double>> timeData, List<List<Double>> data,
        List<LogEvent> events, List<SEAction> actions) {
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet = new XYSeriesCollection();
    double maxY = 0;
    double minY = Double.MAX_VALUE;
    for (int i = 0; i < timeData.size(); i++) {
        if (timeData.get(i) == null || data.get(i) == null) {
            job.bgColor = Color.white; //This hits when we have Expected data but NOT computed data
            continue;
        }//  w  w w .j a  va 2 s  .c  o  m

        title = title + job.headers.get(i) + "_";
        XYSeries dataSeries;
        if (job.isComparePlot) {
            if (timeData.size() > 1)
                dataSeries = plotTool.createXYSeries(i == 0 ? "Expected" : "Computed", timeData.get(i),
                        data.get(i));
            else //If we're comparing but only have one data list, expected is missing, so rename to computed
            {
                dataSeries = plotTool.createXYSeries("Computed", timeData.get(i), data.get(i));
            }
        } else
            dataSeries = plotTool.createXYSeries(job.headers.get(i), timeData.get(i), data.get(i));
        dataSet.addSeries(dataSeries);
        maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
        minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;
    }
    title = title + "vs_Time_Action_Event_Plot";

    //Override the constructed title if desired (usually for compare plots)
    if (job.titleOverride != null && !job.titleOverride.isEmpty()
            && !job.titleOverride.equalsIgnoreCase("None"))
        title = job.titleOverride;

    double rangeLength = maxY - minY;
    if (Math.abs(rangeLength) < 1e-6) {
        rangeLength = .01;
    }

    class AEEntry implements Comparable<AEEntry> {
        public String name;
        public List<Double> times = new ArrayList<Double>();
        public List<Double> YVals = new ArrayList<Double>();
        public String type = "";

        public int compareTo(AEEntry entry) {
            return times.get(0) < entry.times.get(0) ? -1 : times.get(0) > entry.times.get(0) ? 1 : 0;
        }
    }

    List<AEEntry> allActionsAndEvents = new ArrayList<AEEntry>();

    if (!job.skipAllEvents) {
        //Make points for each event
        //Treat each event like two points on the same vertical line
        for (LogEvent event : events) {
            boolean skip = false;

            for (String eventToSkip : job.eventOmissions) {
                if (event.text.contains(eventToSkip))
                    skip = true;
            }
            if (skip)
                continue;
            AEEntry entry = new AEEntry();

            entry.times.add(event.time.getValue());
            if (job.logAxis)
                entry.YVals.add(maxY);
            else if (job.forceZeroYAxisBound && maxY < 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(maxY + 0.15 * rangeLength);

            entry.times.add(event.time.getValue());
            if (job.logAxis)
                entry.YVals.add(minY);
            else if (job.forceZeroYAxisBound && minY > 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(minY - 0.15 * rangeLength);

            entry.name = event.text + "\r\nt=" + event.time.getValue();
            entry.type = "EVENT:";

            allActionsAndEvents.add(entry);
        }
    }

    if (!job.skipAllActions) {
        //Make similar entries for actions
        for (SEAction action : actions) {
            boolean skip = false;

            for (String actionToSkip : job.actionOmissions) {
                if (action.toString().contains(actionToSkip))
                    skip = true;
            }
            if (skip)
                continue;

            if (action.toString().contains("Advance Time"))
                continue;

            AEEntry entry = new AEEntry();

            entry.times.add(action.getScenarioTime().getValue());
            if (job.logAxis)
                entry.YVals.add(maxY);
            else if (job.forceZeroYAxisBound && maxY < 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(maxY + 0.15 * rangeLength);

            entry.times.add(action.getScenarioTime().getValue());
            if (job.logAxis)
                entry.YVals.add(minY);
            else if (job.forceZeroYAxisBound && minY > 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(minY - 0.15 * rangeLength);

            entry.name = action.toString() + "\r\nt=" + action.getScenarioTime().getValue();
            entry.type = "ACTION:";

            allActionsAndEvents.add(entry);
        }
    }

    //Sort the list
    Collections.sort(allActionsAndEvents);

    //Add a series for each entry
    for (AEEntry entry : allActionsAndEvents) {
        dataSet.addSeries(plotTool.createXYSeries(entry.type + entry.name, entry.times, entry.YVals));
    }

    //If we have experimental data, try to load it and create a dataset for it
    XYSeriesCollection expDataSet = new XYSeriesCollection();
    if (job.experimentalData != null && !job.experimentalData.isEmpty()) {
        Map<String, List<Double>> expData = new HashMap<String, List<Double>>();
        List<String> expHeaders = new ArrayList<String>();

        try {
            CSVContents csv = new CSVContents(job.experimentalData);
            csv.abbreviateContents = 0;
            csv.readAll(expData);
            expHeaders = csv.getHeaders();
        } catch (Exception e) {
            Log.error("Unable to read experimental data");
        }

        if (!expData.isEmpty() && !expHeaders.isEmpty()) {
            List<Double> expTimeData = new ArrayList<Double>();
            expTimeData = expData.get("Time(s)");

            for (String h : expHeaders) //Will assume all headers from exp file will be on same Y axis vs time
            {
                if (h.equalsIgnoreCase("Time(s)"))
                    continue;

                expDataSet.addSeries(plotTool.createXYSeries("Experimental " + h, expTimeData, expData.get(h)));
            }
        }
    }

    //set labels
    String XAxisLabel = "Time(s)";
    String YAxisLabel = job.headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    Log.info("Creating Graph " + title);
    XYPlot plot = (XYPlot) chart.getPlot();

    if (!job.logAxis) {
        // Determine Y range
        double resMax0 = maxY;
        double resMin0 = minY;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis().setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.000001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.000001;
        if (job.forceZeroYAxisBound && resMin0 >= 0)
            resMin0 = -.000001;
        if (job.forceZeroYAxisBound && resMax0 <= 0)
            resMax0 = .000001;
        rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis();
        if (rangeLength != 0)
            yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly           

        //Add another Y axis to the right side for easier reading
        ValueAxis rightYAxis = new NumberAxis();
        rightYAxis.setRange(yAxis.getRange());
        rightYAxis.setLabel("");

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null) {
                yAxis.setLowerBound(job.Y1LowerBound);
                rightYAxis.setLowerBound(job.Y1LowerBound);
            }
            if (job.Y1UpperBound != null) {
                yAxis.setUpperBound(job.Y1UpperBound);
                rightYAxis.setUpperBound(job.Y1UpperBound);
            }
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }
        plot.setRangeAxis(0, yAxis);
        plot.setRangeAxis(1, rightYAxis);

    } else {
        double resMin = minY;
        double resMax = maxY;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        LogarithmicAxis rightYAxis = new LogarithmicAxis("");
        yAxis.setLowerBound(resMin);
        rightYAxis.setLowerBound(resMin);
        yAxis.setUpperBound(resMax);
        rightYAxis.setUpperBound(resMax);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null) {
                yAxis.setLowerBound(job.Y1LowerBound);
                rightYAxis.setLowerBound(job.Y1LowerBound);
            }
            if (job.Y1UpperBound != null) {
                yAxis.setUpperBound(job.Y1UpperBound);
                rightYAxis.setUpperBound(job.Y1UpperBound);
            }
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }
        plot.setRangeAxis(0, yAxis);
        plot.setRangeAxis(1, rightYAxis);
    }

    //Override X bounds if desired
    try {
        if (job.X1LowerBound != null)
            plot.getDomainAxis(0).setLowerBound(job.X1LowerBound);
        if (job.X1UpperBound != null)
            plot.getDomainAxis(0).setUpperBound(job.X1UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Override labels if desired
    if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN"))
        plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);

    //If we have experimental data, set up the renderer for it and add to plot
    if (expDataSet.getSeriesCount() != 0) {
        XYItemRenderer renderer1 = new XYLineAndShapeRenderer(false, true); // Shapes only
        renderer1.setSeriesShape(0, ShapeUtilities.createDiamond(8));
        plot.setDataset(1, expDataSet);
        plot.setRenderer(1, renderer1);
        plot.mapDatasetToDomainAxis(1, 0);
        plot.mapDatasetToRangeAxis(1, 0);
    }

    formatAEPlot(job, chart);
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);

    //Changing line widths and colors
    XYItemRenderer r = plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(2.0f);
    Color[] AEcolors = { Color.red, Color.green, Color.black, Color.magenta, Color.orange };
    Color[] dataColors = { Color.blue, Color.cyan, Color.gray, Color.black, Color.red };
    for (int i = 0, cIndex = 0; i < dataSet.getSeriesCount(); i++, cIndex++) {
        r.setSeriesStroke(i, wideLine);
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
        renderer.setBaseShapesVisible(false);
        if (cIndex > 4)
            cIndex = 0;
        if (i < job.headers.size()) //Our actual data
        {
            renderer.setSeriesFillPaint(i, dataColors[cIndex]);
            renderer.setSeriesPaint(i, dataColors[cIndex]);
        } else //actions and events in procession of other colors
        {
            renderer.setSeriesFillPaint(i, AEcolors[cIndex]);
            renderer.setSeriesPaint(i, AEcolors[cIndex]);
        }
    }
    //Special color and format changes for compare plots
    if (job.isComparePlot) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

        for (int i = 0; i < dataSet.getSeriesCount(); i++) {
            if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Expected")) {
                renderer.setSeriesStroke(//makes a dashed line
                        i, //argument below float[]{I,K} -> alternates between solid and opaque (solid for I, opaque for K)
                        new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f,
                                new float[] { 15.0f, 30.0f }, 0.0f));
                renderer.setDrawSeriesLineAsPath(true);
                renderer.setUseFillPaint(true);
                renderer.setBaseShapesVisible(false);
                renderer.setSeriesFillPaint(i, Color.black);
                renderer.setSeriesPaint(i, Color.black);
            }
            if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Computed")) {
                renderer.setSeriesFillPaint(i, Color.red);
                renderer.setSeriesPaint(i, Color.red);
            }
            if (dataSet.getSeries(i).getKey().toString().startsWith("ACTION")) {
                renderer.setSeriesFillPaint(i, Color.green);
                renderer.setSeriesPaint(i, Color.green);
            }
            if (dataSet.getSeries(i).getKey().toString().startsWith("EVENT")) {
                renderer.setSeriesFillPaint(i, Color.blue);
                renderer.setSeriesPaint(i, Color.blue);
            }
        }
    }

    //Split the auto-generated legend into two legends, one for data and one for actions and events
    LegendItemCollection originalLegendCollection = plot.getLegendItems();
    final LegendItemCollection dataLegendCollection = new LegendItemCollection();
    int i;
    for (i = 0; i < job.headers.size() && i < originalLegendCollection.getItemCount(); i++) {
        if (originalLegendCollection.get(i).getLabel().startsWith("ACTION")
                || originalLegendCollection.get(i).getLabel().startsWith("EVENT"))
            break;
        dataLegendCollection.add(originalLegendCollection.get(i));
    }
    final LegendItemCollection remainingLegendCollection = new LegendItemCollection();
    for (; i < originalLegendCollection.getItemCount(); i++) {
        remainingLegendCollection.add(originalLegendCollection.get(i));
    }
    chart.removeLegend();
    LegendItemSource source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(dataLegendCollection);
        }

        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };
    LegendTitle dataLegend = new LegendTitle(source);
    dataLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    dataLegend.setBorder(2, 2, 2, 2);
    dataLegend.setBackgroundPaint(Color.white);
    dataLegend.setPosition(RectangleEdge.TOP);
    dataLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22));
    chart.addLegend(dataLegend);

    source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(remainingLegendCollection);
        }

        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };
    LegendTitle actionEventsLegend = new LegendTitle(source);
    actionEventsLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    actionEventsLegend.setBorder(2, 2, 2, 2);
    actionEventsLegend.setBackgroundPaint(Color.white);
    actionEventsLegend.setPosition(RectangleEdge.BOTTOM);
    actionEventsLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22));
    if (!job.hideAELegend && !job.removeAllLegends)
        chart.addLegend(actionEventsLegend);

    if (job.removeAllLegends)
        chart.removeLegend();

    int verticalPixels = 800 + 170 * (allActionsAndEvents.size() / 5);

    //This is a little hacky, but if we want only the legend, just extend Plot() and remove the draw functionality so it makes a blank plot
    class legendPlot extends Plot {
        public void draw(Graphics2D arg0, Rectangle2D arg1, Point2D arg2, PlotState arg3,
                PlotRenderingInfo arg4) {

        }

        public String getPlotType() {
            return null;
        }
    }
    //Then add the legend to that and throw away the original plot
    if (job.legendOnly) {
        chart = new JFreeChart("", null, new legendPlot(), false);
        chart.addLegend(actionEventsLegend);
    }

    try {
        FileUtils.createDirectory(job.outputDir);
        String filename = job.outputFilename == null
                ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg"
                : job.outputDir + "/" + job.outputFilename;
        if (!filename.endsWith(".jpg"))
            filename = filename + ".jpg";
        File JPGFile = new File(filename);
        if (job.imageHeight != null && job.imageWidth != null)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight);
        else if (!job.hideAELegend && !job.removeAllLegends)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, verticalPixels);
        else
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }
}

From source file:org.yccheok.jstock.charting.Utils.java

/**
 * Returns monthly chart data based on given stock history server.
 *
 * @param stockHistoryServer the stock history server
 * @return list of monthly chart data//  w w  w .  j a  v a2s.c om
 */
public static List<ChartData> getMonthlyChartData(StockHistoryServer stockHistoryServer) {
    final int days = stockHistoryServer.size();
    Calendar prevCalendar = null;

    List<ChartData> chartDatas = new ArrayList<ChartData>();

    double prevPrice = 0;
    double openPrice = 0;
    double lastPrice = 0;
    double highPrice = Double.MIN_VALUE;
    double lowPrice = Double.MAX_VALUE;
    long volume = 0;
    long timestamp = 0;
    int count = 0;

    for (int i = 0; i < days; i++) {
        // First, determine the current data is same month as the previous
        // data.
        boolean isSameMonth = false;
        final long t = stockHistoryServer.getTimestamp(i);
        Stock stock = stockHistoryServer.getStock(t);

        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(t);

        if (prevCalendar != null) {
            int month = calendar.get(Calendar.MONTH);
            int prevMonth = prevCalendar.get(Calendar.MONTH);
            // Is this the same month?
            isSameMonth = (month == prevMonth);
        } else {
            // First time for us to enter this for loop.
            isSameMonth = true;
            openPrice = stock.getOpenPrice();
            prevPrice = stock.getPrevPrice();
        }

        if (isSameMonth == false) {
            // This is a new month. There must be data for previous month.
            assert (count > 0);
            ChartData chartData = ChartData.newInstance(prevPrice, openPrice, lastPrice / count, // Average last price.
                    highPrice, lowPrice, volume / count, // Average volume.
                    timestamp);
            chartDatas.add(chartData);

            // First day of the month.
            prevPrice = stock.getPrevPrice();
            openPrice = stock.getOpenPrice();
            lastPrice = stock.getLastPrice();
            highPrice = stock.getHighPrice();
            lowPrice = stock.getLowPrice();
            volume = stock.getVolume();
            timestamp = stock.getTimestamp();
            count = 1;
        } else {
            // We will not update prevPrice and openPrice. They will remain
            // as the first day of the month's.
            lastPrice += stock.getLastPrice();
            highPrice = Math.max(highPrice, stock.getHighPrice());
            lowPrice = Math.min(lowPrice, stock.getLowPrice());
            volume += stock.getVolume();
            timestamp = stock.getTimestamp();
            count++;
        }

        prevCalendar = calendar;
    }

    // Is there any data which is not being inserted yet?
    if (count > 0) {
        ChartData chartData = ChartData.newInstance(prevPrice, openPrice, lastPrice / count, highPrice,
                lowPrice, volume / count, timestamp);
        chartDatas.add(chartData);
    }

    return chartDatas;
}

From source file:ch.aonyx.broker.ib.api.order.PlaceOrderRequest.java

private void checkOrderComboLegsSupport() {
    if (contract.getSecurityType().equals(SecurityType.COMBO)) {
        final List<OrderComboLeg> orderComboLegs = order.getOrderComboLegs();
        if (!orderComboLegs.isEmpty()) {
            for (final OrderComboLeg orderComboLeg : orderComboLegs) {
                if (orderComboLeg.getPrice() != Double.MAX_VALUE) {
                    if (!Feature.ORDER_COMBO_LEGS_PRICE.isSupportedByVersion(getServerCurrentVersion())) {
                        throw new RequestException(ClientMessageCode.UPDATE_TWS,
                                "It does not support per-leg prices for order combo legs.", this);
                    }/*  w  w  w.  ja v a  2  s.c o m*/
                }
            }
        }
    }
}

From source file:edu.utexas.cs.tactex.utilityestimation.UtilityArchitectureActionGenerator.java

private double findMinConsumptionAvgRate(Set<TariffSpecification> myExistingTariffs) {
    double minAvgRate = -Double.MAX_VALUE;
    for (TariffSpecification spec : myExistingTariffs) {
        if (spec.getPowerType() == PowerType.CONSUMPTION) {
            double avgRate = computeAvgRate(spec);
            if (avgRate > minAvgRate) { // note signs
                minAvgRate = avgRate;/*from   w w w. j  ava2  s .  co m*/
            }
        }
    }
    return minAvgRate;
}

From source file:Imputers.KnniLDProb.java

private double sdist(byte[] v1, byte[] v2, int[] s) {
    int d = 0;//from  w ww.  j a  v  a 2s  .com
    int c = 0;
    // Use the l most similar ones to calculate the distance
    for (int j = 0; j < l; j++) {
        int i = s[j];
        int p1 = v1[i];
        int p2 = v2[i];
        if ((p1 != -1) && (p2 != -1)) {
            // c counts how many snps we've actually used to scale the
            // distance with since some snps will be unknown
            c++;
            d += Math.abs(p1 - p2);
        }
    }
    // If across the l most similar snps there wasn't a single case
    // where both samples had a known genotype then set the distance to
    // max
    if (c == 0) {
        return Double.MAX_VALUE - 1;
    }
    //Else return the scaled distance (adding one so we don't have a
    //distance of zero as that caused problems later.
    else {
        return ((double) d * (double) l / (double) c) + 1.0;
    }
}

From source file:ch.epfl.lsir.xin.algorithm.core.MatrixFactorization.java

/**
 * This function learns a matrix factorization model using Alternative Least Square  
 * refer to "Large-scale Parallel Collaborative Filtering for the Netix Prize"
 * *//*from  w w  w. ja  va  2 s.  c o m*/
public void buildALS() {
    double preError = Double.MAX_VALUE;
    Matrix identify = Matrix.identity(this.latentFactors, this.latentFactors);
    for (int i = 0; i < this.Iterations; i++) {
        System.out.println("Iteration: " + i);
        double error = 0; //overall error of this iteration
        //fix item matrix M, solve user matrix U
        for (int j = 0; j < this.userMatrix.getRows(); j++) {
            //latent factor of items that are rated by user j
            int n = this.ratingMatrix.getUserRatingNumber(j);//number of items rated by user j
            double[][] m = new double[n][this.latentFactors];
            int index = 0;
            for (int k = 0; k < this.itemMatrix.getRows(); k++) {
                if (!Double.isNaN(this.ratingMatrix.get(j, k))) {
                    m[index++] = this.itemMatrix.getRowValues(k);
                }
            }
            Matrix M = new Matrix(m);
            //step 1:
            Matrix A = M.transpose().times(M).plus(identify.times(this.regUser).times(n));
            //step 2:
            double[][] r = new double[1][n];//ratings of this user
            int index1 = 0;
            for (int k = 0; k < this.ratingMatrix.getColumn(); k++) {
                Double rating = this.ratingMatrix.getRatingMatrix().get(j).get(k);
                if (rating != null) {
                    r[0][index1++] = rating.doubleValue();
                }
            }
            Matrix R = new Matrix(r);
            Matrix V = M.transpose().times(R.transpose());
            //step 3: the updated user matrix wrt user j
            Matrix uj = A.inverse().times(V);
            this.userMatrix.getValues()[j] = uj.transpose().getArray()[0];
        }
        //fix user matrix U, solve item matrix M
        for (int j = 0; j < this.itemMatrix.getRows(); j++) {
            //latent factor of users that have rated item j
            int n = this.ratingMatrix.getItemRatingNumber(j);//number of users rate item j
            double[][] u = new double[n][this.latentFactors];
            int index = 0;
            for (int k = 0; k < this.userMatrix.getRows(); k++) {
                if (!Double.isNaN(this.ratingMatrix.get(k, j))) {
                    u[index++] = this.userMatrix.getRowValues(k);
                }
            }
            if (u.length == 0)
                continue;
            Matrix U = new Matrix(u);

            //step 1:
            Matrix A = U.transpose().times(U).plus(identify.times(this.regItem).times(n));

            //step 2:
            double[][] r = new double[1][n];//ratings of this item
            int index1 = 0;
            for (int k = 0; k < this.ratingMatrix.getRow(); k++) {
                Double rating = this.ratingMatrix.getRatingMatrix().get(k).get(j);
                if (rating != null) {
                    r[0][index1++] = rating.doubleValue();
                }
            }
            Matrix R = new Matrix(r);
            Matrix V = U.transpose().times(R.transpose());
            //step 3: the updated item matrix wrt item j
            Matrix mj = A.inverse().times(V);
            this.itemMatrix.getValues()[j] = mj.transpose().getArray()[0];
        }
        //check for convergence
        //error
        ArrayList<MatrixEntry2D> entries = this.ratingMatrix.getValidEntries();
        for (int k = 0; k < entries.size(); k++) {
            MatrixEntry2D entry = entries.get(k);
            double prediction = predict(entry.getRowIndex(), entry.getColumnIndex(), false);
            if (prediction > this.maxRating)
                prediction = this.maxRating;
            if (prediction < this.minRating)
                prediction = this.minRating;
            error = error + Math.abs(entry.getValue() - prediction);
            for (int j = 0; j < this.latentFactors; j++) {
                error = error + this.regUser / 2 * Math.pow(this.userMatrix.get(entry.getRowIndex(), j), 2)
                        + this.regItem / 2 * Math.pow(this.itemMatrix.get(entry.getColumnIndex(), j), 2);
            }
        }

        this.logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Iteration " + i
                + " : Error ~ " + error);
        this.logger.flush();
        //check for convergence
        if (Math.abs(error - preError) <= this.convergence && error <= preError) {
            logger.println("The algorithm convergences.");
            this.logger.flush();
            break;
        }

        preError = error;
        logger.flush();
    }
}