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:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.ApproximationSetPlot.java

@Override
protected void update() {
    XYSeriesCollection dataset = new XYSeriesCollection();

    for (ResultKey key : frame.getSelectedResults()) {
        NondominatedPopulation population = new EpsilonBoxDominanceArchive(EPSILON);

        for (Accumulator accumulator : controller.get(key)) {
            if (!accumulator.keySet().contains(metric)) {
                continue;
            }/*w w  w .j  a  v a  2s  . c o m*/

            List<?> list = (List<?>) accumulator.get(metric, accumulator.size(metric) - 1);

            for (Object object : list) {
                population.add((Solution) object);
            }
        }

        if (!population.isEmpty()) {
            XYSeries series = new XYSeries(key, false, true);

            for (Solution solution : population) {
                if (solution.getNumberOfObjectives() == 1) {
                    series.add(solution.getObjective(0), solution.getObjective(0));
                } else if (solution.getNumberOfObjectives() > 1) {
                    series.add(solution.getObjective(0), solution.getObjective(1));
                }
            }

            dataset.addSeries(series);
        }
    }

    JFreeChart chart = ChartFactory.createScatterPlot(metric, localization.getString("text.objective", 1),
            localization.getString("text.objective", 2), dataset, PlotOrientation.VERTICAL, true, true, false);

    XYPlot plot = chart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true);

    for (int i = 0; i < dataset.getSeriesCount(); i++) {
        Paint paint = frame.getPaintHelper().get(dataset.getSeriesKey(i));

        renderer.setSeriesStroke(i, new BasicStroke(3f, 1, 1));
        renderer.setSeriesPaint(i, paint);
        renderer.setSeriesFillPaint(i, paint);
    }

    plot.setRenderer(renderer);

    //add overlay
    if (controller.getShowLastTrace() && (controller.getLastAccumulator() != null)
            && controller.getLastAccumulator().keySet().contains(metric)) {
        XYSeriesCollection dataset2 = new XYSeriesCollection();
        NondominatedPopulation population = new EpsilonBoxDominanceArchive(EPSILON);

        if (controller.getLastAccumulator().keySet().contains(metric)) {
            List<?> list = (List<?>) controller.getLastAccumulator().get(metric,
                    controller.getLastAccumulator().size(metric) - 1);

            for (Object object : list) {
                population.add((Solution) object);
            }
        }

        if (!population.isEmpty()) {
            XYSeries series = new XYSeries(localization.getString("text.last"), false, true);

            for (Solution solution : population) {
                series.add(solution.getObjective(0), solution.getObjective(1));
            }

            dataset2.addSeries(series);
        }

        XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(false, true);
        renderer2.setSeriesPaint(0, Color.BLACK);

        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    }

    removeAll();
    add(new ChartPanel(chart), BorderLayout.CENTER);
    revalidate();
    repaint();
}

From source file:umontreal.iro.lecuyer.charts.XYListSeriesCollection.java

/**
 * Creates a new <TT>XYListSeriesCollection</TT> instance with default
 *    parameters and given data series. The input parameter <TT>data</TT>
 *    represents a set of plotting data.
 * /*from  w ww .j a  va 2s . c  o m*/
 * <P>
 * For example, if one <SPAN CLASS="MATH"><I>n</I></SPAN>-row matrix <TT>data1</TT> is given as argument,
 *  then the first row <TT>data1</TT><SPAN CLASS="MATH">[0]</SPAN> represents the
 *  <SPAN CLASS="MATH"><I>x</I></SPAN>-coordinate vector, and every other row <TT>data1</TT>
 * <SPAN CLASS="MATH">[<I>i</I>], <I>i</I> = 1,&#8230;, <I>n</I> - 1</SPAN>, represents a <SPAN CLASS="MATH"><I>y</I></SPAN>-coordinate set for the points.
 *   Therefore matrix <TT>data1</TT><SPAN CLASS="MATH">[<I>i</I>][<I>j</I>]</SPAN>, 
 * <SPAN CLASS="MATH"><I>i</I> = 0,&#8230;, <I>n</I> - 1</SPAN>,  corresponds
 *    to <SPAN CLASS="MATH"><I>n</I> - 1</SPAN> curves, all with the same <SPAN CLASS="MATH"><I>x</I></SPAN>-coordinates.
 * 
 * <P>
 * However, one may want to plot several curves with different <SPAN CLASS="MATH"><I>x</I></SPAN>-coordinates.
 *   In that case, one should give the curves as matrices with two rows.
 * For examples, if the argument <TT>data</TT> is made of three 2-row matrices
 * <TT>data1</TT>, <TT>data2</TT> and <TT>data3</TT>, then they represents
 *  three different curves, <TT>data*</TT><SPAN CLASS="MATH">[0]</SPAN> being the <SPAN CLASS="MATH"><I>x</I></SPAN>-coordinates,
 *  and  <TT>data*</TT><SPAN CLASS="MATH">[1]</SPAN> the <SPAN CLASS="MATH"><I>y</I></SPAN>-coordinates of the curves.
 * 
 * <P>
 * However, we may also consider the sets of points above not as part of curves,
 * but rather as several list of points.
 * 
 * @param data series of point sets.
 * 
 * 
 */
