Example usage for org.jfree.data.xy XYSeries getItemCount

List of usage examples for org.jfree.data.xy XYSeries getItemCount

Introduction

In this page you can find the example usage for org.jfree.data.xy XYSeries getItemCount.

Prototype

@Override
public int getItemCount() 

Source Link

Document

Returns the number of items in the series.

Usage

From source file:org.fhcrc.cpl.viewer.gui.MRMDialog.java

private int indexOfMaxY(XYSeries s) {
    double _maxy = -10000000000.0;
    int retVal = -1;
    for (int i = 0; i < s.getItemCount(); i++) {
        XYDataItem xydi = s.getDataItem(i);
        if (_maxy < xydi.getY().doubleValue()) {
            _maxy = xydi.getY().doubleValue();
            retVal = i;//from   w w  w.  ja v a2  s .  c om
        }
    }
    return retVal;
}

From source file:org.fhcrc.cpl.viewer.gui.MRMDialog.java

protected void createChartInPanelDaughterTasksOnly(XYPlot xyp) {
    XYSeries coloredDataset = transitionOnPlot.getCurrentDaughter().getGraphData();
    Paint daughterColor = Utils.paleColor((Color) transitionOnPlot.getCurrentDaughter().getGraphColor());
    ArrayList<XYLineAnnotation> coloredDaughters = new ArrayList<XYLineAnnotation>();
    //Trace calculated elution curves over data spikes
    if (transitionOnPlot.getElutionCurves() != null && !transitionOnPlot.getElutionCurves().isEmpty()) {
        MRMDaughter curDaughter = transitionOnPlot.getCurrentDaughter();
        ElutionCurveStrategy ecs = transitionOnPlot.getElutionCurves().get(curDaughter);
        //Is current daughter rejected?
        Boolean accepted = (Boolean) ((PeaksTableModel) peaksTable.getModel()).data[curDaughter
                .getElutionDataTableRow()][peaksData.Accept.colno];
        if (accepted == null || !accepted) {
            xyp.setBackgroundPaint(new Color(255, 230, 230));
        }// ww w . j a  v a2s .  c o  m
        List<ElutionCurve> ecl = ecs.getDaughterCurves();
        if (ecl != null) {
            for (ElutionCurve e : ecl) {
                List<Line2D.Double> ll2dd = e.getSegments();
                for (Line2D.Double l2dd : ll2dd) {
                    xyp.addAnnotation(Utils.line2Annotation(l2dd, new BasicStroke(2.0f),
                            ecs.isBestDaughterCurve(e) ? Color.BLACK : Color.LIGHT_GRAY));
                }
            }
        }
    }

    // If there is a valid "current" daughter draw the spikes in the daughter's color
    // as annotations (sensu JFree)

    if (coloredDataset != null) {
        int nOfPoints = coloredDataset.getItemCount();
        for (int i = 0; i < (nOfPoints - 1); i++) {
            XYDataItem p1 = coloredDataset.getDataItem(i);
            XYDataItem p2 = coloredDataset.getDataItem(i + 1);
            coloredDaughters.add(new XYLineAnnotation(p1.getX().doubleValue(), p1.getY().doubleValue(),
                    p2.getX().doubleValue(), p2.getY().doubleValue(), new BasicStroke(1.5f),
                    transitionOnPlot.getCurrentDaughter().getGraphColor())
            //                 new XYLineAnnotation(p1.getX().doubleValue(),p1.getY().doubleValue(),p2.getX().doubleValue(),p2.getY().doubleValue(),new BasicStroke(1.5f),daughterColor)
            );
        }
    }
    if (_traceAllFragments) {
        for (MRMDaughter d : transitionOnPlot.getDaughters().values()) {
            if (d == transitionOnPlot.getCurrentDaughter())
                continue;
            XYSeries curXYSeries = d.getContinDaughterData();
            if (curXYSeries == null || curXYSeries.getItemCount() == 0)
                continue;
            if (d.getBestElutionCurve() == null)
                continue;
            int nOfPoints = curXYSeries.getItemCount();
            for (int i = 0; i < (nOfPoints - 1); i++) {
                XYDataItem p1 = curXYSeries.getDataItem(i);
                XYDataItem p2 = curXYSeries.getDataItem(i + 1);
                coloredDaughters.add(
                        //                        new XYLineAnnotation(p1.getX().doubleValue(),p1.getY().doubleValue(),p2.getX().doubleValue(),p2.getY().doubleValue(),new BasicStroke(1f),Utils.paleColor((Color)d.getGraphColor()))
                        new XYLineAnnotation(p1.getX().doubleValue(), p1.getY().doubleValue(),
                                p2.getX().doubleValue(), p2.getY().doubleValue(), new BasicStroke(1f),
                                d.getGraphColor()));
            }
        }
    }
    if (coloredDaughters != null) {
        for (XYLineAnnotation xyla : coloredDaughters) {
            xyp.addAnnotation(xyla);
        }
    }
    coloredDaughters.clear();

    //Display L or H label in upper left hand corner
    Range xRange = xyp.getDomainAxis().getRange();
    Range yRange = xyp.getRangeAxis().getRange();
    XYTextAnnotation lab = new XYTextAnnotation(
            (String) ((PeaksTableModel) peaksTable.getModel()).data[transitionOnPlot.getCurrentDaughter()
                    .getElutionDataTableRow()][peaksData.Label.colno],
            xRange.getUpperBound() - (0.05 * xRange.getLength()),
            yRange.getUpperBound() - (0.05 * yRange.getLength()));
    lab.setFont(lab.getFont().deriveFont(Font.BOLD, 40.0F));
    xyp.addAnnotation(lab);

    XYTextAnnotation midMarker = new XYTextAnnotation("\u25BC",
            ((MRMTransition) transitionOnPlot).getCalcXatMaxYAllDaughters(),
            ((MRMTransition) transitionOnPlot).getCalcMaxYAllDaughters());
    midMarker.setPaint(Color.RED);
    midMarker.setFont(midMarker.getFont().deriveFont(Font.BOLD, 20F));
    XYTextAnnotation midMarkerOutline = new XYTextAnnotation("\u25BC",
            ((MRMTransition) transitionOnPlot).getCalcXatMaxYAllDaughters(),
            ((MRMTransition) transitionOnPlot).getCalcMaxYAllDaughters());
    midMarkerOutline.setPaint(Color.BLACK);
    midMarkerOutline.setFont(midMarker.getFont().deriveFont(Font.BOLD, 23F));
    xyp.addAnnotation(midMarkerOutline);
    xyp.addAnnotation(midMarker);
}

