Example usage for org.jfree.data.xy XYSeriesCollection getSeriesCount

List of usage examples for org.jfree.data.xy XYSeriesCollection getSeriesCount

Introduction

In this page you can find the example usage for org.jfree.data.xy XYSeriesCollection getSeriesCount.

Prototype

@Override
public int getSeriesCount() 

Source Link

Document

Returns the number of series in the collection.

Usage

From source file:whitebox.stats.Kriging.java

/**
 * Draw Semivariogram surface map and also draw the search are if
 * Anisotropic//from  w w w .jav  a2 s. c  om
 *
 * @param Radius
 * @param AnIsotropic
 */
public void DrawSemivariogramSurface(double Radius, boolean AnIsotropic) {
    double[][] data = new double[3][BinSurface.length * BinSurface[0].length];
    int n = 0;
    double max = Double.MIN_VALUE;
    for (int i = 0; i < BinSurface.length; i++) {
        for (int j = 0; j < BinSurface[i].length; j++) {
            data[0][n] = BinSurface[i][j].GridHorDistance;
            data[1][n] = BinSurface[i][j].GridVerDistance;
            if ((Math.pow(data[0][n], 2) + Math.pow(data[1][n], 2)) <= Radius * Radius
                    && !Double.isNaN(BinSurface[i][j].Value)) {
                data[2][n] = BinSurface[i][j].Value;
                if (max < data[2][n]) {
                    max = data[2][n];
                }
            } else {
                data[2][n] = -1;
            }
            n++;
        }
    }
    DefaultXYZDataset dataset = new DefaultXYZDataset();
    dataset.addSeries("Value", data);
    NumberAxis xAxis = new NumberAxis();

    xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    xAxis.setLowerMargin(0.0);
    xAxis.setUpperMargin(0.0);
    NumberAxis yAxis = new NumberAxis();
    yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    yAxis.setLowerMargin(0.0);
    yAxis.setUpperMargin(0.0);
    XYBlockRenderer renderer = new XYBlockRenderer();
    renderer.setBlockWidth(LagSize);
    renderer.setBlockHeight(LagSize);
    renderer.setBlockAnchor(RectangleAnchor.CENTER);

    LookupPaintScale paintScale = new LookupPaintScale(0, max, Color.white);
    double colorRange = max / 6;
    //double colorRange = 23013;
    paintScale.add(0.0, Color.blue);
    paintScale.add(1 * colorRange, Color.green);
    paintScale.add(2 * colorRange, Color.cyan);
    paintScale.add(3 * colorRange, Color.yellow);
    paintScale.add(4 * colorRange, Color.ORANGE);
    paintScale.add(5 * colorRange, Color.red);

    renderer.setPaintScale(paintScale);

    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(false);
    plot.setRangeGridlinePaint(Color.white);

    if (AnIsotropic) {
        CombinedRangeXYPlot combinedrangexyplot = new CombinedRangeXYPlot();
        XYSeries seriesT1 = new XYSeries("1");
        XYSeriesCollection AngleCollct = new XYSeriesCollection();

        double bw = BandWidth;
        double r = bw / Math.sin(Tolerance);
        if (r > Radius) {
            bw = Radius * Math.sin(Tolerance);
            r = Radius;
        }
        seriesT1.add(r * Math.cos(Angle + Tolerance), r * Math.sin(Angle + Tolerance));

        if ((double) Math.round(Math.sin(Angle) * 10000) / 10000 != 0) {
            if ((double) Math.round(Math.cos(Angle) * 10000) / 10000 != 0) {
                double a = (1 + Math.pow(Math.tan(Angle), 2));
                double b = 2 * bw / Math.sin(Angle) * Math.pow(Math.tan(Angle), 2);
                double c = Math.pow(Math.tan(Angle), 2) * Math.pow(bw / Math.sin(Angle), 2)
                        - Math.pow(Radius, 2);
                double x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
                double y1 = Math.tan(Angle) * (x1 + bw / Math.sin(Angle));
                double x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
                double y2 = Math.tan(Angle) * (x2 + bw / Math.sin(Angle));
                double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));
                double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y2), 2)));
                if (d1 < d2) {
                    seriesT1.add(x1, y1);
                } else {
                    seriesT1.add(x2, y2);
                }
            } else {
                double x1 = -bw * Math.sin(Angle);
                double y1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2));
                double y2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2));
                double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));
                double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y2), 2)));

                if (d1 < d2) {
                    seriesT1.add(x1, y1);
                } else {
                    seriesT1.add(x1, y2);
                }
            }
        } else {
            double y1 = bw * Math.cos(Angle);
            double x1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2));
            double x2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2));
            double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                    + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));
            double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2))
                    + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));

            if (d1 < d2) {
                seriesT1.add(x1, y1);
            } else {
                seriesT1.add(x2, y1);
            }
        }

        AngleCollct.addSeries(seriesT1);

        XYSeries seriesT2 = new XYSeries("2");
        seriesT2.add(r * Math.cos(Angle + Tolerance), r * Math.sin(Angle + Tolerance));
        seriesT2.add(0.0, 0.0);
        AngleCollct.addSeries(seriesT2);

        XYSeries seriesT3 = new XYSeries("3");
        seriesT3.add(Radius * Math.cos(Angle), Radius * Math.sin(Angle));
        seriesT3.add(0, 0);
        AngleCollct.addSeries(seriesT3);

        XYSeries seriesT4 = new XYSeries("4");
        seriesT4.add(r * Math.cos(Angle - Tolerance), r * Math.sin(Angle - Tolerance));
        seriesT4.add(0, 0);
        AngleCollct.addSeries(seriesT4);

        XYSeries seriesT5 = new XYSeries("5");

        seriesT5.add(r * Math.cos(Angle - Tolerance), r * Math.sin(Angle - Tolerance));
        if ((double) Math.round(Math.sin(Angle) * 10000) / 10000 != 0) {
            if ((double) Math.round(Math.cos(Angle) * 10000) / 10000 != 0) {
                double a = (1 + Math.pow(Math.tan(Angle), 2));
                double b = -2 * bw / Math.sin(Angle) * Math.pow(Math.tan(Angle), 2);
                double c = Math.pow(Math.tan(Angle), 2) * Math.pow(bw / Math.sin(Angle), 2)
                        - Math.pow(Radius, 2);
                double x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
                double y1 = Math.tan(Angle) * (x1 - bw / Math.sin(Angle));
                double x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
                double y2 = Math.tan(Angle) * (x2 - bw / Math.sin(Angle));
                double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));
                double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y2), 2)));
                if (d1 < d2) {
                    seriesT5.add(x1, y1);
                } else {
                    seriesT5.add(x2, y2);
                }
            } else {
                double x1 = bw * Math.sin(Angle);
                double y1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2));
                double y2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2));
                double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));
                double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                        + (Math.pow((Radius * Math.sin(Angle) - y2), 2)));

                if (d1 < d2) {
                    seriesT5.add(x1, y1);
                } else {
                    seriesT5.add(x1, y2);
                }
            }
        } else {
            double y1 = -bw * Math.cos(Angle);
            double x1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2));
            double x2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2));
            double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2))
                    + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));
            double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2))
                    + (Math.pow((Radius * Math.sin(Angle) - y1), 2)));

            if (d1 < d2) {
                seriesT5.add(x1, y1);
            } else {
                seriesT5.add(x2, y1);
            }
        }
        AngleCollct.addSeries(seriesT5);
        plot.setDataset(1, AngleCollct);
        XYLineAndShapeRenderer lineshapRend = new XYLineAndShapeRenderer(true, false);
        for (int i = 0; i < AngleCollct.getSeriesCount(); i++) {
            //plot.getRenderer().setSeriesPaint(i , Color.BLUE);
            lineshapRend.setSeriesPaint(i, Color.BLACK);
        }
        plot.setRenderer(1, lineshapRend);
        combinedrangexyplot.add(plot);
    }
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    JFreeChart chart = new JFreeChart("Semivariogram Surface", plot);
    chart.removeLegend();
    chart.setBackgroundPaint(Color.white);

    // create and display a frame...
    ChartFrame frame = new ChartFrame("", chart);
    frame.pack();
    //frame.setSize(100, 50);
    frame.setVisible(true);
}

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