public XYListSeriesCollection(double[][]... data) {
    renderer = new XYLineAndShapeRenderer(true, false);
    //   ((XYLineAndShapeRenderer)renderer).setShapesVisible(false);
    seriesCollection = new XYSeriesCollection();

    XYSeriesCollection tempSeriesCollection = (XYSeriesCollection) seriesCollection;
    for (int i = 0; i < data.length; i++) {

        if (data[i].length < 2)
            throw new IllegalArgumentException(
                    "Unable to render the plot. data[" + i + "] contains less than two rows");

        for (int j = 0; j < data[i].length - 1; j++)
            if (data[i][j].length != data[i][j + 1].length)
                throw new IllegalArgumentException("data[" + i + "][" + j + "] and data[" + i + "][" + (j + 1)
                        + "] must share the same length");

        for (int j = 1; j < data[i].length; j++) {
            XYSeries serie = new XYSeries(" ");
            for (int k = 0; k < data[i][0].length; k++)
                serie.add(data[i][0][k], data[i][j][k]);
            tempSeriesCollection.addSeries(serie);
        }
    }

    // set default colors
    for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++)
        renderer.setSeriesPaint(i, getDefaultColor(i));

    // set default plot style
    plotStyle = new String[tempSeriesCollection.getSeriesCount()];
    marksType = new String[tempSeriesCollection.getSeriesCount()];
    dashPattern = new String[tempSeriesCollection.getSeriesCount()];
    for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++) {
        marksType[i] = " ";
        plotStyle[i] = "smooth";
        dashPattern[i] = "solid";
    }
}

From source file:umontreal.iro.lecuyer.charts.XYListSeriesCollection.java

/**
 * Creates a new <TT>XYListSeriesCollection</TT> instance with default parameters and given data.
 *    The input parameter represents a set of data plots, the constructor will count the occurrence number
 *    <SPAN CLASS="MATH"><I>Y</I></SPAN> of each value <SPAN CLASS="MATH"><I>X</I></SPAN> in the <TT>DoubleArrayList</TT>, and plot the point <SPAN CLASS="MATH">(<I>X</I>, <I>Y</I>)</SPAN>.
 *    Each {@link cern.colt.list.DoubleArrayList DoubleArrayList} variable corresponds to a curve on the chart.
 * /*from  w ww . j a va2 s  .  c  om*/
 * @param data series of point sets.
 * 
 * 
 */
public XYListSeriesCollection(DoubleArrayList... data) {
    renderer = new XYLineAndShapeRenderer(true, false);
    // ((XYLineAndShapeRenderer)renderer).setShapesVisible(false);
    seriesCollection = new XYSeriesCollection();
    XYSeriesCollection tempSeriesCollection = (XYSeriesCollection) seriesCollection;

    XYSeries serie;
    double[] elements;
    int count = 0;
    DoubleArrayList temp;
    for (int i = 0; i < data.length; i++) {
        serie = new XYSeries(" ");

        temp = data[i].copy(); // deep copy
        temp.trimToSize(); // set capacity to the current size
        temp.quickSortFromTo(0, temp.size() - 1); // sort list in increasing order, simplify the next processings
        elements = temp.elements();

        int j = 0;
        int l = 0;
        while (j < elements.length) {
            while (j < elements.length && elements[j] == elements[l]) {
                j++;
                count++;
            }
            serie.add(elements[l], count);
            count = 0;
            l = j;
        }
        tempSeriesCollection.addSeries(serie);
    }

    // set default colors
    for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++) {
        renderer.setSeriesPaint(i, getDefaultColor(i));
    }

    // set default plot style
    plotStyle = new String[tempSeriesCollection.getSeriesCount()];
    marksType = new String[tempSeriesCollection.getSeriesCount()];
    dashPattern = new String[tempSeriesCollection.getSeriesCount()];
    for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++) {
        marksType[i] = " ";
        plotStyle[i] = "smooth";
        dashPattern[i] = "solid";
    }
}