From source file:edu.ucla.stat.SOCR.chart.util.MixtureEMExperiment.java

private void pointSegmenting() {
    segmentedPoints = new XYSeriesCollection();

    XYSeries mainGroup = new XYSeries(""); // mainGroup saves the points not included in any kernel
    XYSeries[] otherGroups = new XYSeries[num_kernels];
    int num_pts = DB.nPoints();

    double[][] kernel_x = new double[num_pts][num_kernels];
    double[][] kernel_y = new double[num_pts][num_kernels];
    int[] num_pts_in_kernel = new int[num_kernels];

    for (int i = 0; i < DB.nPoints(); i++) // For each point find the 2-nd level Gaussian
    {/*from   w  w w .  ja v a 2 s  .  c om*/
        boolean found = false;
        double x_value = DB.xVal(i);
        double y_value = DB.yVal(i);
        for (int k = 1; k <= num_kernels; k++) // for each kernel
        {

            if (CGMix.getKernel(k) instanceof CurvedGaussian
                    && ((CurvedGaussian) (CGMix.getKernel(k))).getPolygon().contains(x_value, y_value))
            // point inside the 2nd polygon Ellipse
            // "CGMix")
            {
                // System.out.println("Inside::pointSegmenting()");
                //  System.out.println("found one point in "+k);  // k is index of kernel+1
                if (otherGroups[k - 1] == null)
                    otherGroups[k - 1] = new XYSeries("");
                otherGroups[k - 1].add(x_value, y_value);
                found = true;

                kernel_x[num_pts_in_kernel[k - 1]][k - 1] = (x_value);
                kernel_y[num_pts_in_kernel[k - 1]][k - 1] = (y_value);
                num_pts_in_kernel[k - 1]++;

                k = num_kernels; // exit inner
                // loop
            }

        }
        if (!found) {
            mainGroup.add(x_value, y_value);

        }
    }

    num_group = 0;
    color_groups = new Paint[num_kernels];
    int results_rowCount = 0;

    String[][] results = new String[num_kernels * 6 + num_pts + 2][2];
    Paint[] row_color = new Paint[num_kernels * 6 + num_pts + 2];

    for (int i = 0; i < num_kernels; i++) {
        if (otherGroups[i] != null) {
            color_groups[num_group] = color_kernels[i];
            segmentedPoints.addSeries(otherGroups[i]);
            num_group++;

            results[results_rowCount][0] = "Kernel:" + num_group;
            results[results_rowCount][1] = color_kernels[i].toString();
            row_color[results_rowCount] = color_kernels[i];
            results_rowCount++;
            results[results_rowCount][0] = "mX = " + CGMix.getkmx(i + 1);
            ;
            results[results_rowCount][1] = "mY = " + CGMix.getkmy(i + 1);
            ;
            row_color[results_rowCount] = color_kernels[i];
            results_rowCount++;
            results[results_rowCount][0] = "sXX = " + CGMix.getksx(i + 1);
            ;
            results[results_rowCount][1] = "sXY = " + CGMix.getksxy(i + 1);
            ;
            row_color[results_rowCount] = color_kernels[i];
            results_rowCount++;
            results[results_rowCount][0] = "sYX = " + CGMix.getksxy(i + 1);
            ;
            results[results_rowCount][1] = "sYY = " + CGMix.getksy(i + 1);
            row_color[results_rowCount] = color_kernels[i];
            results_rowCount++;
            results[results_rowCount][0] = "weight = " + CGMix.getWeight(i + 1);
            results[results_rowCount][1] = "likelihood = " + CGMix.likelihood();
            row_color[results_rowCount] = color_kernels[i];
            results_rowCount++;
            results[results_rowCount][0] = "Points";
            results[results_rowCount][1] = "Count = " + num_pts_in_kernel[i];
            row_color[results_rowCount] = color_kernels[i];
            for (int j = 0; j < num_pts_in_kernel[i]; j++) {
                results_rowCount++;
                results[results_rowCount][0] = Double.toString(kernel_x[j][i]);
                results[results_rowCount][1] = Double.toString(kernel_y[j][i]);
                row_color[results_rowCount] = color_kernels[i];
            }
            results_rowCount++;
        }
    }

    results[results_rowCount][0] = "The rest";
    results[results_rowCount][1] = color_mainGroup.toString();
    row_color[results_rowCount] = color_mainGroup;
    results_rowCount++;
    results[results_rowCount][0] = "Points";
    results[results_rowCount][1] = "Count = " + Integer.toString(mainGroup.getItemCount());
    row_color[results_rowCount] = color_mainGroup;
    results_rowCount++;
    for (int i = 0; i < mainGroup.getItemCount(); i++) {
        results[results_rowCount][0] = mainGroup.getX(i).toString();
        results[results_rowCount][1] = mainGroup.getY(i).toString();
        row_color[results_rowCount] = color_mainGroup;
        results_rowCount++;
    }

    String[] resultsHeading = new String[2];
    resultsHeading[0] = "Kernel";
    resultsHeading[1] = "Resutls";
    tempResultsTable = new JTable(results, resultsHeading);

    resetRTableRows(tempResultsTable.getRowCount());

    for (int i = 0; i < tempResultsTable.getRowCount(); i++)
        for (int j = 0; j < tempResultsTable.getColumnCount(); j++) {
            resultsTable.setValueAt(tempResultsTable.getValueAt(i, j), i, j);
        }
    resultsTable.setColor(row_color, num_kernels * 6 + num_pts);

    num_group++;
    segmentedPoints.addSeries(mainGroup);

}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java