public void createGraph(PlotJob job, Map<String, List<Double>> PFTData, Map<String, 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 < job.headers.size(); i++) {
        title = title + job.headers.get(i) + "_";
        XYSeries dataSeries;/*from w  w  w.  j  ava 2  s . c o m*/
        dataSeries = plotTool.createXYSeries(job.headers.get(i), data.get("Time(s)"),
                data.get(job.headers.get(i)));
        dataSet.addSeries(dataSeries);
        maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
        minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;
    }

    //Now make a data series for PFT data and check its max and min
    XYSeries dataSeries = plotTool.createXYSeries("PFT Total Lung Volume (mL)", PFTData.get("Time"),
            PFTData.get("Volume"));
    dataSet.addSeries(dataSeries);
    maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
    minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;

    title = title + "vs_Time";

    //Override the constructed title if desired
    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));
    }

    //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(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);
        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);

    formatRPFTPlot(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]);
        }
    }

    //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);

    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.fhcrc.cpl.viewer.gui.SpectrumComponent.java

/**
 * update the chart with new data//  w w  w .jav  a  2  s  . c  o m
 */
public void updateChart(boolean preserveDomain) {
    _log.debug("updateChart: start");
    float[][] spectrumIN = null;
    MSRun run = (MSRun) ApplicationContext.getProperty(SharedProperties.MS_RUN);
    MSRun.MSScan selectedScan = getSelectedScan();

    FloatRange rangeSpectrum = null; // restricted range of displayed data (for autoZoom)
    Pair<Spectrum.Peak, Spectrum.Peak> chartRange = null; // tell other components what we are displaying

    Range domainRange = null;
    if (preserveDomain && _chart != null)
        domainRange = _chart.getXYPlot().getDomainAxis().getRange();

    if (null == run || null == selectedScan) {
        clearChart();
        //if no chart to display, show white background
        chartArea.setBackground(java.awt.Color.WHITE);
        return;
    }

    chartArea.setBackground(_backgroundColor);

    if ("scan".equals(_type)) {
        scanSpinner.setValue(new Integer(selectedScan.getNum()));
        double t = selectedScan.getDoubleRetentionTime();
        timeTextField.setText("" + Math.round(t * 10) / 10.0);
        scanSpinner.setEnabled(true);
        //mzTextField.setText("");
        //mzTextField.setEnabled(false);
        mzSpinner.setValue(new Double(_selectedMZ));
        mzSpinner.setEnabled(false);

        /*         ArrayList l = new ArrayList();
                 l.add(selectedScan.getSpectrum());
                    spectrumIN = Spectrum.CombineRawSpectra(
            run.getTemplateSpectrum(),
            l,
            new FloatRange(selectedScan.getLowMz(),selectedScan.getHighMz())
            ); */

        spectrumIN = selectedScan.getSpectrum();

        if (autoZoom()) {
            // we don't want to filter the analyzed data, in case
            // that affects any of the algorithms
            // we only filter the result Datasets
            // UNDONE: choose range based on size of MSDetailPanel

            // range of 27+ is enough to see 4 ICAT labelled features (9*(4-1))
            rangeSpectrum = new FloatRange((float) _selectedMZ - 10F, (float) _selectedMZ + 30F);
        }

        if (null == rangeSpectrum) {
            chartRange = new Pair<Spectrum.Peak, Spectrum.Peak>(
                    new Spectrum.Peak(_selectedScanNum, spectrumIN[0][0], 0.0F),
                    new Spectrum.Peak(_selectedScanNum, spectrumIN[0][spectrumIN[0].length - 1]));
        } else {
            chartRange = new Pair<Spectrum.Peak, Spectrum.Peak>(
                    new Spectrum.Peak(_selectedScanNum, rangeSpectrum.min, 0.0F),
                    new Spectrum.Peak(_selectedScanNum, rangeSpectrum.max, 0.0F));
        }
    } else // elution
    {
        if (_selectedMZ == -1) {
            clearChart();
            return;
        }

        int RESAMPLE = 36;
        float mz = (float) Math.round(_selectedMZ * RESAMPLE) / RESAMPLE;
        _log.debug("updateChart mz=" + mz);

        scanSpinner.setValue(new Integer(selectedScan.getNum()));
        scanSpinner.setEnabled(false);
        double t = selectedScan.getDoubleRetentionTime();
        timeTextField.setText("" + Math.round(t * 10) / 10.0);
        //mzTextField.setText("" + mz);
        //mzTextField.setEnabled(true);
        mzSpinner.setValue(new Double(_selectedMZ));
        mzSpinner.setEnabled(true);

        FloatArray arrayIntensity = new FloatArray();
        FloatArray arrayScan = new FloatArray();
        int scanIndex = run.getIndexForScanNum(selectedScan.getNum());
        int scanStart = Math.max(0, scanIndex - 64);
        int scanEnd = Math.min(run.getScanCount() - 1, scanStart + 128);
        FloatRange r = new FloatRange(mz, mz);
        for (int s = scanStart; s < scanEnd; s++) {
            MSRun.MSScan scan = run.getScan(s);
            float[][] spectrumRaw = scan.getSpectrum();
            float[] resample = Spectrum.Resample(spectrumRaw, r, RESAMPLE);
            float f = resample[0];
            arrayIntensity.add(f);
            //arrayScan.add((float)scan.getDoubleRetentionTime());
            //            arrayScan.add((float)s);
            arrayScan.add((float) scan.getNum());
        }
        spectrumIN = new float[][] { arrayScan.toArray(null), arrayIntensity.toArray(null) };

        chartRange = new Pair<Spectrum.Peak, Spectrum.Peak>(
                new Spectrum.Peak(run.getScan(scanStart).getNum(), mz, 0.0F),
                new Spectrum.Peak(run.getScan(scanEnd).getNum(), mz, 0.0F));
    }

    String mode = (String) displayMode.getSelectedItem();

    java.util.List<XYSeriesCollection> listMultipleCharts = null;
    XYSeriesCollection series = new XYSeriesCollection();
    series.setIntervalWidth(0.0);

    //
    // Process source spectrum
    //

    float[][] spectrum = new float[][] { (float[]) spectrumIN[0].clone(), (float[]) spectrumIN[1].clone() };
    ProcessSpectrum: {
        if ("raw".equals(mode)) {
            break ProcessSpectrum;
        }

        if ("background centroided".equals(mode)) {
            if (run.getHeaderInfo().getDataProcessing().getCentroided() == 1)
                spectrum = FeatureStrategyCentroided.backgroundSpectrum(spectrum);
            break ProcessSpectrum;
        }

        if ("clean centroided".equals(mode)) {
            if (run.getHeaderInfo().getDataProcessing().getCentroided() == 1)
                spectrum = FeatureStrategyCentroided.cleanSpectrum(spectrum);
            break ProcessSpectrum;
        }

        // all subsequent processing expects resampling
        // don't resample elution profile
        if ("scan".equals(_type)) {
            int len = spectrum[0].length;
            spectrum = Spectrum.ResampleSpectrum(spectrumIN,
                    new FloatRange((float) Math.floor(spectrum[0][0]), (float) Math.ceil(spectrum[0][len - 1])),
                    36, false);
        } else {
            spectrum[1] = Spectrum.MedianSmooth(spectrum[1]);
            Spectrum.SmoothALittle(spectrum[1]);
        }

        if ("resampled".equals(mode))
            break ProcessSpectrum;

        /*         if ("compressed".equals(mode)) (data encoding test)
                    {
                    float[] s = spectrum[1];
                    short c[] = new short[s.length];
                    double m = 1.0;
                    for (int i = 0 ; i<c.length ; i++)
                       m = Math.max(m, s[i]);
                    double sqrt = Math.sqrt(m+1);
                    m = Math.round(Math.log(sqrt))+1;
                    double f = Math.floor(0x7fff / Math.log(sqrt));
                    m = 0;
                    for (int i = 0 ; i<c.length ; i++)
                       {
                       c[i] = (short)(Math.round(Math.log((s[i]+1)/sqrt) * f));
                       m = Math.max(m, Math.abs(c[i]));
                       }
                    System.err.println("MAX " + m);
                    for (int i = 0 ; i<c.length ; i++)
                       s[i] = (float)((Math.exp((double)c[i]/f) * sqrt) - 1);
                    break ProcessSpectrum;
                    } */

        // remove background for further processing
        if (run.getHeaderInfo().getDataProcessing().getCentroided() != 1) {
            int window = "scan".equals(_type) ? 72 : 15;
            float x[] = spectrum[1];
            float bg[] = Spectrum.MinimaWindow(x, spectrum[0].length, window, null);
            for (int i = 0; i < bg.length; i++)
                bg[i] = Math.max(0, x[i] - bg[i]);
            spectrum = new float[][] { spectrum[0], bg };
        }

        if ("subtract background".equals(mode))
            break ProcessSpectrum;

        if (mode.startsWith("threshold")) {
            spectrum[1] = Spectrum.WaveletD3(spectrum[1], null);
            break ProcessSpectrum;
        }

        if ("peaks".equals(mode) || "smoothed".equals(mode)) {
            if ("scan".equals(_type)) {
                double s = Smooth2D.smoothYfactor;
                spectrum[1] = Spectrum.FFTsmooth(spectrum[1], s, false);
            } else {
                //FeatureStrategyPeakClusters.smoothTHRESHOLD sm = new FeatureStrategyPeakClusters.smoothTHRESHOLD();
                spectrum[1] = SmootherCreator._thresholdElution(spectrum[1]);
            }
            break ProcessSpectrum;
        }
    } // ProcessSpectrum:

    //
    // This is the source spectrum
    //

    String name = mode.indexOf("peaks") != -1 ? "-spectrum" : "|spectrum";
    series.addSeries(new SpectrumXYSeries(name, spectrum, rangeSpectrum));
    _spectrum = spectrum;

    //
    // add additional series/charts
    //

    // show min/med for reference
    if (mode.equals("resampled") || mode.equals("subtract background")) {
        float[] T;
        if (mode.equals("resampled")) {
            T = Spectrum.MinimaWindow(spectrum[1], spectrum[0].length, 72, null);
            series.addSeries(new SpectrumXYSeries("-min", new float[][] { spectrum[0], T }, rangeSpectrum));
        }
        T = Spectrum.MedianWindow(spectrum[1], spectrum[0].length, 72, false);
        series.addSeries(new SpectrumXYSeries("-med", new float[][] { spectrum[0], T }, rangeSpectrum));
    }

    if (mode.startsWith("wavelet decomposition") || mode.startsWith("wavelet multiresolution")) {
        Filter f = new Filter("haar");
        float[] signal = spectrum[1]; // Spectrum.PadToDouble(spectrum[1], 32);
        int N = spectrum[0].length; // signal.length;
        int levels = 5;

        //if ("wavelet decomposition 2".equals(mode)) Spectrum.SmoothALittle(signal);

        float[][] modwt1 = Transform.decompose(signal, N, levels, f, "modwt", "periodic", null);
        float[][] t = modwt1;

        if ("wavelet multiresolution".equals(mode)) {
            t = Transform.multiresolution(t, N, levels, f, "modwt", "periodic", null);
        } else if ("wavelet decomposition 2".equals(mode)) {
            float[][] mra = Transform.multiresolution(t, N, levels, f, "modwt", "periodic", null);
            float[][] modwt2 = Transform.decompose(t[2], N, levels, f, "modwt", "periodic", null);
            // show original, d1, and d2
            float[] a = modwt1[2];
            float[] b = modwt2[2];
            float[] m = mra[2];
            Spectrum.Rotate(a, -3);
            Spectrum.Rotate(b, -7);
            t = new float[][] { a, /*b,*/ m }; // b is a mirror image of m
        }

        // copy array into data series
        listMultipleCharts = new java.util.LinkedList<XYSeriesCollection>();
        XYSeriesCollection ds = new XYSeriesCollection(
                new SpectrumXYSeries("spectrum", spectrum, rangeSpectrum));
        ds.setIntervalWidth(0.0);
        listMultipleCharts.add(ds);
        for (int i = 0; i < t.length; i++) {
            //float[] s = Spectrum.UnpadToFloat(t[i], 32, null);
            float[][] l = new float[][] { spectrum[0], t[i] };
            ds = new XYSeriesCollection(new SpectrumXYSeries("level " + (i + 1), l, rangeSpectrum));
            ds.setIntervalWidth(0.0);
            listMultipleCharts.add(ds);
        }
    } else if (mode.startsWith("haar")) {
        int l = Integer.parseInt(mode.substring(4));
        listMultipleCharts = new LinkedList<XYSeriesCollection>();

        float[] t1 = Haar.transform(spectrum[1], l);
        float[] t2 = Haar.transform(t1, l);
        XYSeriesCollection ds = new XYSeriesCollection(
                new SpectrumXYSeries("spectrum", spectrum, rangeSpectrum));
        ds.setIntervalWidth(0.0);
        listMultipleCharts.add(ds);
        XYSeriesCollection ds1 = new XYSeriesCollection(
                new SpectrumXYSeries(mode, new float[][] { spectrum[0], t1 }, rangeSpectrum));
        ds1.setIntervalWidth(0.0);
        listMultipleCharts.add(ds1);
        XYSeriesCollection ds2 = new XYSeriesCollection(
                new SpectrumXYSeries(mode, new float[][] { spectrum[0], t2 }, rangeSpectrum));
        ds2.setIntervalWidth(0.0);
        listMultipleCharts.add(ds2);
    } else if ("peaks".equals(mode) || "threshold peaks".equals(mode)) {
        double noise = 0.1; //"peaks".equals(mode) ? 2.0 : 1.0; // Spectrum.Noise(spectrum[1], 0, spectrum[1].length);
        int[] peakList = Spectrum.PickPeakIndexes(spectrum[1], noise);

        float[][] peaks = new float[2][peakList.length];
        for (int i = 0; i < peakList.length; i++) {
            int p = peakList[i];
            if (p >= spectrum[0].length)
                continue;
            peaks[0][i] = spectrum[0][p];
            peaks[1][i] = spectrum[1][p];
        }
        series.addSeries(new SpectrumXYSeries("|peaks", peaks, rangeSpectrum));
        _spectrum = peaks;
    } else if ("wavelet peaks".equals(mode)) {
        //Spectrum.Peak[] peaks = Spectrum.WaveletPeaks(spectrum);
        Spectrum.Peak[] peaks = Spectrum.WaveletPeaksD3(spectrum);
        float[][] peakSpectrum = new float[2][peaks.length];
        for (int p = 0; p < peaks.length; p++) {
            peakSpectrum[0][p] = peaks[p].mz;
            peakSpectrum[1][p] = peaks[p].intensity;
        }

        // show d3 and thresholded spectrum
        int levels = 3, N = spectrum[0].length;
        Filter f = new Filter("haar");
        float[][] modwt = Transform.decompose(spectrum[1], N, levels, f, "modwt", "periodic", null);
        float[][] mra = Transform.multiresolution(modwt, N, levels, f, "modwt", "periodic", null);
        float[] thresholded = new float[N];
        for (int i = 0; i < N; i++)
            thresholded[i] = mra[2][i] + mra[3][i];

        series.removeAllSeries();
        //series.addSeries(new SpectrumXYSeries("-spectrum", new float[][] {spectrum[0],thresholded}, rangeSpectrum));
        series.addSeries(new SpectrumXYSeries("-mra", new float[][] { spectrum[0], mra[2] }, rangeSpectrum));
        series.addSeries(new SpectrumXYSeries("|peaks", peakSpectrum, rangeSpectrum));
        _spectrum = peakSpectrum;
    }

    //
    // now update or create chart
    //

    Color[] colors = series.getSeriesCount() == 3 ? new Color[] { Color.RED, Color.BLUE, Color.BLUE }
            : series.getSeriesCount() == 2 ? new Color[] { Color.BLUE, Color.RED } : new Color[] { Color.RED };

    // NOTE: the more often we call setDatasets instead of creating new chart the better
    // CONSIDER: if we don't save chart, at least preserve zoom settings
    if (false && _chart != null && _chartPanel != null && !(_chart.getPlot() instanceof CombinedDomainXYPlot)
            && listMultipleCharts == null) {
        SpectrumChartFactory.setColors(_chartPanel, colors);
        _chart.getXYPlot().setDataset(series);
        _chartPanel.updateUI();
    } else {
        if (listMultipleCharts == null) {
            _log.debug(
                    "updateChart: series=" + series.getSeriesCount() + " length(0)=" + series.getItemCount(0));
            _chartPanel = SpectrumChartFactory.CreateChartPanel(series, colors);
        } else {
            _log.debug("updateChart: charts=" + listMultipleCharts.size());
            _chartPanel = SpectrumChartFactory.CreateChartPanel(listMultipleCharts, colors);
        }
        _chart = _chartPanel.getChart();

        // there seem to be mystery margins so give a little extra space
        Dimension size = chartArea.getSize();
        _chartPanel.setPreferredSize(new Dimension(size.width - 10, size.height - 10));
        chartArea.removeAll();
        chartArea.add(_chartPanel);
        chartArea.doLayout();
    }
    if (null != domainRange)
        _chart.getXYPlot().getDomainAxis().setRange(domainRange);

    //dhmay: if the user has locked the Y axis, then try to use the stored Y axis range
    if (isYAxisLocked()) {
        //a locked axis value won't be available if the axis was _just_ locked
        if (null == _lockedYAxisRange) {
            //if we've already displayed a chart, use that chart's axis range.  Otherwise,
            //don't force, and record this chart's axis range
            if (_previousYAxisRange != null)
                _lockedYAxisRange = _previousYAxisRange;
            else
                _lockedYAxisRange = _chart.getXYPlot().getRangeAxis().getRange();
        }
        _chart.getXYPlot().getRangeAxis().setRange(_lockedYAxisRange);
    } else {
        //if the Y axis isn't locked, then dump the stored range so it isn't used later
        _lockedYAxisRange = null;
    }

    //always store the previous Y axis range
    if (_chart.getXYPlot() != null && _chart.getXYPlot().getRangeAxis() != null
            && _chart.getXYPlot().getRangeAxis().getRange() != null) {
        _previousYAxisRange = _chart.getXYPlot().getRangeAxis().getRange();
    }

    ApplicationContext.setProperty(SharedProperties.CHART_RANGE, chartRange);
}