From source file:com.griddynamics.jagger.monitoring.reporting.SystemUnderTestPlotsProvider.java

public Map<String, List<MonitoringReporterData>> createTaskPlots() {
    log.info("BEGIN: Create task plots");

    Map<String, List<MonitoringReporterData>> taskPlots = new LinkedHashMap<String, List<MonitoringReporterData>>();
    DetailStatistics detailStatistics = getStatistics();

    for (String taskId : detailStatistics.findTaskIds()) {
        log.info("    Create task plots for task '{}'", taskId);

        List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
        for (GroupKey groupName : plotGroups.getPlotGroups().keySet()) {
            log.info("        Create task plots for group '{}'", groupName);

            if (showPlotsByGlobal) {
                log.info("            Create global task plots");

                XYSeriesCollection chartsCollection = new XYSeriesCollection();
                for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                    log.info("                Create global task plots for parameter '{}'", parameterId);

                    MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                    List<MonitoringStatistics> statistics = detailStatistics.findGlobalStatistics(taskId,
                            param);//from ww w .  ja va2 s.com
                    if (!statistics.isEmpty()) {
                        XYSeries values = new XYSeries(param.getDescription());
                        for (MonitoringStatistics monitoringStatistics : statistics) {
                            values.add(monitoringStatistics.getTime(), monitoringStatistics.getAverageValue());
                        }
                        if (values.isEmpty()) {
                            values.add(0, 0);
                        }
                        chartsCollection.addSeries(values);
                    }
                }

                log.debug("group name \n{} \nparams {}]\n", groupName,
                        Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection, null);

                chartsCollection = pair.getSecond();

                if (chartsCollection.getSeriesCount() > 0) {
                    JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                            "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 3, 2,
                            ChartHelper.ColorTheme.LIGHT);
                    MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                    monitoringReporterData.setParameterName(groupName.getUpperName());
                    monitoringReporterData.setTitle(groupName.getUpperName());
                    monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                    plots.add(monitoringReporterData);
                }
            }

            if (showPlotsByBox) {
                log.info("            Create box task plots");

                for (String boxIdentifier : detailStatistics.findBoxIdentifiers(taskId)) {
                    log.info("                Create box task plots for box '{}'", boxIdentifier);

                    XYSeriesCollection chartsCollection = new XYSeriesCollection();
                    for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                        log.info("                    Create box task plots for parameter '{}'", parameterId);

                        MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                        List<MonitoringStatistics> statistics = detailStatistics.findBoxStatistics(taskId,
                                param, boxIdentifier);
                        if (!statistics.isEmpty()) {
                            XYSeries values = new XYSeries(param.getDescription());
                            for (MonitoringStatistics monitoringStatistics : statistics) {
                                values.add(monitoringStatistics.getTime(),
                                        monitoringStatistics.getAverageValue());
                            }
                            if (values.isEmpty()) {
                                values.add(0, 0);
                            }
                            chartsCollection.addSeries(values);
                        }
                    }

                    log.debug("group name \n{} \nparams {}]\n", groupName,
                            Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                    Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection, null);

                    chartsCollection = pair.getSecond();

                    if (chartsCollection.getSeriesCount() > 0) {
                        JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                                "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 3, 2,
                                ChartHelper.ColorTheme.LIGHT);
                        MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                        monitoringReporterData.setParameterName(groupName.getUpperName());
                        monitoringReporterData.setTitle(groupName.getUpperName() + " on " + boxIdentifier);
                        monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                        plots.add(monitoringReporterData);
                    }
                }
            }

            if (showPlotsBySuT) {
                log.info("            Create sut task plots");

                for (String sutUrl : detailStatistics.findSutUrls(taskId)) {
                    log.info("                Create sut task plots for sut '{}'", sutUrl);

                    XYSeriesCollection chartsCollection = new XYSeriesCollection();
                    for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                        log.info("                    Create sut task plots for parameter '{}'", parameterId);

                        MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                        List<MonitoringStatistics> statistics = detailStatistics.findSutStatistics(taskId,
                                param, sutUrl);
                        if (!statistics.isEmpty()) {
                            XYSeries values = new XYSeries(param.getDescription());
                            for (MonitoringStatistics monitoringStatistics : statistics) {
                                values.add(monitoringStatistics.getTime(),
                                        monitoringStatistics.getAverageValue());
                            }
                            if (values.isEmpty()) {
                                values.add(0, 0);
                            }
                            chartsCollection.addSeries(values);
                        }
                    }

                    log.debug("group name \n{} \nparams {}]\n", groupName,
                            Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                    Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection, null);

                    chartsCollection = pair.getSecond();

                    if (chartsCollection.getSeriesCount() > 0) {
                        JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                                "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 3, 2,
                                ChartHelper.ColorTheme.LIGHT);
                        MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                        monitoringReporterData.setParameterName(groupName.getUpperName());
                        monitoringReporterData.setTitle(groupName.getUpperName() + " on " + sutUrl);
                        monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                        plots.add(monitoringReporterData);
                    }
                }
            }
        }

        taskPlots.put(taskId, plots);
    }

    clearStatistics();

    log.info("END: Create task plots");

    return taskPlots;
}

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.  co 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:umontreal.iro.lecuyer.charts.XYListSeriesCollection.java