/***********************************************************************************************
 * Create a new Chart to show only those channels which are selected.
 * This must work even if the ChannelSelector is NULL.
 *
 * @param chartui//from  w ww .j  a  v  a  2 s. c  o  m
 * @param dao
 * @param datasettype
 * @param primarydataset
 * @param secondarydatasets
 * @param updatetype
 * @param isrefreshable
 * @param isclickrefresh
 * @param displaylimit
 * @param domainstartpoint
 * @param domainendpoint
 * @param channelselector
 * @param debug
 *
 * @return JFreeChart
 */

private static JFreeChart createChartForSelection(final ChartUIComponentPlugin chartui,
        final ObservatoryInstrumentDAOInterface dao, final DatasetType datasettype,
        final XYDataset primarydataset, final List<XYDataset> secondarydatasets,
        final DataUpdateType updatetype, final boolean isrefreshable, final boolean isclickrefresh,
        final int displaylimit, final int domainstartpoint, final int domainendpoint,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "ChartHelper.createChartForSelection() ";
    final JFreeChart jFreeChart;

    LOGGER.debug(debug, SOURCE);

    if ((datasettype != null) && (primarydataset != null) && (secondarydatasets != null)
            && (updatetype != null)) {
        final XYDataset xyNewPrimaryDataset;
        final List<XYDataset> listNewSecondaryDatasets;
        final List<XYDataset> listParentSecondaryDatasetForSeries;
        final Iterator iterOriginalSecondaryDatasets;
        final Calendar calObservatory;

        // Create a list of NewSecondaryDatasets for display
        // Add an appropriate *empty* new dataset for every one existing in the secondary set
        // and record the parent new Dataset for each Series in each original Dataset
        // So much complexity just to handle the very few cases of secondary datasets...

        listNewSecondaryDatasets = new ArrayList<XYDataset>(10);
        listParentSecondaryDatasetForSeries = new ArrayList<XYDataset>(10);

        iterOriginalSecondaryDatasets = secondarydatasets.iterator();

        // Either find the Current Observatory calendar, or provide a default
        calObservatory = ObservatoryInstrumentHelper.getCurrentObservatoryCalendar(REGISTRY.getFramework(), dao,
                debug);
        while (iterOriginalSecondaryDatasets.hasNext()) {
            final XYDataset xyDatasetOriginal;

            xyDatasetOriginal = (XYDataset) iterOriginalSecondaryDatasets.next();

            if ((xyDatasetOriginal != null) && (xyDatasetOriginal.getSeriesCount() > 0)) {
                final XYDataset xyDatasetNew;

                // Create an empty Dataset to correspond with the original
                if (datasettype.getName().equals(DatasetType.XY.getName())) {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else if (datasettype.getName().equals(DatasetType.TIMESTAMPED.getName())) {
                    xyDatasetNew = new TimeSeriesCollection(calObservatory.getTimeZone());
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                }

                // Record the *same* parent Dataset for each Series in each original Secondary Dataset
                // This creates a List in channel order, but with references to Datasets not Series
                for (int i = 0; i < xyDatasetOriginal.getSeriesCount(); i++) {
                    listParentSecondaryDatasetForSeries.add(xyDatasetNew);
                }
            }
        }

        LOGGER.debug(debug, SOURCE + "Check the DatasetType");

        // Confirm the DatasetType
        if ((datasettype.getName().equals(DatasetType.XY.getName()))
                && (primarydataset instanceof XYSeriesCollection)) {
            final XYSeriesCollection collectionPrimary;

            // Prepare a new XYSeriesCollection for display
            xyNewPrimaryDataset = new XYSeriesCollection();

            // There should be a collection of <channelcount> XYSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (XYSeriesCollection) primarydataset;

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)) {
                final int intChannelCount;

                if (channelselector != null) {
                    channelselector.debugSelector(debug, SOURCE);

                    if ((channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        intChannelCount = channelselector.getChannelSelectionModes().size();
                        LOGGER.debug(debug, SOURCE + "[channelcount.channelselector=" + intChannelCount + "]");
                    } else if (dao != null) {
                        intChannelCount = dao.getRawDataChannelCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.dao.raw=" + intChannelCount
                                + "] (has channelselector?)");
                    } else {
                        intChannelCount = collectionPrimary.getSeriesCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.primary.series=" + intChannelCount + "]");
                    }
                } else if (dao != null) {
                    intChannelCount = dao.getRawDataChannelCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.dao.raw" + intChannelCount + "] (no channelselector)");
                } else {
                    // This should never happen!
                    intChannelCount = collectionPrimary.getSeriesCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.primary.series" + intChannelCount + "] (last resort)");
                }

                LOGGER.debug(debug,
                        SOURCE + DatasetType.XY.getName() + " [domain.start.point=" + domainstartpoint
                                + "] [domain.end.point=" + domainendpoint + "] [channelcount.inferred="
                                + intChannelCount + "]");

                // Find which channels to use this time round
                for (int intChannelIndex = 0; intChannelIndex < intChannelCount; intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    // Use the ChannelSelectionMode if we can
                    if ((channelselector != null) && (channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);
                    } else {
                        // If there is no ChannelSelector then we can safely assume the Channel is ON
                        selectionMode = ChannelSelectionMode.X1;
                    }

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final XYSeries seriesOriginalData;

                        seriesOriginalData = (XYSeries) getSeriesForIndex(datasettype, primarydataset,
                                secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final XYSeries seriesChangedData;
                            final List listOriginalDataItems;
                            int intStartIndex;
                            int intEndIndex;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new XYSeries(seriesOriginalData.getKey());

                            // Map the slider values to data indexes
                            intStartIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                    DatasetDomainUIComponentInterface.INDEX_LEFT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.XY, calObservatory,
                                    seriesOriginalData, debug);

                            intEndIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                    DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.XY, calObservatory,
                                    seriesOriginalData, debug);
                            if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                // If either index is returned as -1, then there's nothing to do...
                                // ...so stop the for() loop
                                intStartIndex = 0;
                                intEndIndex = 0;
                            } else if (intEndIndex <= intStartIndex) {
                                intEndIndex = intStartIndex + 1;
                            }

                            LOGGER.debug(debug,
                                    SOURCE + "before copy of selected series subset [channel=" + intChannelIndex
                                            + "] [index.start=" + intStartIndex + "] [index.end=" + intEndIndex
                                            + "] [show.ticks=" + ((intEndIndex - intStartIndex) <= 25) + "]");

                            // Copy over only the selected range from the Slider
                            for (int intDataIndex = intStartIndex; ((intDataIndex < intEndIndex)
                                    && (listOriginalDataItems.size() > 0)); intDataIndex++) {
                                final XYDataItem dataOriginalItem;
                                final XYDataItem dataChangedItem;

                                dataOriginalItem = (XYDataItem) listOriginalDataItems.get(intDataIndex);

                                if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                    // Change each value of the series according to the multiplier
                                    dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                            dataOriginalItem.getY().doubleValue()
                                                    * selectionMode.getMultiplier());
                                } else {
                                    // Just use the whole series unaltered for gain of X1
                                    dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                            dataOriginalItem.getY());
                                }

                                seriesChangedData.add(dataChangedItem);
                            }

                            // Place the changed series in the correct collection
                            // to correspond with the original

                            // Did we collect any data for this Series?
                            // If not, place a dummy point at the origin of the *visible* chart
                            if (seriesChangedData.getItemCount() == 0) {
                                // TODO
                                seriesChangedData.add(new XYDataItem(0, 0));
                            }

                            if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                // Simply add the changed Primary series to the PrimaryDataset collection
                                ((XYSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                            } else {
                                // It must be a secondary dataset
                                // Add the changed Secondary series to the parent SecondaryDataset
                                // given by the *secondary* channel index
                                addSecondarySeries(datasettype, listParentSecondaryDatasetForSeries,
                                        seriesChangedData,
                                        intChannelIndex - collectionPrimary.getSeriesCount());
                            }
                        } else {
                            LOGGER.warn(SOURCE + "OriginalData XYSeries unexpectedly NULL");
                        }
                    }
                }

                // Dump the (partial) contents of each Series in the composite XYdataset
                dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "XYSeriesCollection --> createCustomisedChart() xyNewPrimaryDataset");

                jFreeChart = chartui.createCustomisedChart(datasettype, xyNewPrimaryDataset,
                        listNewSecondaryDatasets, updatetype, displaylimit, channelselector, debug);
            } else {
                LOGGER.error(SOURCE + " The XYSeriesCollection does not have any XYSeries");
                jFreeChart = null;
            }
        } else if ((datasettype.getName().equals(DatasetType.TIMESTAMPED.getName()))
                && (primarydataset instanceof TimeSeriesCollection)) {
            final TimeSeriesCollection collectionPrimary;

            // Prepare a new TimeSeriesCollection for display
            xyNewPrimaryDataset = new TimeSeriesCollection(calObservatory.getTimeZone());

            // There should be a collection of <channelcount> TimeSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (TimeSeriesCollection) primarydataset;

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)) {
                final int intChannelCount;

                if (channelselector != null) {
                    channelselector.debugSelector(debug, SOURCE);

                    if ((channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        intChannelCount = channelselector.getChannelSelectionModes().size();
                        LOGGER.debug(debug, SOURCE + "[channelcount.channelselector=" + intChannelCount + "]");
                    } else if (dao != null) {
                        intChannelCount = dao.getRawDataChannelCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.dao.raw=" + intChannelCount
                                + "] (has channelselector)");
                    } else {
                        intChannelCount = collectionPrimary.getSeriesCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.primary.series=" + intChannelCount + "]");
                    }
                } else if (dao != null) {
                    intChannelCount = dao.getRawDataChannelCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.dao.raw=" + intChannelCount + "] (no channelselector)");
                } else {
                    // This should never happen!
                    intChannelCount = collectionPrimary.getSeriesCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.primary.series=" + intChannelCount + "] (last resort)");
                }

                LOGGER.debug(debug,
                        SOURCE + DatasetType.TIMESTAMPED.getName() + " [domain.startpoint=" + domainstartpoint
                                + "] [domain.endpoint=" + domainendpoint + "] [domain.lowerbound="
                                + (long) collectionPrimary.getDomainLowerBound(true) + "] [domain.upperbound="
                                + (long) collectionPrimary.getDomainUpperBound(true)
                                + "] [channelcount.inferred=" + intChannelCount + "]");

                // Find which channels to use this time round
                for (int intChannelIndex = 0; intChannelIndex < intChannelCount; intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    // Use the ChannelSelectionMode if we can
                    if ((channelselector != null) && (channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);
                    } else {
                        // If there is no ChannelSelector then we can safely assume the Channel is ON
                        selectionMode = ChannelSelectionMode.X1;
                    }

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final TimeSeries seriesOriginalData;

                        seriesOriginalData = (TimeSeries) getSeriesForIndex(datasettype, primarydataset,
                                secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final TimeSeries seriesChangedData;
                            final List listOriginalDataItems;
                            int intStartIndex;
                            int intEndIndex;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new TimeSeries(seriesOriginalData.getKey().toString(),
                                    seriesOriginalData.getTimePeriodClass());

                            // Map the slider values to data indexes
                            intStartIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                    DatasetDomainUIComponentInterface.INDEX_LEFT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                    calObservatory, seriesOriginalData, debug);

                            intEndIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                    DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                    calObservatory, seriesOriginalData, debug);
                            if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                // If either index is returned as -1, then there's nothing to do...
                                // ...so stop the for() loop
                                intStartIndex = 0;
                                intEndIndex = 0;
                            } else if (intEndIndex <= intStartIndex) {
                                intEndIndex = intStartIndex + 1;
                            }

                            LOGGER.debug(debug,
                                    SOURCE + "before copy of selected series subset [channel=" + intChannelIndex
                                            + "] [index.start=" + intStartIndex + "] [index.end=" + intEndIndex
                                            + "] [item.count=" + listOriginalDataItems.size() + "]");

                            // Copy over only the selected range from the Slider
                            for (int intDataIndex = intStartIndex; ((intDataIndex < intEndIndex)
                                    && (intDataIndex < listOriginalDataItems.size())); intDataIndex++) {
                                final TimeSeriesDataItem dataOriginalItem;
                                final TimeSeriesDataItem dataChangedItem;

                                dataOriginalItem = (TimeSeriesDataItem) listOriginalDataItems.get(intDataIndex);

                                if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                    // Change each value of the series according to the multiplier
                                    dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                            dataOriginalItem.getValue().doubleValue()
                                                    * selectionMode.getMultiplier());
                                } else {
                                    // Just use the whole series unaltered for gain of X1
                                    dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                            dataOriginalItem.getValue().doubleValue());
                                }

                                seriesChangedData.add(dataChangedItem);
                            }

                            // Did we collect any data for this Series?
                            // If not, place a dummy point at the origin of the *visible* chart
                            if (seriesChangedData.getItemCount() == 0) {
                                seriesChangedData.add(createDummyTimeSeriesDataItemAtOrigin(collectionPrimary,
                                        seriesOriginalData, domainstartpoint, debug));
                            }

                            // Place the changed series in the correct collection
                            // to correspond with the original
                            if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                // Simply add the changed Primary series to the PrimaryDataset collection
                                ((TimeSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                            } else {
                                // It must be a secondary dataset
                                // Add the changed Secondary series to the parent SecondaryDataset
                                // given by the *secondary* channel index
                                addSecondarySeries(datasettype, listParentSecondaryDatasetForSeries,
                                        seriesChangedData,
                                        intChannelIndex - collectionPrimary.getSeriesCount());
                            }
                        } else {
                            LOGGER.warn(SOURCE + "OriginalData TimeSeries unexpectedly NULL");
                        }
                    }
                }

                // Dump the (partial) contents of each Series in the composite XYdataset
                dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "TimeSeriesCollection --> createCustomisedChart() xyNewPrimaryDataset");

                jFreeChart = chartui.createCustomisedChart(datasettype, xyNewPrimaryDataset,
                        listNewSecondaryDatasets, updatetype, displaylimit, channelselector, debug);
            } else {
                LOGGER.error(SOURCE + " The TimeSeriesCollection does not have any TimeSeries");
                jFreeChart = null;
            }
        } else {
            LOGGER.error(SOURCE + " The Dataset is of an invalid type");
            jFreeChart = null;
        }
    } else {
        LOGGER.debug(debug, SOURCE + " Unable to change the Chart - invalid parameters");
        jFreeChart = null;
    }

    return (jFreeChart);
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartUIComponent.java