public String toLatex(double XScale, double YScale, double XShift, double YShift, double xmin, double xmax,
        double ymin, double ymax) {

    // Calcule les bornes reelles du graphique, en prenant en compte la position des axes
    xmin = Math.min(XShift, xmin);
    xmax = Math.max(XShift, xmax);
    ymin = Math.min(YShift, ymin);
    ymax = Math.max(YShift, ymax);

    Formatter formatter = new Formatter(Locale.US);
    XYSeriesCollection tempSeriesCollection = (XYSeriesCollection) seriesCollection;
    double XEPSILON = (1.0E-4 / XScale) + XShift;
    double YEPSILON = (1.0E-4 / YScale) + YShift;
    boolean outOfBounds = false;
    MathFunction[] spline = null;//from w  w  w.  j a  va  2  s. c o  m
    double[] xBounds = getRangeBounds();
    double[] yBounds = getDomainBounds();
    double x, y;
    // Smoothing splines, consulter  ref: QA278.2 G74, QA278.2 T35, QA278.2 E87

    //       if(xBounds[0] < xmin || xBounds[1] > xmax || yBounds[0] < ymin || yBounds[1] > ymax) {
    //          // on sait qu'il y a des points qui vont sortir du chart
    //          // initialisation d'une spline pour chaque courbe
    //          spline = new SmoothingCubicSpline[seriesCollection.getSeriesCount()];
    //          for(int i = 0; i<seriesCollection.getSeriesCount(); i++)
    //             spline[i] = new SmoothingCubicSpline(  (seriesCollection.getSeries(i).toArray())[0],
    //                                                    (seriesCollection.getSeries(i).toArray())[1], 0.5);
    //       }

    // on sait qu'il y a des points qui vont sortir du chart
    // initialisation d'une spline pour chaque courbe
    if (true) {
        spline = new SmoothingCubicSpline[tempSeriesCollection.getSeriesCount()];
        for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++)
            spline[i] = new SmoothingCubicSpline((tempSeriesCollection.getSeries(i).toArray())[0],
                    (tempSeriesCollection.getSeries(i).toArray())[1], 1);
    } else {
        spline = new AffineFit[tempSeriesCollection.getSeriesCount()];
        for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++)
            spline[i] = new AffineFit((tempSeriesCollection.getSeries(i).toArray())[0],
                    (tempSeriesCollection.getSeries(i).toArray())[1]);
    }

    for (int i = tempSeriesCollection.getSeriesCount() - 1; i >= 0; i--) {
        XYSeries temp = tempSeriesCollection.getSeries(i);

        if (temp.getItemCount() < 2)
            throw new IllegalArgumentException(
                    "Unable to plot series " + i + ": this series must have two points at least");

        Color color = (Color) renderer.getSeriesPaint(i);
        String colorString = detectXColorClassic(color);
        if (colorString == null) {
            colorString = "color" + i;
            formatter.format("\\definecolor{%s}{rgb}{%.2f, %.2f, %.2f}%n", colorString, color.getRed() / 255.0,
                    color.getGreen() / 255.0, color.getBlue() / 255.0);
        }

        // Cas particulier pour le premier point, on doit savoir si il est dans le chart ou pas
        if (temp.getX(0).doubleValue() >= xmin && temp.getX(0).doubleValue() <= xmax
                && temp.getY(0).doubleValue() >= ymin && temp.getY(0).doubleValue() <= ymax) {
            outOfBounds = false;
            formatter.format("\\draw [%s, color=%s, mark=%s, style=%s] plot coordinates {%%%n", plotStyle[i],
                    colorString, marksType[i], dashPattern[i]);
        } else {
            outOfBounds = true;
            formatter.format("%% ");
        }
        formatter.format("(%.2f,%.4f)", (temp.getX(0).doubleValue() - XShift) * XScale,
                (temp.getY(0).doubleValue() - YShift) * YScale);
        formatter.format(" %%   (%f,  %f)%n", temp.getX(0).doubleValue(), temp.getY(0).doubleValue());

        // Cas general
        for (int j = 1; j < temp.getItemCount(); j++) {
            double[] result;
            if (!outOfBounds) { //on est dans le chart
                result = evalLimitValues(xmin, xmax, ymin, ymax, XEPSILON, YEPSILON, spline[i], temp, j, false);
                // on regarde si on ne sort pas du chart, si c'est le cas on evalue le point en limite
                if (result != null) { // le point courant n'est pas dans le chart, on sort donc du chart
                    outOfBounds = true;
                    if (autoCompletion)
                        formatter.format("(%.2f,%.4f) %%%n", (result[0] - XShift) * XScale,
                                (result[1] - YShift) * YScale);
                    formatter.format("}%%%n%% ");
                }
            } else { // le point precedent etait hors du chart
                if (temp.getX(j).doubleValue() >= xmin && temp.getX(j).doubleValue() <= xmax
                        && temp.getY(j).doubleValue() >= ymin && temp.getY(j).doubleValue() <= ymax) {
                    // on rentre dans le chart, il faut evaluer le point en limite
                    j = j - 1;
                    result = evalLimitValues(xmin, xmax, ymin, ymax, XEPSILON, YEPSILON, spline[i], temp, j,
                            true);
                    // ici result ne peut pas etre null
                    formatter.format(";%%%n\\draw [%s, color=%s, mark=%s, style=%s] plot coordinates {%%%n",
                            plotStyle[i], colorString, marksType[i], dashPattern[i]);
                    if (autoCompletion)
                        formatter.format("(%.2f,%.4f) %%%n ", (result[0] - XShift) * XScale,
                                (result[1] - YShift) * YScale);
                    formatter.format("%% ");
                    outOfBounds = false;
                } else {
                    formatter.format("%% ");
                    // on les donnees sont toujours hors du chart
                }
            }
            /* on affiche les coordonnees du point quoiqu'il arrive,
            si celui ci est hors du chart alors la balise de commentaire a ete deja place */
            formatter.format("(%.2f,%.4f)", (temp.getX(j).doubleValue() - XShift) * XScale,
                    (temp.getY(j).doubleValue() - YShift) * YScale);
            if (j == temp.getItemCount() - 1)
                formatter.format("}");
            formatter.format(" %%   (%f,  %f)%n", temp.getX(j).doubleValue(), temp.getY(j).doubleValue());
            //            formatter.format(" %%%n");
        }
        formatter.format(" node[right] {%s};%n", (String) temp.getKey());
    }
    return formatter.toString();
}

From source file:com.itemanalysis.jmetrik.graph.irt.IrtPlotAnalysis.java

public void summarize() throws SQLException {
    initializeProgress();/*from w w  w .  java 2s  . c  om*/

    if (plotTcc)
        tcc = new double[theta.length];
    if (plotTestInfo || plotTestStdError)
        tinfo = new double[theta.length];

    int j = 0;
    double maxPossibleTestScore = 0.0;
    double maxItemScore = 1;
    XYSeriesCollection collection = null;
    ItemResponseModel irm = null;
    for (String s : itemParameterSet.keySet()) {
        collection = new XYSeriesCollection();
        irm = itemParameterSet.get(s);
        maxPossibleTestScore += irm.getMaxScoreWeight();
        int ncat = irm.getNcat();

        //plot icc
        if (plotIcc) {
            if (ncat > 2) {
                if (categoryProbability) {
                    //plot all category probabilities for polytomous item
                    for (int i = 0; i < ncat; i++) {
                        collection.addSeries(getCategoryProbability(irm, i));
                    }
                } else {
                    //plot expected value for polytomous item
                    collection.addSeries(getExpectedValue(irm));
                    maxItemScore = irm.getMaxScoreWeight();
                }
            } else {
                //plot probability of a correct response for binary item
                collection.addSeries(getCategoryProbability(irm, 1));
            }
        }

        irtPanel.updateOrdinate(s, 0.0, maxItemScore);
        if (plotItemInfo) {
            collection.addSeries(getItemInformation(irm));
            if (!plotIcc) {
                irtPanel.setOrdinateLabel(s, "Item Information");
                irtPanel.setOrdinateAutoRange(s, true);
            }
        }

        if (hasResponseData) {
            addObservedPoints(j, irm.getNcat(), collection);
            irtPanel.updateDatasetLinesAndPoints(s, collection, collection.getSeriesCount() > 2);
        } else {
            irtPanel.updateDataset(s, collection, collection.getSeriesCount() > 1);
        }

        if (plotTcc) {
            incrementTcc(irm);
        }

        if (plotTestInfo || plotTestStdError) {
            incrementTestInfo(irm);
        }

        j++;
    }

    if (plotTcc || plotTestInfo || plotTestStdError) {
        collection = new XYSeriesCollection();
        if (plotTcc) {
            addTcc(collection);
            irtPanel.updateOrdinate("jmetrik-tcc-tif-tse", 0.0, maxPossibleTestScore);
            irtPanel.setOrdinateLabel("jmetrik-tcc-tif-tse", "True Score");
        } else {
            irtPanel.setOrdinateAutoRange("jmetrik-tcc-tif-tse", true);
            if (plotTestStdError && !plotTestInfo) {
                irtPanel.setOrdinateLabel("jmetrik-tcc-tif-tse", "Standard Error");
            }
            if (plotTestInfo && !plotTestStdError) {
                irtPanel.setOrdinateLabel("jmetrik-tcc-tif-tse", "Test Information");
            }
        }
        if (plotTestInfo)
            addTestInfo(collection);
        if (plotTestStdError)
            addTestStdError(collection);
        irtPanel.updateDataset("jmetrik-tcc-tif-tse", collection, collection.getSeriesCount() > 1);

    }

}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.PlateHeatMapController.java