/***********************************************************************************************
 * Update the existing Chart referenced by the DAO, by applying the specified datasets,
 * using all existing channel selections and range selections.
 * This implementation ASSUMES a ChannelSelector is present.
 *
 * @param dao/*  w w w.  java  2  s .c  o  m*/
 * @param datasettype
 * @param primarydataset
 * @param secondarydatasets
 * @param displaylimit
 * @param domainstartpoint
 * @param domainendpoint
 * @param channelselector
 * @param debug
 */

public void updateChartForSelection(final ObservatoryInstrumentDAOInterface dao, final DatasetType datasettype,
        final XYDataset primarydataset, final List<XYDataset> secondarydatasets, final int displaylimit,
        final int domainstartpoint, final int domainendpoint,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "ChartUIComponent.updateChartForSelection() ";

    if ((dao != null) && (dao.getChartUI() != null) && (dao.getChartUI().getChartPanel() != null)
            && (dao.getChartUI().getChartPanel().getChart() != null)
            && (dao.getChartUI().getChartPanel().getChart().getXYPlot() != null) && (datasettype != null)
            && (primarydataset != null) && (secondarydatasets != null) && (channelselector != null)) {
        final XYDataset xyNewPrimaryDataset;
        final List<XYDataset> listNewSecondaryDatasets;
        final List<XYDataset> listParentSecondaryDatasetForSeries;
        final Iterator iterOriginalSecondaryDatasets;
        final Calendar calObservatory;

        // Either find the Current Observatory calendar, or provide a default
        calObservatory = ObservatoryInstrumentHelper.getCurrentObservatoryCalendar(REGISTRY.getFramework(), dao,
                debug);

        // Create a list of NewSecondaryDatasets for display
        // Add an appropriate *empty* new dataset for every one existing in the secondary set
        // and record the parent new Dataset for each Series in each original Dataset
        // So much complexity just to handle the very few cases of secondary datasets...

        listNewSecondaryDatasets = new ArrayList<XYDataset>(10);
        listParentSecondaryDatasetForSeries = new ArrayList<XYDataset>(10);

        iterOriginalSecondaryDatasets = secondarydatasets.iterator();

        while (iterOriginalSecondaryDatasets.hasNext()) {
            final XYDataset xyDatasetOriginal;

            xyDatasetOriginal = (XYDataset) iterOriginalSecondaryDatasets.next();

            if ((xyDatasetOriginal != null) && (xyDatasetOriginal.getSeriesCount() > 0)) {
                final XYDataset xyDatasetNew;

                // Create an empty Dataset to correspond with the original
                if (datasettype.getName().equals(DatasetType.XY.getName())) {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else if (datasettype.getName().equals(DatasetType.TIMESTAMPED.getName())) {
                    xyDatasetNew = new TimeSeriesCollection(calObservatory.getTimeZone());
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                }

                // Record the *same* parent Dataset for each Series in each original Secondary Dataset
                // This creates a List in channel order, but with references to Datasets not Series
                for (int i = 0; i < xyDatasetOriginal.getSeriesCount(); i++) {
                    listParentSecondaryDatasetForSeries.add(xyDatasetNew);
                }
            }
        }

        // Confirm the DatasetType
        if ((datasettype.getName().equals(DatasetType.XY.getName()))
                && (primarydataset instanceof XYSeriesCollection)) {
            final XYSeriesCollection collectionPrimary;

            // Prepare a new XYSeriesCollection for display
            xyNewPrimaryDataset = new XYSeriesCollection();

            // There should be a collection of <channelcount> XYSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (XYSeriesCollection) primarydataset;

            // ToDo Make this work for ChannelSelector NULL, get channel count from primary and secondaries? Set mode to X1?

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)
                    && (channelselector.getChannelSelectionModes() != null)) {
                LOGGER.debug(debug, SOURCE + "XY domainstartpoint=" + domainstartpoint + " domainendpoint="
                        + domainendpoint);

                ChartHelper.dumpXYDataset(debug, calObservatory, collectionPrimary, 4,
                        SOURCE + "XYSeriesCollection --> Original Dataset");

                // Find which channels and data range to use this time round
                for (int intChannelIndex = 0; intChannelIndex < channelselector.getChannelSelectionModes()
                        .size(); intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final XYSeries seriesOriginalData;

                        // We needed to know about the secondary datasets in order to get the correct index
                        seriesOriginalData = (XYSeries) ChartHelper.getSeriesForIndex(datasettype,
                                primarydataset, secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final XYSeries seriesChangedData;
                            final List listOriginalDataItems;
                            int intStartIndex;
                            int intEndIndex;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new XYSeries(seriesOriginalData.getKey());

                            if (listOriginalDataItems.size() > 0) {
                                // Map the slider values to data indexes
                                intStartIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                        DatasetDomainUIComponentInterface.INDEX_LEFT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.XY,
                                        calObservatory, seriesOriginalData, debug);

                                intEndIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                        DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.XY,
                                        calObservatory, seriesOriginalData, debug);
                                if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                    // If either index is returned as -1, then there's nothing to do...
                                    // ...so stop the for() loop
                                    intStartIndex = 0;
                                    intEndIndex = 0;
                                } else if (intEndIndex <= intStartIndex) {
                                    intEndIndex = intStartIndex + 1;
                                }

                                LOGGER.debug(debug,
                                        SOURCE + "before copy of selected series subset [channel="
                                                + intChannelIndex + "] [index.start=" + intStartIndex
                                                + "] [index.end=" + intEndIndex + "]");

                                // Copy over only the selected range from the Slider
                                for (int intDataIndex = intStartIndex; intDataIndex < intEndIndex; intDataIndex++) {
                                    final XYDataItem dataOriginalItem;
                                    final XYDataItem dataChangedItem;

                                    dataOriginalItem = (XYDataItem) listOriginalDataItems.get(intDataIndex);

                                    if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                        // Change each value of the series according to the multiplier
                                        dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                                dataOriginalItem.getY().doubleValue()
                                                        * selectionMode.getMultiplier());
                                    } else {
                                        // Just use the whole series unaltered for gain of X1
                                        dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                                dataOriginalItem.getY());
                                    }

                                    seriesChangedData.add(dataChangedItem);
                                }

                                // Did we collect any data for this Series?
                                // If not, place a dummy point at the origin of the *visible* chart
                                if (seriesChangedData.getItemCount() == 0) {
                                    // TODO ChartHelper.createDummyXYSeriesDataItemAtOrigin()
                                    seriesChangedData.add(new XYDataItem(0, 0));
                                }

                                // Place the changed series in the correct collection
                                // to correspond with the original
                                if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                    // Simply add the changed Primary series to the PrimaryDataset collection
                                    ((XYSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                                } else {
                                    // It must be a secondary dataset
                                    // Add the changed Secondary series to the parent SecondaryDataset
                                    // given by the *secondary* channel index
                                    ChartHelper.addSecondarySeries(datasettype,
                                            listParentSecondaryDatasetForSeries, seriesChangedData,
                                            intChannelIndex - collectionPrimary.getSeriesCount());
                                }
                            } else {
                                LOGGER.warn(SOURCE + "OriginalData XYSeries unexpectedly NULL");
                            }
                        } else {
                            // There are no data! Do nothing...
                            LOGGER.warn(SOURCE + "There are no data, so do nothing");
                        }
                    }
                }

                LOGGER.debug(debug, SOURCE + "Update the data shown on existing Chart");

                // The outputs are xyNewPrimaryDataset and listNewSecondaryDatasets
                // This Chart does not use secondary datasets (yet)

                // Dump the (partial) contents of each Series in the new XYdataset
                ChartHelper.dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "XYSeriesCollection --> setDataset");

                dao.getChartUI().getChartPanel().getChart().getXYPlot().setDataset(INDEX_DATA,
                        xyNewPrimaryDataset);
            } else {
                LOGGER.error(SOURCE + " The XYSeriesCollection does not have any XYSeries");
            }
        } else if ((datasettype.getName().equals(DatasetType.TIMESTAMPED.getName()))
                && (primarydataset instanceof TimeSeriesCollection)) {
            final TimeSeriesCollection collectionPrimary;

            LOGGER.debug(debug, SOURCE + "TIMESTAMPED domainstartpoint=" + domainstartpoint + " domainendpoint="
                    + domainendpoint);

            // Prepare a new TimeSeriesCollection for display
            xyNewPrimaryDataset = new TimeSeriesCollection(calObservatory.getTimeZone());

            // There should be a collection of <channelcount> TimeSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (TimeSeriesCollection) primarydataset;

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)
                    && (channelselector.getChannelSelectionModes() != null)) {
                ChartHelper.dumpXYDataset(debug, calObservatory, collectionPrimary, 4,
                        SOURCE + "TimeSeriesCollection PrimaryDataset --> Original Dataset");

                // Find which channels and data range to use this time round
                for (int intChannelIndex = 0; intChannelIndex < channelselector.getChannelSelectionModes()
                        .size(); intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final TimeSeries seriesOriginalData;

                        // We needed to know about the secondary datasets in order to get the correct index
                        seriesOriginalData = (TimeSeries) ChartHelper.getSeriesForIndex(datasettype,
                                primarydataset, secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final List listOriginalDataItems;
                            final TimeSeries seriesChangedData;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new TimeSeries(seriesOriginalData.getKey().toString(),
                                    seriesOriginalData.getTimePeriodClass());

                            if (listOriginalDataItems.size() > 0) {
                                int intStartIndex;
                                int intEndIndex;

                                // Map the slider values to data indexes
                                intStartIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                        DatasetDomainUIComponentInterface.INDEX_LEFT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                        calObservatory, seriesOriginalData, debug);

                                intEndIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                        DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                        calObservatory, seriesOriginalData, debug);
                                if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                    // If either index is returned as -1, then there's nothing to do...
                                    // ...so stop the for() loop
                                    LOGGER.debug(debug, SOURCE + "Set EndIndex = StartIndex = 0");
                                    intStartIndex = 0;
                                    intEndIndex = 0;
                                } else if (intEndIndex <= intStartIndex) {
                                    LOGGER.debug(debug, SOURCE + "Correcting EndIndex less than StartIndex");
                                    intEndIndex = intStartIndex + 1;
                                }

                                LOGGER.debug(debug,
                                        SOURCE + "before copy of selected series subset [channel="
                                                + intChannelIndex + "] [start_index=" + intStartIndex
                                                + "] [end_index=" + intEndIndex + "]");

                                // Copy over only the selected range from the Slider
                                for (int intDataIndex = intStartIndex; intDataIndex < intEndIndex; intDataIndex++) {
                                    final TimeSeriesDataItem dataOriginalItem;
                                    final TimeSeriesDataItem dataChangedItem;

                                    dataOriginalItem = (TimeSeriesDataItem) listOriginalDataItems
                                            .get(intDataIndex);

                                    if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                        // Change each value of the series according to the multiplier
                                        dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                                dataOriginalItem.getValue().doubleValue()
                                                        * selectionMode.getMultiplier());
                                    } else {
                                        // Just use the whole series unaltered for gain of X1
                                        dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                                dataOriginalItem.getValue().doubleValue());
                                    }

                                    seriesChangedData.add(dataChangedItem);
                                }

                                // Did we collect any data for this Series?
                                // If not, place a dummy point at the origin of the *visible* chart
                                if (seriesChangedData.getItemCount() == 0) {
                                    seriesChangedData.add(ChartHelper.createDummyTimeSeriesDataItemAtOrigin(
                                            collectionPrimary, seriesOriginalData, domainstartpoint, debug));
                                }

                                // Place the changed series in the correct collection
                                // to correspond with the original
                                if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                    // Simply add the changed Primary series to the PrimaryDataset collection
                                    ((TimeSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                                } else {
                                    // It must be a secondary dataset
                                    // Add the changed Secondary series to the parent SecondaryDataset
                                    // given by the *secondary* channel index
                                    ChartHelper.addSecondarySeries(datasettype,
                                            listParentSecondaryDatasetForSeries, seriesChangedData,
                                            intChannelIndex - collectionPrimary.getSeriesCount());
                                }
                            } else {
                                // There are no data! Do nothing...
                                LOGGER.warn(SOURCE + "There are no data, so do nothing [channel.index="
                                        + intChannelIndex + "]");
                            }
                        } else {
                            LOGGER.warn(SOURCE + "OriginalData TimeSeries unexpectedly NULL [channel.index="
                                    + intChannelIndex + "]");
                        }
                    } else {
                        LOGGER.debug(debug, SOURCE + "Channel is OFF [channel.index=" + intChannelIndex + "]");
                    }
                }

                LOGGER.debug(debug, SOURCE + "Update the data shown on existing Chart");

                // The outputs are xyNewPrimaryDataset and listNewSecondaryDatasets
                // This Chart superclass does not use secondary datasets (yet)

                // Dump the (partial) contents of each Series in the new XYdataset
                ChartHelper.dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "TimeSeriesCollection NewPrimaryDataset --> setDataset");

                dao.getChartUI().getChartPanel().getChart().getXYPlot().setDataset(INDEX_DATA,
                        xyNewPrimaryDataset);
            } else {
                LOGGER.error(SOURCE + " The TimeSeriesCollection does not have any TimeSeries");
            }
        } else {
            LOGGER.error(SOURCE + " The Dataset is of an invalid type");
        }
    } else {
        LOGGER.debug(debug, SOURCE + " Unable to change the Chart - invalid parameters");
    }
}