/**
 * Plot the z-scores: simple scatterplot
 *//*from  w  w  w .j a v  a2s.  c o m*/
private void plotZScores() {
    XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
    Map<Well, Double> map = computeZScoresForMap();

    List<PlateCondition> plateConditionList = trackCoordinatesController.getPlateConditionList();

    for (int i = 0; i < plateConditionList.size(); i++) {
        // current condition
        PlateCondition condition = plateConditionList.get(i);
        XYSeries series = new XYSeries(i + "-" + condition);
        for (int j = 0; j < condition.getSingleCellAnalyzedWells().size(); j++) {
            // current well
            Well well = condition.getSingleCellAnalyzedWells().get(j);
            series.add(i + 1, map.get(well));
        }
        xySeriesCollection.addSeries(series);
    }

    JFreeChart jfreechart = ChartFactory.createScatterPlot("z*-score", "condition number", "z*-score",
            xySeriesCollection, PlotOrientation.VERTICAL, false, true, false);
    JFreeChartUtils.setupXYPlot(jfreechart.getXYPlot());
    jfreechart.getXYPlot().getDomainAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    // line for the median speed
    ValueMarker marker = new ValueMarker(0);
    marker.setPaint(Color.GRAY);
    Stroke dashedStroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f,
            new float[] { 1.0f, 3.0f }, 0.0f);
    marker.setStroke(dashedStroke);
    jfreechart.getXYPlot().addRangeMarker(marker);

    marker = new ValueMarker(3);
    marker.setPaint(Color.GRAY);
    marker.setStroke(dashedStroke);
    jfreechart.getXYPlot().addRangeMarker(marker);

    marker = new ValueMarker(-3);
    marker.setPaint(Color.GRAY);
    marker.setStroke(dashedStroke);
    jfreechart.getXYPlot().addRangeMarker(marker);

    XYItemRenderer renderer = jfreechart.getXYPlot().getRenderer();
    for (int i = 0; i < xySeriesCollection.getSeriesCount(); i++) {
        // plot lines according to conditions indexes
        int colorIndex = i % GuiUtils.getAvailableColors().length;
        Color color = GuiUtils.getAvailableColors()[colorIndex];
        color = new Color(color.getRed(), color.getGreen(), color.getBlue(), 127);
        renderer.setSeriesPaint(i, color);
        renderer.setSeriesShape(i, new Ellipse2D.Double(0, 0, 10, 10));
    }
    zScoreChartPanel.setChart(jfreechart);
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.ApproximationSetViewer.java

/**
 * Updates the display.  This method must only be invoked on the event
 * dispatch thread./*w  ww  .j  a v  a2  s. c o  m*/
 */