From source file:org.micromanager.asidispim.fit.Fitter.java

/**
 * Utility to facilitate fitting data plotted in JFreeChart
 * Provide data in JFReeChart format (XYSeries), and retrieve univariate
 * function parameters that best fit (using least squares) the data. All data
 * points will be weighted equally./*  www. j a  va  2s . c o  m*/
 * 
 * TODO: investigate whether weighting (possibly automatic weighting) can
 * improve accuracy
 * 
 * @param data xy series in JFReeChart format
 * @param type one of the Fitter.FunctionType predefined functions
 * @param guess initial guess for the fit.  The number and meaning of these
     parameters depends on the FunctionType.  Implemented:
     Gaussian: 0: Normalization, 1: Mean 2: Sigma
        
 * @return array with parameters, whose meaning depends on the FunctionType.
 *          Use the function getXYSeries to retrieve the XYDataset predicted 
 *          by this fit
 */
public static double[] fit(XYSeries data, FunctionType type, double[] guess) {

    if (type == FunctionType.NoFit) {
        return null;
    }
    // create the commons math data object from the JFreeChart data object
    final WeightedObservedPoints obs = new WeightedObservedPoints();
    for (int i = 0; i < data.getItemCount(); i++) {
        obs.add(1.0, data.getX(i).doubleValue(), data.getY(i).doubleValue());
    }

    double[] result = null;
    switch (type) {
    case Pol1:
        final PolynomialCurveFitter fitter1 = PolynomialCurveFitter.create(1);
        result = fitter1.fit(obs.toList());
        break;
    case Pol2:
        final PolynomialCurveFitter fitter2 = PolynomialCurveFitter.create(2);
        result = fitter2.fit(obs.toList());
        break;
    case Pol3:
        final PolynomialCurveFitter fitter3 = PolynomialCurveFitter.create(3);
        result = fitter3.fit(obs.toList());
        break;
    case Gaussian:
        final GaussianWithOffsetCurveFitter gf = GaussianWithOffsetCurveFitter.create();
        if (guess != null) {
            gf.withStartPoint(guess);
        }
        result = gf.fit(obs.toList());
    default:
        break;
    }

    return result;
}

From source file:org.micromanager.asidispim.fit.Fitter.java

/**
 * Given a JFreeChart dataset and a commons math function, return a JFreeChart
 * dataset in which the original x values are now accompanied by the y values
 * predicted by the function/* w w  w.j  ava2s  .  co  m*/
 * 
 * @param data input JFreeChart data set
 * @param type one of the Fitter.FunctionType predefined functions
 * @param parms parameters describing the function.  These need to match the
 *             selected function or an IllegalArgumentEception will be thrown
 * 
 * @return JFreeChart dataset with original x values and fitted y values.
 */
public static XYSeries getFittedSeries(XYSeries data, FunctionType type, double[] parms) {
    XYSeries result = new XYSeries(data.getItemCount() * 10);
    double minRange = data.getMinX();
    double maxRange = data.getMaxX();
    double xStep = (maxRange - minRange) / (data.getItemCount() * 10);
    switch (type) {
    case NoFit:
        try {
            result = data.createCopy(0, data.getItemCount() - 1);
            result.setKey(data.getItemCount() * 10);
        } catch (CloneNotSupportedException ex) {
            return null;
        }
        break;
    case Pol1:
    case Pol2:
    case Pol3:
        checkParms(type, parms);
        PolynomialFunction polFunction = new PolynomialFunction(parms);
        for (int i = 0; i < data.getItemCount() * 10; i++) {
            double x = minRange + i * xStep;
            double y = polFunction.value(x);
            result.add(x, y);
        }
        break;
    case Gaussian:
        checkParms(type, parms);
        Gaussian.Parametric gf = new Gaussian.Parametric();
        for (int i = 0; i < data.getItemCount() * 10; i++) {
            double x = minRange + i * xStep;
            double[] gparms = new double[3];
            System.arraycopy(parms, 0, gparms, 0, 3);
            double y = gf.value(x, gparms) + parms[3];
            result.add(x, y);
        }
        break;
    }

    return result;
}