protected void update() {
    XYSeriesCollection dataset = new XYSeriesCollection();

    //generate approximation set
    for (int seedIndex : seedList.getSelectedIndices()) {
        Accumulator accumulator = accumulators.get(seedIndex);
        int index = 0;

        if (!accumulator.keySet().contains("Approximation Set")) {
            continue;
        }

        while ((index < accumulator.size("NFE") - 1)
                && ((Integer) accumulator.get("NFE", index) < slider.getValue())) {
            index++;
        }

        List<?> list = (List<?>) accumulator.get("Approximation Set", index);
        XYSeries series = new XYSeries(localization.getString("text.seed", seedIndex + 1), false, true);

        for (Object object : list) {
            Solution solution = (Solution) object;
            series.add(getValue(solution, 0), getValue(solution, 1));
        }

        dataset.addSeries(series);
    }

    //generate reference set
    if (referenceSet != null) {
        XYSeries series = new XYSeries(localization.getString("text.referenceSet"), false, true);

        for (Solution solution : referenceSet) {
            series.add(getValue(solution, 0), getValue(solution, 1));
        }

        dataset.addSeries(series);
    }

    JFreeChart chart = ChartFactory.createScatterPlot(getTitle() + " @ " + slider.getValue() + " NFE",
            (String) xAxisSelection.getSelectedItem(), (String) yAxisSelection.getSelectedItem(), dataset,
            PlotOrientation.VERTICAL, true, true, false);

    //set the renderer to only display shapes
    XYPlot plot = chart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true);

    for (int i = 0; i < dataset.getSeriesCount(); i++) {
        Paint paint = paintHelper.get(dataset.getSeriesKey(i));
        renderer.setSeriesPaint(i, paint);
    }

    plot.setRenderer(renderer);

    //set the zoom based on the user's preferences
    if ((initialRangeBounds == null) || (initialDomainBounds == null)) {
        initialRangeBounds = plot.getRangeAxis().getRange();
        initialDomainBounds = plot.getDomainAxis().getRange();
    }

    if (useInitialBounds.isSelected()) {
        plot.getRangeAxis().setRange(initialRangeBounds);
        plot.getDomainAxis().setRange(initialDomainBounds);
    } else if (useZoomBounds.isSelected()) {
        if ((zoomRangeBounds == null) || (zoomDomainBounds == null)) {
            zoomRangeBounds = initialRangeBounds;
            zoomDomainBounds = initialDomainBounds;
        }

        plot.getRangeAxis().setRange(zoomRangeBounds);
        plot.getDomainAxis().setRange(zoomDomainBounds);
    } else if (useReferenceSetBounds.isSelected()) {
        if (referenceRangeBounds.getLength() > 0.0) {
            plot.getRangeAxis().setRange(referenceRangeBounds);
        }

        if (referenceDomainBounds.getLength() > 0.0) {
            plot.getDomainAxis().setRange(referenceDomainBounds);
        }
    }

    //register with the chart to receive zoom events
    chart.addChangeListener(this);

    chartContainer.removeAll();
    chartContainer.add(new ChartPanel(chart), BorderLayout.CENTER);
    chartContainer.revalidate();
    chartContainer.repaint();
}

From source file:mineria.UI.java