From source file:org.micromanager.asidispim.fit.Fitter.java

/**
 * Finds the x value corresponding to the maximum function value within the 
 * range of the provided data set.//from   w w  w .  j  a  v a2s .c om
 * 
 * @param type one of the Fitter.FunctionType predefined functions
 * @param parms parameters describing the function.  These need to match the
 *             selected function or an IllegalArgumentEception will be thrown
 * @param data JFreeChart series, used to bracket the range in which the 
 *             maximum will be found
 * 
 * @return x value corresponding to the maximum function value
 */
public static double getXofMaxY(XYSeries data, FunctionType type, double[] parms) {
    double xAtMax = 0.0;
    double minX = data.getMinX();
    double maxX = data.getMaxX();
    switch (type) {
    case NoFit:
        //  find the position in data with the highest y value
        double highestScore = data.getY(0).doubleValue();
        int highestIndex = 0;
        for (int i = 1; i < data.getItemCount(); i++) {
            double newVal = data.getY(i).doubleValue();
            if (newVal > highestScore) {
                highestScore = newVal;
                highestIndex = i;
            }
        }
        return data.getX(highestIndex).doubleValue();
    case Pol1:
    case Pol2:
    case Pol3:
        checkParms(type, parms);
        PolynomialFunction derivativePolFunction = (new PolynomialFunction(parms)).polynomialDerivative();

        final double relativeAccuracy = 1.0e-12;
        final double absoluteAccuracy = 1.0e-8;
        final int maxOrder = 5;
        UnivariateSolver solver = new BracketingNthOrderBrentSolver(relativeAccuracy, absoluteAccuracy,
                maxOrder);
        xAtMax = solver.solve(100, derivativePolFunction, minX, maxX);
        break;
    case Gaussian:
        // for a Gaussian we can take the mean and be sure it is the maximum
        // note that this may be outside our range of X values, but 
        // this will be caught by our sanity checks below
        xAtMax = parms[1];
    }

    // sanity checks
    if (xAtMax > maxX)
        xAtMax = maxX;
    if (xAtMax < minX)
        xAtMax = minX;

    return xAtMax;
}

From source file:org.micromanager.asidispim.fit.Fitter.java

/**
 * Find the index in the data series with an x value closest to the given
 * searchValue//from w w  w.j a va 2  s .co m
 * 
 * @param data data in XYSeries format
 * @param searchValue x value that we try to get close to
 * @return index into data with x value closest to searhValue
 */
public static int getIndex(XYSeries data, double searchValue) {
    int index = 0;
    double diff = dataDiff(data.getX(0), searchValue);
    for (int i = 1; i < data.getItemCount(); i++) {
        double newVal = dataDiff(data.getX(i), searchValue);
        if (newVal < diff) {
            diff = newVal;
            index = i;
        }
    }
    return index;
}

From source file:org.micromanager.asidispim.fit.Fitter.java

/**
 * Calculates a measure for the goodness of fit as defined here:
 * http://en.wikipedia.org/wiki/Coefficient_of_determination
 * R^2 = 1 - (SSres/SStot)//from  w  w w.j  a  v  a  2 s.  c  o  m
 * where
 *    SSres = SUM(i) (yi - fi)^2
 * end
 *    SStot = SUM(i) (yi - yavg)^2
 * 
 * @param data input data (raw data that were fitted
 * @param type function type used for fitting
 * @param parms function parameters derived in the fit
 * @return 
 */
public static double getRSquare(XYSeries data, FunctionType type, double[] parms) {

    // calculate SStot
    double yAvg = getYAvg(data);
    double ssTot = 0.0;
    for (int i = 0; i < data.getItemCount(); i++) {
        double y = data.getY(i).doubleValue();
        ssTot += (y - yAvg) * (y - yAvg);
    }

    // calculate SSres
    double ssRes = 0.0;
    for (int i = 0; i < data.getItemCount(); i++) {
        double y = data.getY(i).doubleValue();
        double f = getFunctionValue(data.getX(i).doubleValue(), type, parms);
        ssRes += (y - f) * (y - f);

    }

    return 1.0 - (ssRes / ssTot);
}