public UI() {
    this.setLayout(new GridBagLayout());

    Label lblnodatos = new Label("NoDatos: ");
    Label label = new Label("BD: ");
    JTextField filename = new JTextField("/Users/eduardomartinez/Documents/mineria/representacion.txt");
    JTextField nodatos = new JTextField();
    nodatos.setText("500");

    JTextField funcion = new JTextField("6");
    JTextField individuos = new JTextField("200");
    JTextField enteros = new JTextField("1");
    JTextField decimales = new JTextField("40");
    JTextField variables = new JTextField("6");
    JTextField Pc = new JTextField("0.9");
    JTextField Pm = new JTextField("0.01");
    JTextField generaciones = new JTextField("100");
    JTextField minimiza = new JTextField("0");

    Label lblfuncion = new Label("funcion: ");
    Label lblindividuos = new Label("individuos: ");
    Label lblenteros = new Label("enteros: ");
    Label lbldecimales = new Label("decimales: ");
    Label lblvariables = new Label("variables: ");
    Label lblpc = new Label("Pc: ");
    Label lblpm = new Label("Pm: ");
    Label lblgeneraciones = new Label("generaciones: ");
    Label lblminimiza = new Label("[0 Min/1 Max] : ");

    /*//from w ww.  j  a  v a  2 s.  c o  m
    FN=funcion;
    N =individuos;
    E =bits_enteros;
    D =bits_decimales;
    V =variables;
    Pc=porcentaje_cruza;
    Pm=porcentaje_muta;
    G =generaciones;
    MM=minimiza;
    */

    JButton openBtn = new JButton("Open BD");
    JButton ejecutarEGA = new JButton("Ejecutar EGA");
    JTextField resultado = new JTextField();
    Label fitness = new Label("fitness: ");

    XYSeriesCollection datosSerie = new XYSeriesCollection();

    AGF agf = new AGF(2);
    EGA ega = new EGA();

    JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot", // chart title
            "X", // x axis label
            "Y", // y axis label
            datosSerie, // data  ***-----PROBLEM------***
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

    // create and display a frame...
    ChartPanel panelChart = new ChartPanel(chart);

    //leer BD
    openBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            //datosSerie.removeAllSeries();
            if (filename.getText().length() > 0) {
                agf.LeerDatos(filename.getText(), Integer.parseInt(nodatos.getText()));

                createDataset(datosSerie, agf.data, "Datos");
                chart.fireChartChanged();
            } else {
                JFileChooser openFile = new JFileChooser();
                int rVal = openFile.showOpenDialog(null);
                if (rVal == JFileChooser.APPROVE_OPTION) {
                    filename.setText(openFile.getSelectedFile().getAbsolutePath());
                    agf.LeerDatos(filename.getText(), Integer.parseInt(nodatos.getText()));
                    //createDataset(datosSerie, agf.data, "Datos");
                    //chart.fireChartChanged();
                }
                if (rVal == JFileChooser.CANCEL_OPTION) {
                    filename.setText("");
                    //dir.setText("");
                }
            }
        }
    });

    ejecutarEGA.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            //datosSerie.removeAllSeries();
            if (datosSerie.getSeriesCount() > 1)
                datosSerie.removeSeries(1);

            int fn = Integer.parseInt(funcion.getText());
            int n = Integer.parseInt(individuos.getText());
            int e = Integer.parseInt(enteros.getText());
            int d = Integer.parseInt(decimales.getText());
            int v = Integer.parseInt(variables.getText());
            double pc = Double.parseDouble(Pc.getText());
            double pm = Double.parseDouble(Pm.getText());
            int g = Integer.parseInt(generaciones.getText());
            int mm = Integer.parseInt(minimiza.getText());

            ega.setParams(fn, n, e, d, v, pc, pm, g, mm);

            Resultado res = ega.ejecutarAlgoritmoGenetico(agf);

            resultado.setText(String.valueOf(res.getFitnessSemental()));

            res.creaArchivo();
            createDataset(datosSerie, res.getFenotipoSemental(), "Centros");

            Shape cross = ShapeUtilities.createDiagonalCross(5, 1);
            XYPlot xyPlot = (XYPlot) chart.getPlot();
            xyPlot.setDomainCrosshairVisible(true);
            xyPlot.setRangeCrosshairVisible(true);
            XYItemRenderer renderer = xyPlot.getRenderer();
            renderer.setSeriesShape(1, cross);
            renderer.setSeriesPaint(1, Color.blue);

            chart.fireChartChanged();

        }
    });
    //ejecutar AG

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblnodatos, gbc);

    gbc.gridx = 3;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(nodatos, gbc);

    gbc.gridx = 2;
    gbc.gridy = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(filename, gbc);

    gbc.gridx = 3;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(openBtn, gbc);

    gbc.gridx = 2;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(fitness, gbc);

    gbc.gridx = 3;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(resultado, gbc);

    gbc.gridx = 2;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(ejecutarEGA, gbc);

    //-----------------PARAMETROS
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblfuncion, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(funcion, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblindividuos, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(individuos, gbc);

    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblenteros, gbc);

    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(enteros, gbc);

    gbc.gridx = 0;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lbldecimales, gbc);

    gbc.gridx = 1;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(decimales, gbc);

    gbc.gridx = 0;
    gbc.gridy = 4;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblvariables, gbc);

    gbc.gridx = 1;
    gbc.gridy = 4;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(variables, gbc);

    gbc.gridx = 0;
    gbc.gridy = 5;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblpc, gbc);

    gbc.gridx = 1;
    gbc.gridy = 5;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(Pc, gbc);

    gbc.gridx = 0;
    gbc.gridy = 6;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblpm, gbc);

    gbc.gridx = 1;
    gbc.gridy = 6;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(Pm, gbc);

    gbc.gridx = 0;
    gbc.gridy = 7;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblgeneraciones, gbc);

    gbc.gridx = 1;
    gbc.gridy = 7;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(generaciones, gbc);

    gbc.gridx = 0;
    gbc.gridy = 8;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblminimiza, gbc);

    gbc.gridx = 1;
    gbc.gridy = 8;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(minimiza, gbc);

    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 0;
    gbc.gridy = 9;
    gbc.gridheight = 2;
    gbc.gridwidth = 4;
    this.add(panelChart, gbc);

    this.setTitle("File Chooser");

    this.pack();
}