Example usage for org.jfree.data.time TimeSeriesCollection addSeries

List of usage examples for org.jfree.data.time TimeSeriesCollection addSeries

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeriesCollection addSeries.

Prototype

public void addSeries(TimeSeries series) 

Source Link

Document

Adds a series to the collection and sends a DatasetChangeEvent to all registered listeners.

Usage

From source file:csds60analyzer.csds60analyzerGUI.java

public BufferedImage creaImagen() {
    BufferedImage imagen = null;/*  ww w .  jav  a2  s. c o m*/
    try {
        SAXBuilder builder = new SAXBuilder(false);
        Document doc = null;
        TimeSeriesCollection datos = new TimeSeriesCollection();
        if (fichero != null) {
            doc = builder.build(fichero);
            Element raiz = doc.getRootElement();
            List<Element> dias = raiz.getChildren("dia");
            Iterator<Element> diasIT = dias.iterator();
            TimeSeries desayunoAntes = new TimeSeries("Desayuno antes");
            TimeSeries desayunoDespues = new TimeSeries("Desayuno despus");
            TimeSeries almuerzoAntes = new TimeSeries("Almuerzo antes");
            TimeSeries almuerzoDespues = new TimeSeries("Almuerzo despus");
            TimeSeries cenaAntes = new TimeSeries("Cena antes");
            TimeSeries cenaDespues = new TimeSeries("Cena despus");

            pdesayuno = 0;
            pdesant = 0;
            pdesdes = 0;
            palmuerzo = 0;
            palmant = 0;
            palmdes = 0;
            pcena = 0;
            pcenant = 0;
            pcendes = 0;

            contdesant = 0;
            contdesdes = 0;
            contalmant = 0;
            contalmdes = 0;
            contcenant = 0;
            contcendes = 0;

            while (diasIT.hasNext()) {
                Element diaActual = diasIT.next();
                Integer fechaActual = Integer.parseInt(diaActual.getChildText("fecha").substring(0, 10));

                Calendar fad = GregorianCalendar.getInstance();
                fad.setTimeInMillis(fechaActual.longValue() * 1000);

                int dia = fad.get(Calendar.DAY_OF_MONTH);
                int mes = fad.get(Calendar.MONTH) + 1;
                int ano = fad.get(Calendar.YEAR);

                if (diaActual.getChildren().toString().contains("desayunoantes")) {
                    int desayunoAntesActual = Integer.parseInt(diaActual.getChildText("desayunoantes"));
                    desayunoAntes.add(new Day(dia, mes, ano), desayunoAntesActual);
                    pdesant = pdesant + desayunoAntesActual;
                    contdesant++;
                }
                if (diaActual.getChildren().toString().contains("desayunodespues")) {
                    int desayunoDespuesActual = Integer.parseInt(diaActual.getChildText("desayunodespues"));
                    desayunoDespues.add(new Day(dia, mes, ano), desayunoDespuesActual);
                    pdesdes = pdesdes + desayunoDespuesActual;
                    contdesdes++;
                }
                if (diaActual.getChildren().toString().contains("almuerzoantes")) {
                    int almuerzoAntesActual = Integer.parseInt(diaActual.getChildText("almuerzoantes"));
                    almuerzoAntes.add(new Day(dia, mes, ano), almuerzoAntesActual);
                    palmant = palmant + almuerzoAntesActual;
                    contalmant++;
                }
                if (diaActual.getChildren().toString().contains("almuerzodespues")) {
                    int almuerzoDespuesActual = Integer.parseInt(diaActual.getChildText("almuerzodespues"));
                    almuerzoDespues.add(new Day(dia, mes, ano), almuerzoDespuesActual);
                    palmdes = palmdes + almuerzoDespuesActual;
                    contalmdes++;
                }
                if (diaActual.getChildren().toString().contains("cenaantes")) {
                    int cenaAntesActual = Integer.parseInt(diaActual.getChildText("cenaantes"));
                    cenaAntes.add(new Day(dia, mes, ano), cenaAntesActual);
                    pcenant = pcenant + cenaAntesActual;
                    contcenant++;
                }
                if (diaActual.getChildren().toString().contains("cenadespues")) {
                    int cenaDespuesActual = Integer.parseInt(diaActual.getChildText("cenadespues"));
                    cenaDespues.add(new Day(dia, mes, ano), cenaDespuesActual);
                    pcendes = pcendes + cenaDespuesActual;
                    contcendes++;
                }
            }
            //controlar la division por cero
            if ((contdesant + contdesdes) > 0)
                pdesayuno = (pdesant + pdesdes) / (contdesant + contdesdes);
            if (contdesant > 0)
                pdesant = pdesant / contdesant;
            if (contdesdes > 0)
                pdesdes = pdesdes / contdesdes;
            if ((contalmant + contalmdes) > 0)
                palmuerzo = (palmant + palmdes) / (contalmant + contalmdes);
            if (contalmant > 0)
                palmant = palmant / contalmant;
            if (contalmdes > 0)
                palmdes = palmdes / contalmdes;
            if ((contcenant + contcendes) > 0)
                pcena = (pcenant + pcendes) / (contcenant + contcendes);
            if (contcenant > 0)
                pcenant = pcenant / contcenant;
            if (contcendes > 0)
                pcendes = pcendes / contcendes;
            datos.addSeries(desayunoAntes);
            datos.addSeries(desayunoDespues);
            datos.addSeries(almuerzoAntes);
            datos.addSeries(almuerzoDespues);
            datos.addSeries(cenaAntes);
            datos.addSeries(cenaDespues);
        }
        JFreeChart graficaJfree = ChartFactory.createTimeSeriesChart("Anlisis", " ", "Glucosa (mg)", datos,
                true, true, false);
        XYPlot plot = (XYPlot) graficaJfree.getPlot();
        plot.setBackgroundPaint(Color.getHSBColor(0f, 0f, .88f));
        plot.setDomainGridlinePaint(Color.getHSBColor(0f, 0f, .35f));
        plot.setDomainTickBandPaint(Color.getHSBColor(0f, 0f, .93f));
        plot.setOutlinePaint(Color.getHSBColor(0f, 0f, 0.35f));
        plot.setRangeGridlinePaint(Color.getHSBColor(0f, 0f, 0.35f));
        XYLineAndShapeRenderer plot2 = (XYLineAndShapeRenderer) plot.getRenderer();
        if (!CBdesayunoantes.getState())
            plot2.setSeriesLinesVisible(0, false);
        plot2.setSeriesPaint(0, Color.getHSBColor(.3f, 1f, .5f));
        //plot2.setSeriesStroke(0,new BasicStroke(2.0f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.0f));
        if (!CBdesayunodespues.getState())
            plot2.setSeriesLinesVisible(1, false);
        plot2.setSeriesPaint(1, Color.getHSBColor(.2f, 1f, .9f));
        if (!CBalmuerzoantes.getState())
            plot2.setSeriesLinesVisible(2, false);
        plot2.setSeriesPaint(2, Color.getHSBColor(.0f, 1f, .6f));
        if (!CBalmuerzodespues.getState())
            plot2.setSeriesLinesVisible(3, false);
        plot2.setSeriesPaint(3, Color.getHSBColor(.0f, 1f, .9f));
        if (!CBcenaantes.getState())
            plot2.setSeriesLinesVisible(4, false);
        plot2.setSeriesPaint(4, Color.getHSBColor(.6f, 1f, .4f));
        if (!CBcenadespues.getState())
            plot2.setSeriesLinesVisible(5, false);
        plot2.setSeriesPaint(5, Color.getHSBColor(.6f, 1f, 1f));
        imagen = graficaJfree.createBufferedImage(800, 600);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return imagen;
}

From source file:org.mwc.debrief.track_shift.views.StackedDotHelper.java

/**
 * ok, our track has been dragged, calculate the new series of offsets
 * /*w ww  . j ava  2s .  c om*/
 * @param linePlot
 * @param dotPlot
 * @param onlyVis
 * @param showCourse
 * @param b
 * @param holder
 * @param logger
 * 
 * @param currentOffset
 *          how far the current track has been dragged
 */
public void updateBearingData(final XYPlot dotPlot, final XYPlot linePlot, final TrackDataProvider tracks,
        final boolean onlyVis, final boolean showCourse, final boolean flipAxes, final Composite holder,
        final ErrorLogger logger, final boolean updateDoublets) {
    // do we even have a primary track
    if (_primaryTrack == null)
        return;

    // ok, find the track wrappers
    if (_secondaryTrack == null)
        initialise(tracks, false, onlyVis, holder, logger, "Bearing", true, false);

    // did it work?
    // if (_secondaryTrack == null)
    // return;

    // ok - the tracks have moved. better update the doublets
    if (updateDoublets)
        updateDoublets(onlyVis, true, false);

    // aah - but what if we've ditched our doublets?
    if ((_primaryDoublets == null) || (_primaryDoublets.size() == 0)) {
        // better clear the plot
        dotPlot.setDataset(null);
        linePlot.setDataset(null);
        return;
    }

    // create the collection of series
    final TimeSeriesCollection errorSeries = new TimeSeriesCollection();
    final TimeSeriesCollection actualSeries = new TimeSeriesCollection();

    // produce a dataset for each track
    final TimeSeries errorValues = new TimeSeries(_primaryTrack.getName());

    final TimeSeries measuredValues = new TimeSeries("Measured");
    final TimeSeries ambigValues = new TimeSeries("Ambiguous Bearing");
    final TimeSeries calculatedValues = new TimeSeries("Calculated");

    final TimeSeries osCourseValues = new TimeSeries("Course");

    // ok, run through the points on the primary track
    final Iterator<Doublet> iter = _primaryDoublets.iterator();
    while (iter.hasNext()) {
        final Doublet thisD = iter.next();

        try {
            // obvious stuff first (stuff that doesn't need the tgt data)
            final Color thisColor = thisD.getColor();
            double measuredBearing = thisD.getMeasuredBearing();
            double ambigBearing = thisD.getAmbiguousMeasuredBearing();
            final HiResDate currentTime = thisD.getDTG();
            final FixedMillisecond thisMilli = new FixedMillisecond(currentTime.getDate().getTime());

            // put the measured bearing back in the positive domain
            if (measuredBearing < 0)
                measuredBearing += 360d;

            // stop, stop, stop - do we wish to plot bearings in the +/- 180 domain?
            if (flipAxes)
                if (measuredBearing > 180)
                    measuredBearing -= 360;

            final ColouredDataItem mBearing = new ColouredDataItem(thisMilli, measuredBearing, thisColor, false,
                    null);

            // and add them to the series
            measuredValues.add(mBearing);

            if (ambigBearing != Doublet.INVALID_BASE_FREQUENCY) {
                if (flipAxes)
                    if (ambigBearing > 180)
                        ambigBearing -= 360;

                final ColouredDataItem amBearing = new ColouredDataItem(thisMilli, ambigBearing, thisColor,
                        false, null);
                ambigValues.add(amBearing);
            }

            // do we have target data?
            if (thisD.getTarget() != null) {
                double calculatedBearing = thisD.getCalculatedBearing(null, null);
                final Color calcColor = thisD.getTarget().getColor();
                final double thisError = thisD.calculateBearingError(measuredBearing, calculatedBearing);
                final ColouredDataItem newError = new ColouredDataItem(thisMilli, thisError, thisColor, false,
                        null);

                if (flipAxes)
                    if (calculatedBearing > 180)
                        calculatedBearing -= 360;

                final ColouredDataItem cBearing = new ColouredDataItem(thisMilli, calculatedBearing, calcColor,
                        true, null);

                errorValues.add(newError);
                calculatedValues.add(cBearing);
            }

        } catch (final SeriesException e) {
            CorePlugin.logError(Status.INFO, "some kind of trip whilst updating bearing plot", e);
        }

    }

    // right, we do course in a special way, since it isn't dependent on the
    // target track. Do course here.
    HiResDate startDTG, endDTG;

    // just double-check we've still got our primary doublets
    if (_primaryDoublets == null) {
        CorePlugin.logError(Status.WARNING, "FOR SOME REASON PRIMARY DOUBLETS IS NULL - INVESTIGATE", null);
        return;
    }

    if (_primaryDoublets.size() == 0) {
        CorePlugin.logError(Status.WARNING, "FOR SOME REASON PRIMARY DOUBLETS IS ZERO LENGTH - INVESTIGATE",
                null);
        return;
    }

    startDTG = _primaryDoublets.first().getDTG();
    endDTG = _primaryDoublets.last().getDTG();

    if (startDTG.greaterThan(endDTG)) {
        System.err.println("in the wrong order, start:" + startDTG + " end:" + endDTG);
        return;
    }

    final Collection<Editable> hostFixes = _primaryTrack.getItemsBetween(startDTG, endDTG);

    // loop through th items
    for (final Iterator<Editable> iterator = hostFixes.iterator(); iterator.hasNext();) {
        final Editable editable = (Editable) iterator.next();
        final FixWrapper fw = (FixWrapper) editable;
        final FixedMillisecond thisMilli = new FixedMillisecond(fw.getDateTimeGroup().getDate().getTime());
        double ownshipCourse = MWC.Algorithms.Conversions.Rads2Degs(fw.getCourse());

        // stop, stop, stop - do we wish to plot bearings in the +/- 180 domain?
        if (flipAxes)
            if (ownshipCourse > 180)
                ownshipCourse -= 360;

        final ColouredDataItem crseBearing = new ColouredDataItem(thisMilli, ownshipCourse, fw.getColor(), true,
                null);
        osCourseValues.add(crseBearing);
    }

    // ok, add these new series

    if (showCourse) {
        actualSeries.addSeries(osCourseValues);
    }

    if (errorValues.getItemCount() > 0)
        errorSeries.addSeries(errorValues);

    actualSeries.addSeries(measuredValues);

    if (ambigValues.getItemCount() > 0)
        actualSeries.addSeries(ambigValues);

    if (calculatedValues.getItemCount() > 0)
        actualSeries.addSeries(calculatedValues);

    dotPlot.setDataset(errorSeries);
    linePlot.setDataset(actualSeries);
}

From source file:org.openmrs.web.controller.ConceptStatsFormController.java

/**
 * Called prior to form display. Allows for data to be put in the request to be used in the view
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
 *///from  w w w. j  a v  a2  s . com
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    if (!Context.hasPrivilege("View Observations")) {
        return map;
    }

    MessageSourceAccessor msa = getMessageSourceAccessor();
    Locale locale = Context.getLocale();
    ConceptService cs = Context.getConceptService();
    String conceptId = request.getParameter("conceptId");
    //List<Obs> obs = new Vector<Obs>();
    //List<Obs> obsAnswered = new Vector<Obs>();

    if (conceptId != null) {
        Concept concept = cs.getConcept(Integer.valueOf(conceptId));
        ObsService obsService = Context.getObsService();

        if (concept != null) {

            // previous/next ids for links
            map.put("previousConcept", cs.getPrevConcept(concept));
            map.put("nextConcept", cs.getNextConcept(concept));

            //obs = obsService.getObservations(concept, "valueNumeric, obsId");
            //obsAnswered = obsService.getObservationsAnsweredByConcept(concept);

            if (ConceptDatatype.NUMERIC.equals(concept.getDatatype().getHl7Abbreviation())) {
                map.put("displayType", "numeric");

                List<Obs> numericAnswers = obsService.getObservations(null, null,
                        Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null,
                        Collections.singletonList("valueNumeric"), null, null, null, null, false);

                if (numericAnswers.size() > 0) {
                    Double min = numericAnswers.get(0).getValueNumeric();
                    Double max = (Double) numericAnswers.get(numericAnswers.size() - 1).getValueNumeric();
                    Double median = (Double) numericAnswers.get(numericAnswers.size() / 2).getValueNumeric();

                    Map<Double, Integer> counts = new HashMap<Double, Integer>(); // counts for the histogram
                    Double total = 0.0; // sum of values. used for mean

                    // dataset setup for lineChart
                    TimeSeries timeSeries = new TimeSeries(concept.getName().getName(), Day.class);
                    TimeSeriesCollection timeDataset = new TimeSeriesCollection();
                    Calendar calendar = Calendar.getInstance();

                    // array for histogram
                    double[] obsNumerics = new double[(numericAnswers.size())];

                    Integer i = 0;
                    for (Obs obs : numericAnswers) {
                        Date date = (Date) obs.getObsDatetime();
                        Double value = (Double) obs.getValueNumeric();

                        // for mean calculation
                        total += value;

                        // for histogram
                        obsNumerics[i++] = value;
                        Integer count = counts.get(value);
                        counts.put(value, count == null ? 1 : count + 1);

                        // for line chart
                        calendar.setTime(date);
                        Day day = new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, // January = 0 
                                calendar.get(Calendar.YEAR) < 1900 ? 1900 : calendar.get(Calendar.YEAR) // jfree chart doesn't like the 19th century
                        );
                        timeSeries.addOrUpdate(day, value);
                    }

                    Double size = new Double(numericAnswers.size());
                    Double mean = total / size;

                    map.put("size", numericAnswers.size());
                    map.put("min", min);
                    map.put("max", max);
                    map.put("mean", mean);
                    map.put("median", median);

                    // create histogram chart
                    HistogramDataset histDataset = new HistogramDataset(); // dataset for histogram
                    histDataset.addSeries(concept.getName().getName(), obsNumerics, counts.size());

                    JFreeChart histogram = ChartFactory.createHistogram(concept.getName().getName(),
                            msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                            msa.getMessage("Concept.stats.histogramRangeAxisTitle"), histDataset,
                            PlotOrientation.VERTICAL, false, true, false);
                    map.put("histogram", histogram);

                    if (size > 25) {
                        // calculate 98th percentile of the data:
                        Double x = 0.98;
                        Integer xpercentile = (int) (x * size);
                        Double upperQuartile = numericAnswers.get(xpercentile).getValueNumeric();
                        Double lowerQuartile = numericAnswers.get((int) (size - xpercentile)).getValueNumeric();
                        Double innerQuartile = upperQuartile - lowerQuartile;
                        Double innerQuartileLimit = innerQuartile * 1.5; // outliers will be greater than this from the upper/lower quartile
                        Double upperQuartileLimit = upperQuartile + innerQuartileLimit;
                        Double lowerQuartileLimit = lowerQuartile - innerQuartileLimit;

                        List<Obs> outliers = new Vector<Obs>();

                        // move outliers to the outliers list
                        // removing lower quartile outliers
                        for (i = 0; i < size - xpercentile; i++) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() >= lowerQuartileLimit) {
                                break; // quit if this value is greater than the lower limit
                            }
                            outliers.add(possibleOutlier);
                        }

                        // removing upper quartile outliers
                        for (i = size.intValue() - 1; i >= xpercentile; i--) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() <= upperQuartileLimit) {
                                break; // quit if this value is less than the upper limit
                            }
                            outliers.add(possibleOutlier);
                        }
                        numericAnswers.removeAll(outliers);

                        double[] obsNumericsOutliers = new double[(numericAnswers.size())];
                        i = 0;
                        counts.clear();
                        for (Obs values : numericAnswers) {
                            Double value = values.getValueNumeric();
                            obsNumericsOutliers[i++] = value;
                            Integer count = counts.get(value);
                            counts.put(value, count == null ? 1 : count + 1);
                        }

                        // create outlier histogram chart
                        HistogramDataset outlierHistDataset = new HistogramDataset();
                        outlierHistDataset.addSeries(concept.getName().getName(), obsNumericsOutliers,
                                counts.size());

                        JFreeChart histogramOutliers = ChartFactory.createHistogram(concept.getName().getName(),
                                msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                                msa.getMessage("Concept.stats.histogramRangeAxisTitle"), outlierHistDataset,
                                PlotOrientation.VERTICAL, false, true, false);
                        map.put("histogramOutliers", histogramOutliers);
                        map.put("outliers", outliers);

                    }

                    // create line graph chart
                    timeDataset.addSeries(timeSeries);
                    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(concept.getName().getName(),
                            msa.getMessage("Concept.stats.lineChartDomainAxisLabel"),
                            msa.getMessage("Concept.stats.lineChartRangeAxisLabel"), timeDataset, false, true,
                            false);
                    map.put("timeSeries", lineChart);

                }
            } else if (ConceptDatatype.BOOLEAN.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create bar chart for boolean answers
                map.put("displayType", "boolean");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Boolean answer = o.getValueAsBoolean();
                    if (answer == null) {
                        answer = false;
                    }
                    String name = answer.toString();
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            } else if (ConceptDatatype.CODED.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create pie graph for coded answers
                map.put("displayType", "coded");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Concept value = o.getValueCoded();
                    String name;
                    if (value == null) {
                        name = "[value_coded is null]";
                    } else {
                        name = value.getName().getName();
                    }
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            }
        }

    }

    //map.put("obs", obs);
    //map.put("obsAnswered", obsAnswered);

    map.put("locale", locale.getLanguage().substring(0, 2));

    return map;
}

From source file:com.planetmayo.debrief.satc_rcp.views.MaintainContributionsView.java

protected void redoOwnshipStates() {
    if (legPlot == null)
        return;//from w  ww .  jav a2s.c  o m

    boolean showCourses = true;
    if (showOSCourse != null)
        showCourses = showOSCourse.getSelection();

    java.awt.Color courseCol = java.awt.Color.blue.darker().darker();
    java.awt.Color speedCol = java.awt.Color.blue.brighter().brighter();

    // ok, now loop through and set them
    long startTime = Long.MAX_VALUE;
    long endTime = Long.MIN_VALUE;

    // clear any datasets
    legPlot.setDataset(0, null);
    legPlot.setDataset(1, null);

    // hmm, actually we have to remove any target leg markers
    @SuppressWarnings("unchecked")
    Collection<IntervalMarker> markers = legPlot.getDomainMarkers(Layer.BACKGROUND);
    if (markers != null) {
        ArrayList<IntervalMarker> markersToDelete = new ArrayList<IntervalMarker>(markers);
        Iterator<IntervalMarker> mIter = markersToDelete.iterator();
        while (mIter.hasNext()) {
            IntervalMarker im = mIter.next();
            legPlot.removeDomainMarker(im);
        }
    }

    // hey, does it have any ownship legs?
    TimeSeriesCollection tscC = new TimeSeriesCollection();
    TimeSeriesCollection tscS = new TimeSeriesCollection();
    TimeSeriesCollection tscCLegs = new TimeSeriesCollection();
    TimeSeriesCollection tscSLegs = new TimeSeriesCollection();
    TimeSeries courses = new TimeSeries("Course");
    TimeSeries bearings = new TimeSeries("Bearings");
    TimeSeries speeds = new TimeSeries("Speed");
    TimeSeries courseLegs = new TimeSeries("Course (leg)");
    TimeSeries speedLegs = new TimeSeries("Speed (leg)");

    Iterator<BaseContribution> conts = activeSolver.getContributions().iterator();
    while (conts.hasNext()) {
        BaseContribution baseC = conts.next();
        if (baseC.isActive())
            if (baseC instanceof BearingMeasurementContribution) {
                BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC;

                Iterator<LegOfData> lIter = null;
                LegOfData thisLeg = null;

                if (bmc.getOwnshipLegs() != null) {
                    lIter = bmc.getOwnshipLegs().iterator();
                    thisLeg = lIter.next();
                }

                List<HostState> hostStates = bmc.getHostState();
                if (hostStates != null) {
                    Iterator<HostState> stateIter = hostStates.iterator();
                    while (stateIter.hasNext()) {
                        BearingMeasurementContribution.HostState hostState = stateIter.next();
                        long thisTime = hostState.time;
                        double thisCourse = hostState.courseDegs;
                        if (showCourses)
                            courses.add(new FixedMillisecond(thisTime), thisCourse);
                        double thisSpeed = hostState.speedKts;
                        speeds.add(new FixedMillisecond(thisTime), thisSpeed);
                        startTime = Math.min(thisTime, startTime);
                        endTime = Math.max(thisTime, endTime);

                        // sort out if this is in a leg or not
                        if (thisLeg != null) {
                            if (thisTime > thisLeg.getEnd() && lIter.hasNext()) {
                                thisLeg = lIter.next();
                            } else {
                                if (thisTime >= thisLeg.getStart()) {
                                    speedLegs.add(new FixedMillisecond(thisTime), thisSpeed);
                                    if (showCourses)
                                        courseLegs.add(new FixedMillisecond(thisTime), thisCourse);
                                }
                            }
                        }
                    }
                }

                // also, we wish to show the bearings from the BMC
                Iterator<BMeasurement> cuts = bmc.getMeasurements().iterator();
                while (cuts.hasNext()) {
                    BearingMeasurementContribution.BMeasurement measurement = cuts.next();
                    if (measurement.isActive()) {
                        long thisT = measurement.getDate().getTime();
                        bearings.add(new FixedMillisecond(thisT),
                                Math.toDegrees(Math.abs(measurement.getBearingRads())));
                    }
                }

            }
    }

    // HEY, also shade the ownship legs
    conts = activeSolver.getContributions().iterator();
    while (conts.hasNext()) {
        BaseContribution baseC = conts.next();
        if (baseC.isActive()) {
            if (baseC instanceof BearingMeasurementContribution) {
                BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC;

                Iterator<LegOfData> lIter = null;
                if (bmc.getOwnshipLegs() != null) {
                    int ctr = 1;
                    lIter = bmc.getOwnshipLegs().iterator();
                    while (lIter.hasNext()) {
                        LegOfData thisL = lIter.next();
                        long thisStart = thisL.getStart();
                        long thisFinish = thisL.getEnd();

                        java.awt.Color transCol = new java.awt.Color(0, 0, 255, 12);

                        final Marker bst = new IntervalMarker(thisStart, thisFinish, transCol,
                                new BasicStroke(2.0f), null, null, 1.0f);
                        bst.setLabel("O/S-" + ctr++);
                        bst.setLabelAnchor(RectangleAnchor.TOP_LEFT);
                        bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10));
                        bst.setLabelTextAnchor(TextAnchor.TOP_LEFT);
                        legPlot.addDomainMarker(bst, Layer.BACKGROUND);
                    }
                }
            }
        }
    }

    tscS.addSeries(speeds);
    tscSLegs.addSeries(speedLegs);
    tscC.addSeries(bearings);

    if (showCourses) {
        tscC.addSeries(courses);
        tscCLegs.addSeries(courseLegs);
    }

    legPlot.setDataset(0, null);
    legPlot.setDataset(1, null);
    legPlot.setDataset(2, null);
    legPlot.setDataset(3, null);
    legPlot.setDataset(0, tscC);
    legPlot.setDataset(1, tscS);
    legPlot.setDataset(2, tscCLegs);
    legPlot.setDataset(3, tscSLegs);

    final NumberAxis axis2 = new NumberAxis("Speed (Kts)");
    legPlot.setRangeAxis(1, axis2);
    legPlot.mapDatasetToRangeAxis(1, 1);
    legPlot.mapDatasetToRangeAxis(3, 1);

    legPlot.getRangeAxis(0).setLabel("Crse/Brg (Degs)");
    legPlot.mapDatasetToRangeAxis(0, 0);
    legPlot.mapDatasetToRangeAxis(2, 0);

    final XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true);
    lineRenderer1.setSeriesPaint(1, courseCol);
    lineRenderer1.setSeriesShape(1, ShapeUtilities.createDiamond(0.1f));
    lineRenderer1.setSeriesPaint(0, java.awt.Color.RED);
    lineRenderer1.setSeriesShape(0, ShapeUtilities.createDiamond(2f));

    final XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer(true, false);
    lineRenderer2.setSeriesPaint(0, speedCol);

    final XYLineAndShapeRenderer lineRenderer3 = new XYLineAndShapeRenderer(false, true);
    lineRenderer3.setSeriesPaint(0, courseCol);
    lineRenderer3.setSeriesShape(0, ShapeUtilities.createUpTriangle(2f));

    final XYLineAndShapeRenderer lineRenderer4 = new XYLineAndShapeRenderer(false, true);
    lineRenderer4.setSeriesPaint(0, speedCol);
    lineRenderer4.setSeriesShape(0, ShapeUtilities.createDownTriangle(2f));

    // ok, and store them
    legPlot.setRenderer(0, lineRenderer1);
    legPlot.setRenderer(1, lineRenderer2);
    legPlot.setRenderer(2, lineRenderer3);
    legPlot.setRenderer(3, lineRenderer4);

    if (startTime != Long.MAX_VALUE)
        legPlot.getDomainAxis().setRange(startTime, endTime);

    // ok - get the straight legs to sort themselves out
    // redoStraightLegs();
}

From source file:studio.ui.LineChart.java

public static JFreeChart createDataset(KTableModel table) {
    TimeZone tz = TimeZone.getTimeZone("GMT");

    XYDataset ds = null;/*  w  w  w  .ja  va 2  s. c o  m*/

    if (table.getColumnCount() > 0) {
        Class klass = table.getColumnClass(0);

        if ((klass == K.KTimestampVector.class) || (klass == K.KTimespanVector.class)
                || (klass == K.KDateVector.class) || (klass == K.KTimeVector.class)
                || (klass == K.KMonthVector.class) || (klass == K.KMinuteVector.class)
                || (klass == K.KSecondVector.class) || (klass == K.KDatetimeVector.class)) {
            TimeSeriesCollection tsc = new TimeSeriesCollection(tz);

            for (int col = 1; col < table.getColumnCount(); col++) {
                TimeSeries series = null;

                try {
                    if (klass == K.KDateVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Day.class);
                        K.KDateVector dates = (K.KDateVector) table.getColumn(0);

                        for (int row = 0; row < dates.getLength(); row++) {
                            K.KDate date = (K.KDate) dates.at(row);
                            Day day = new Day(date.toDate(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(day, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KTimeVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);

                        K.KTimeVector times = (K.KTimeVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.KTime time = (K.KTime) times.at(row);
                            Millisecond ms = new Millisecond(time.toTime(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(ms, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KTimestampVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Day.class);
                        K.KTimestampVector dates = (K.KTimestampVector) table.getColumn(0);

                        for (int row = 0; row < dates.getLength(); row++) {
                            K.KTimestamp date = (K.KTimestamp) dates.at(row);
                            Day day = new Day(new java.util.Date(date.toTimestamp().getTime()), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(day, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KTimespanVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);

                        K.KTimespanVector times = (K.KTimespanVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.KTimespan time = (K.KTimespan) times.at(row);
                            Millisecond ms = new Millisecond(time.toTime(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(ms, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KDatetimeVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);
                        K.KDatetimeVector times = (K.KDatetimeVector) table.getColumn(0);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.KDatetime time = (K.KDatetime) times.at(row);
                            Millisecond ms = new Millisecond(time.toTimestamp(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(ms, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KMonthVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Month.class);
                        K.KMonthVector times = (K.KMonthVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.Month time = (K.Month) times.at(row);
                            int m = time.i + 24000;
                            int y = m / 12;
                            m = 1 + m % 12;

                            Month month = new Month(m, y);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(month, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KSecondVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Second.class);
                        K.KSecondVector times = (K.KSecondVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.Second time = (K.Second) times.at(row);
                            Second second = new Second(time.i % 60, time.i / 60, 0, 1, 1, 2001);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(second, ((ToDouble) o).toDouble());

                        }
                    } else if (klass == K.KMinuteVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Minute.class);
                        K.KMinuteVector times = (K.KMinuteVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.Minute time = (K.Minute) times.at(row);
                            Minute minute = new Minute(time.i % 60, time.i / 60, 1, 1, 2001);
                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(minute, ((ToDouble) o).toDouble());
                        }
                    }
                } catch (SeriesException e) {
                    System.err.println("Error adding to series");
                }

                if (series.getItemCount() > 0)
                    tsc.addSeries(series);
            }

            ds = tsc;
        } else if ((klass == K.KDoubleVector.class) || (klass == K.KFloatVector.class)
                || (klass == K.KShortVector.class) || (klass == K.KIntVector.class)
                || (klass == K.KLongVector.class)) {
            XYSeriesCollection xysc = new XYSeriesCollection();

            for (int col = 1; col < table.getColumnCount(); col++) {
                XYSeries series = null;

                try {
                    series = new XYSeries(table.getColumnName(col));

                    for (int row = 0; row < table.getRowCount(); row++) {
                        double x = ((ToDouble) table.getValueAt(row, 0)).toDouble();
                        double y = ((ToDouble) table.getValueAt(row, col)).toDouble();
                        series.add(x, y);
                    }
                } catch (SeriesException e) {
                    System.err.println("Error adding to series");
                }

                if (series.getItemCount() > 0)
                    xysc.addSeries(series);
            }

            ds = xysc;
        }
    }

    if (ds != null) {
        boolean legend = false;

        if (ds.getSeriesCount() > 1)
            legend = true;

        if (ds instanceof XYSeriesCollection)
            return ChartFactory.createXYLineChart("", "", "", ds, PlotOrientation.VERTICAL, legend, true, true);
        else if (ds instanceof TimeSeriesCollection)
            return ChartFactory.createTimeSeriesChart("", "", "", ds, legend, true, true);
    }

    return null;
}

From source file:de.fau.amos.ChartRenderer.java

/**
 * /*from  ww  w . jav a 2 s . co  m*/
 * Creates TimeSeriesCollection by querying energy data from database.
 * 
 * @param granularity Accuracy of distinguishment of displayed values (Summarise data to hours, days, months, years).
 * @param startTime Start of queried period.
 * @param endTime End of queried period.
 * @param sumOrAvg Shall values be added or averaged.
 * @param groupParameters Controlpoints that are affected.
 * @param unit Sets Unit (kWh or kWh/TNF)
 * @return TimeSeriesCollection that privedes the basis for creation of a png-chart
 */
private TimeSeriesCollection createTimeCollection(String granularity, String startTime, String endTime,
        String sumOrAvg, String groupParameters, String unit) {

    //time series containing all data
    TimeSeriesCollection collection = new TimeSeriesCollection();
    //split groupParameter string to get all queryed groups seperated
    groupParameters = groupParameters.replace("||", "splitHere");
    String[] groups = groupParameters.split("splitHere");

    //handle groups one after another
    for (int i = 0; i < groups.length; i++) {
        //get group name
        String groupName = groups[i].contains("'") ? groups[i].substring(0, groups[i].indexOf("'")) : groups[i];
        groups[i] = groups[i].contains("'") ? groups[i].substring(groupName.length()) : "";

        if (!groups[i].contains("|")) {
            continue;
        }
        //get used plants
        String plants = groups[i].substring(groups[i].indexOf("|") + 1);

        //prepare queryString
        groups[i] = groups[i].substring(0, groups[i].indexOf("|"));

        //generate series for group
        TimeSeries series = new TimeSeries(groupName);

        ResultSet rs = null;

        //skip group if nothing is selected to query
        if (groups[i].trim() != "") {
            if ("1".equals(unit)) {
                //query kWh
                rs = SQL.queryToResultSet("select * from (select round(" + sumOrAvg
                        + "(gruppenWert),4), gruppenZeit from(select " + sumOrAvg
                        + "(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from (select "
                        + sumOrAvg + "(value)as wert,control_point_name,date_trunc('" + granularity
                        + "',measure_time)as zeit1 from measures inner join controlpoints on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '"
                        + startTime + "' AND measure_time < '" + endTime + "' AND controlpoints_id in("
                        + groups[i]
                        + ") group by measure_time,control_point_name)as data group by zeit1,control_point_name)as groupedByTime group by gruppenZeit)as result order by gruppenZeit"
                        + ";");
            } else if ("2".equals(unit)) {
                //query kWh/TNF (only as sum, not avg)

                rs = SQL.queryToResultSet(

                        "select * from (select round(sum(gruppenWert)/(select sum(am) from(select sum(amount)as am,date_trunc('"
                                + granularity
                                + "',measure_time)as zeit from productiondata inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id "
                                + "where productiondata.measure_time >= '" + startTime
                                + "' AND productiondata.measure_time < '" + endTime
                                + "' AND reference_point='t' AND plant_id in(" + plants
                                + ") group by measure_time)as wat where zeit=gruppenZeit group by zeit order by zeit),4), gruppenZeit from("
                                + "select sum(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from (select sum(value)as wert,control_point_name,date_trunc('"
                                + granularity
                                + "',measure_time)as zeit1 from measures inner join controlpoints on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '"
                                + startTime + "' AND measure_time < '" + endTime + "' AND controlpoints_id in("
                                + groups[i]
                                + ")group by measure_time,control_point_name)as data group by zeit1,control_point_name)as groupedByTime group by gruppenZeit)as result order by gruppenZeit"
                                + ";");

            }
        }
        if (rs != null) {
            try {
                while (rs.next()) {
                    switch (granularity) {

                    case "minute":
                        series.add(new Minute(Integer.parseInt(rs.getString(2).substring(14, 16)),
                                Integer.parseInt(rs.getString(2).substring(11, 13)),
                                Integer.parseInt(rs.getString(2).substring(8, 10)),
                                Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));
                        break;
                    case "day":
                        series.add(new Day(Integer.parseInt(rs.getString(2).substring(8, 10)),
                                Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));
                        break;

                    case "month":
                        series.add(new Month(Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));
                        break;

                    case "year":
                        series.add(new Year(Integer.parseInt(rs.getString(2).substring(0, 4))),
                                rs.getDouble(1));
                        break;

                    //default: day
                    default:
                        series.add(new Day(Integer.parseInt(rs.getString(2).substring(8, 10)),
                                Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));

                    }
                }
                rs.close();

            } catch (NumberFormatException e) {

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //Add the series to the collection
        collection.addSeries(series);
    }
    return collection;
}

From source file:gov.llnl.lustre.lwatch.PlotFrame2.java

/**
 * Create the dataset for the set of TimeSeries curves to be plotted.
 */// w w w.  ja v  a2 s  . c om

public XYDataset createDataset() {

    // Load data for settings from last "Refresh" time
    String[] selectedRows = lastRefreshPlotParams.getCategories();
    String[] selectedVars = lastRefreshPlotParams.getVariables();
    String[] selectedCurves = lastRefreshPlotParams.getCurves();

    int savedGranularity = granularity;
    granularity = lastRefreshPlotParams.getGranularity();

    if (localDebug)
        Debug.out("Granularity used for timeSeries generation is " + granularity);

    //int nLines = nRowsSelected * nColsSelected * nCurvesSelected;
    int nLines = selectedRows.length * selectedVars.length * selectedCurves.length;
    //TimeSeries [] ts = new TimeSeries[nRowsSelected * nColsSelected *
    //nCurvesSelected];
    TimeSeries[] ts = new TimeSeries[nLines];

    int row = 0;
    int col = 0;
    int crv = -1;
    long tmBeg = tsStartPlot.getTime();
    long tmEnd = tsEndPlot.getTime();

    for (int i = 0; i < nLines; i++) {
        //if (localDebug)
        //Debug.out("Plot curve # " + i);

        //if (dataPointCount[i] <=0) {
        //Debug.out("dataPointCount[" + i + "] <= 0. Skip it.");
        //}

        crv++;
        if (crv == selectedCurves.length) {
            crv = 0;
            col++;
            if (col == selectedVars.length) {
                col = 0;
                row++;
            }
        }
        int tindx = i / selectedCurves.length;

        //String catvar = cats2Plot[row] + " " + vars2Plot[col] + crvs2Plot[crv];
        String catvar = selectedRows[row] + " " + selectedVars[col] + selectedCurves[crv];
        //Debug.out("Plot line for " + catvar);
        if (granularity == Database.HOUR)
            ts[i] = new TimeSeries(catvar, Hour.class);
        else if (granularity == Database.DAY)
            ts[i] = new TimeSeries(catvar, Day.class);
        else if (granularity == Database.WEEK)
            ts[i] = new TimeSeries(catvar, Week.class);
        else if (granularity == Database.MONTH)
            ts[i] = new TimeSeries(catvar, Month.class);
        else if (granularity == Database.YEAR)
            ts[i] = new TimeSeries(catvar, Year.class);
        else if ((granularity == Database.RAW) || (granularity == HEARTBEAT)) {
            //if (limitedDebug) {
            //System.out.println("\n\n" + i + "  " + catvar);
            //}
            ts[i] = new TimeSeries(catvar, Second.class);
        }

        if (rawData == null) {
            if (localDebug)
                Debug.out("ERROR     RawData = null");
            return null;
        }

        if (rawData[i] == null) {
            if (localDebug)
                Debug.out("ERROR     RawData[" + i + "] = null");
            return null;
        }

        int dsSize = dataPointCount[i]; //rawData[i].length;

        if (localDebug) {
            Debug.out("Size of " + catvar + " data set # " + i + " = " + dsSize);
        }

        int includeCnt = 0;
        for (int j = 0; j <= dataPointCount[i] - 1; j++) {
            //if (localDebug)
            //Debug.out("tindx " + tindx + "  j " + j + " secs " +
            //rawTimes[tindx][j]);
            long rawT = rawTimes[tindx][j];
            if ((rawT >= tmBeg) && (rawT <= tmEnd)) {
                float rangeVal = rawData[i][j];
                if (useLogRangeAxis && (rangeVal <= 0.0))
                    rangeVal = 1;

                try {
                    if (granularity == Database.HOUR)
                        ts[i].add(new Hour(new Date(rawT)), rangeVal, false);
                    else if (granularity == Database.DAY)
                        ts[i].add(new Day(new Date(rawT)), rangeVal, false);
                    else if (granularity == Database.WEEK)
                        ts[i].add(new Week(new Date(rawT)), rangeVal, false);
                    else if (granularity == Database.MONTH)
                        ts[i].add(new Month(new Date(rawT)), rangeVal, false);
                    else if (granularity == Database.YEAR)
                        ts[i].add(new Year(new Date(rawT)), rangeVal, false);
                    else if ((granularity == Database.RAW) || (granularity == HEARTBEAT)) {
                        includeCnt++;
                        //if (localDebug) {
                        //System.out.println(i + " " + j + " " +
                        //(new Second(new Date(rawT))).toString() +
                        //"  " + rangeVal);
                        //}
                        ts[i].add(new Second(new Date(rawT)), rangeVal, false);

                    }
                } catch (org.jfree.data.general.SeriesException e) {
                    if (localDebug)
                        Debug.out("Exception detected while calculating Timestamp objects. Problem at rawT = "
                                + rawT + "\n" + e.getMessage());
                }
            }
        }
        if (localDebug)
            Debug.out("# of points included in time series = " + includeCnt + "\n# of curves to be plotted = "
                    + nLines);
    }
    if (localDebug)
        Debug.out("\nTimeSeries array generation complete\n");

    // *****************************************************************
    //  More than 150 demo applications are included with the JFreeChar
    //  Developer Guide...for more information, see
    //
    //  >   http://www.object-refinery.com/jfreechart/guide.html
    //
    // ******************************************************************

    TimeSeriesCollection dataset = new TimeSeriesCollection();

    for (int i = 0; i < nLines; i++) {
        if (dataPointCount[i] > 0) {
            if (localDebug)
                Debug.out("Add timeSeries # " + i + " to chart dataset.");
            dataset.addSeries(ts[i]);
        }
    }

    // Reset granularity;
    granularity = savedGranularity;

    return dataset;

}

From source file:com.zimbra.perf.chart.ChartUtil.java

private List<JFreeChart> createJFReeChart(ChartSettings cs) {

    double minValue = Double.MAX_VALUE;
    double maxValue = Double.MIN_VALUE;
    double d = 0;
    double count = 0;
    double total = 0;
    TimeSeriesCollection data = new TimeSeriesCollection();

    ArrayList<ChartSettings> syntheticSettings = new ArrayList<ChartSettings>();
    for (GroupPlotSettings gps : cs.getGroupPlots()) {
        String groupBy = gps.getGroupBy();
        DataColumn dc = new DataColumn(gps.getInfile(), groupBy);
        StringSeries groupBySeries = mStringSeries.get(dc);
        dc = new DataColumn(gps.getInfile(), gps.getDataColumn());
        DataSeries ds = mDataSeries.get(dc);
        int idx = 0;
        Map<String, List<Integer>> groups = new HashMap<String, List<Integer>>();
        for (StringEntry e : groupBySeries.dataCollection) {
            String g = e.getVal();
            List<Integer> indices = groups.get(g);
            if (indices == null) {
                indices = new ArrayList<Integer>();
                groups.put(g, indices);/*w w  w  .jav a 2s.c  o  m*/
            }
            indices.add(idx);
            idx++;
        }
        for (Map.Entry<String, List<Integer>> g : groups.entrySet()) {
            String groupByValue = g.getKey();
            if (gps.getIgnoreSet().contains(groupByValue))
                continue;
            List<Integer> indices = g.getValue();
            DataSeries syntheticDS = new DataSeries();
            DataColumn c = new DataColumn(gps.getInfile(),
                    GROUP_PLOT_SYNTHETIC + groupByValue + ":" + gps.getDataColumn());
            for (int i : indices) {
                Entry e = ds.get(i);
                syntheticDS.AddEntry(e.getTimestamp(), e.getVal());
            }
            mDataSeries.put(c, syntheticDS);
            PlotSettings syntheticPlot = new PlotSettings(groupByValue, c.getInfile(), c.getColumn(),
                    gps.getShowRaw(), gps.getShowMovingAvg(), gps.getMovingAvgPoints(), gps.getMultiplier(),
                    gps.getDivisor(), gps.getNonNegative(), gps.getPercentTime(), gps.getDataFunction(),
                    gps.getAggregateFunction(), gps.getOptional(), null, null);
            cs.addPlot(syntheticPlot);
            if (cs.getOutDocument() != null) {
                ChartSettings s = new ChartSettings(String.format(cs.getTitle(), groupByValue),
                        cs.getCategory(), String.format(cs.getOutfile(), groupByValue), cs.getXAxis(),
                        cs.getYAxis(), cs.getAllowLogScale(), cs.getPlotZero(), cs.getWidth(), cs.getHeight(),
                        null, cs.getTopPlots(), cs.getTopPlotsType());
                s.addPlot(syntheticPlot);
                syntheticSettings.add(s);
            }
        }
    }
    if (cs.getOutDocument() != null && cs.getGroupPlots().size() != 0) {
        ArrayList<JFreeChart> charts = new ArrayList<JFreeChart>();
        for (ChartSettings c : syntheticSettings) {
            charts.addAll(createJFReeChart(c));
            c.setOutDocument(cs.getOutDocument());
        }
        mSyntheticChartSettings.addAll(syntheticSettings);
        return charts;
    }

    List<PlotSettings> plots = cs.getPlots();
    if (cs.getTopPlots() > 0 && plots.size() > cs.getTopPlots()) {
        String aggregateFunction = cs.getTopPlotsType().name().toLowerCase();
        System.out.println(String.format("Reducing %d to %d plots for chart '%s'", plots.size(),
                cs.getTopPlots(), cs.getTitle()));
        ArrayList<PlotAggregatePair> aggregates = new ArrayList<PlotAggregatePair>();
        for (PlotSettings ps : plots) {
            DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn());
            String key = ps.getInfile() + ":" + ps.getDataColumn() + ":" + ps.getAggregateFunction();
            PlotDataIterator pdIter = new PlotDataIterator(ps, mDataSeries.get(dc));
            double aggregate = mAggregator.compute(pdIter, aggregateFunction, mAggregateStartAt,
                    mAggregateEndAt, key);
            aggregates.add(new PlotAggregatePair(ps, aggregate));
        }
        Collections.sort(aggregates);
        while (aggregates.size() > cs.getTopPlots()) {
            PlotAggregatePair pair = aggregates.remove(0);
            plots.remove(pair.ps);
        }
    }
    for (PlotSettings ps : plots) {
        String columnName = ps.getDataColumn();
        if (columnName == null) {
            columnName = RATIO_PLOT_SYNTHETIC + ps.getRatioTop() + "/" + ps.getRatioBottom();
            String infile = ps.getInfile();

            String[] top = ps.getRatioTop().split("\\+");
            String[] bottom = ps.getRatioBottom().split("\\+");

            DataColumn[] ratioTop = new DataColumn[top.length];
            DataColumn[] ratioBottom = new DataColumn[bottom.length];

            for (int i = 0, j = top.length; i < j; i++)
                ratioTop[i] = new DataColumn(infile, top[i]);
            for (int i = 0, j = bottom.length; i < j; i++)
                ratioBottom[i] = new DataColumn(infile, bottom[i]);

            DataSeries[] topData = new DataSeries[ratioTop.length];
            DataSeries[] bottomData = new DataSeries[ratioBottom.length];

            for (int i = 0, j = ratioTop.length; i < j; i++)
                topData[i] = mDataSeries.get(ratioTop[i]);
            for (int i = 0, j = ratioBottom.length; i < j; i++)
                bottomData[i] = mDataSeries.get(ratioBottom[i]);

            DataSeries ds = new DataSeries();
            for (int i = 0, j = topData[0].size(); i < j; i++) {
                double topValue = 0.0;
                double bottomValue = 0.0;
                double ratio = 0.0;
                Entry lastEntry = null;
                for (int m = 0, n = topData.length; m < n; m++) {
                    Entry e = topData[m].get(i);
                    topValue += e.getVal();
                }
                for (int m = 0, n = bottomData.length; m < n; m++) {
                    Entry e = bottomData[m].get(i);
                    bottomValue += e.getVal();
                    lastEntry = e;
                }
                if (bottomValue != 0.0) {
                    ratio = topValue / bottomValue;
                }
                // should never be null
                assert lastEntry != null;
                ds.AddEntry(lastEntry.getTimestamp(), ratio);
            }
            mDataSeries.put(new DataColumn(infile, columnName), ds);
            ps.setDataColumn(columnName);
        }
        DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn());
        DataSeries ds = mDataSeries.get(dc);
        TimeSeries ts = new TimeSeries(ps.getLegend(), FixedMillisecond.class);
        int numSamples = 0;
        for (PlotDataIterator pdIter = new PlotDataIterator(ps, ds); pdIter.hasNext(); numSamples++) {
            Pair<Date, Double> entry = pdIter.next();
            Date tstamp = entry.getFirst();
            double val = entry.getSecond().doubleValue();
            if (val != 0 || cs.getPlotZero()) {
                if (d < minValue)
                    minValue = val;
                if (d > maxValue)
                    maxValue = val;
                count++;
                total += val;
                try {
                    ts.addOrUpdate(new FixedMillisecond(tstamp), val);
                } catch (SeriesException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
        if (numSamples == 0 && ps.getOptional()) {
            System.out.format("Skipping optional plot %s (no data sample found)\n\n", ps.getLegend());
            continue;
        }
        System.out.format("Adding %d %s points to %s.\n\n", ds.size(), ps.getLegend(), cs.getOutfile());
        if (ps.getShowRaw()) {
            data.addSeries(ts);
        }
        if (ps.getShowMovingAvg()) {
            int numPoints = ps.getMovingAvgPoints();
            if (numPoints == PlotSettings.DEFAULT_PLOT_MOVING_AVG_POINTS) {
                // Display 200 points for moving average.
                // Divide the total number of points by 200 to
                // determine the number of samples to average
                // for each point.
                numPoints = ts.getItemCount() / 200;
            }
            if (numPoints >= 2) {
                TimeSeries ma = MovingAverage.createPointMovingAverage(ts, ps.getLegend() + " (moving avg)",
                        numPoints);
                data.addSeries(ma);
            } else {
                System.out.println("Not enough data to display moving average for " + ps.getLegend());
                data.addSeries(ts);

            }
        }

    }
    // Create chart
    boolean legend = (data.getSeriesCount() > 1);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, cs.getXAxis(), cs.getYAxis(), data, legend,
            false, false);

    // Make Y-axis logarithmic if a spike was detected
    if (cs.getAllowLogScale() && (minValue > 0) && (maxValue > 0) && (maxValue > 20 * (total / count))) {
        if (maxValue / minValue > 100) {
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis oldAxis = plot.getRangeAxis();
            LogarithmicAxis newAxis = new LogarithmicAxis(oldAxis.getLabel());
            plot.setRangeAxis(newAxis);
        }
    }

    mChartMap.put(cs, chart);
    return Arrays.asList(chart);

}

From source file:org.atomserver.testutils.plot.PerfDataSet.java

static public XYDataset combineDataSets(List<XYDataset> xyDatasetList) {
    TimeSeriesCollection newTSC = new TimeSeriesCollection();
    for (XYDataset xyDataset : xyDatasetList) {
        TimeSeriesCollection subTSC = (TimeSeriesCollection) xyDataset;
        List seriesList = subTSC.getSeries();
        for (Object seriesObj : seriesList) {
            TimeSeries series = (TimeSeries) seriesObj;
            newTSC.addSeries(series);
        }//  ww  w.  ja v a2 s  . com
    }
    return newTSC;
}

From source file:org.atomserver.testutils.plot.PerfDataSet.java

public XYDataset getXYDataSet(boolean normalizeTimes, List methodNamesToPlot, String methodNameSuffix,
        boolean computeMovingAverage, int numPointsInAvg, boolean plotTPM) {
    long lMinDate = 0L;
    if (normalizeTimes) {
        lMinDate = minDate.getTime();//from  w  w  w .  j a v a  2  s  . c o  m
    }
    TimeSeriesCollection tsc = new TimeSeriesCollection();

    for (Map.Entry<String, List<PerfData>> entry : dataSet.entrySet()) {
        String methodName = entry.getKey();

        if (methodNamesToPlot != null) {
            if (!methodNamesToPlot.contains(methodName))
                continue;
        }

        if (methodNameSuffix != null) {
            methodName += " " + methodNameSuffix;
        }

        TimeSeries series = new TimeSeries(methodName, Second.class);

        List<PerfData> perfDataList = entry.getValue();
        for (PerfData perfData : perfDataList) {
            Date datetime = perfData.getDateTime();
            Double value = 0.0;
            if (plotTPM)
                value = perfData.getTPM();
            else
                value = perfData.getAvgResp();

            if (normalizeTimes) {
                long lDatetime = datetime.getTime();
                long lNormalizedTime = lDatetime - lMinDate;
                datetime = new Date(lNormalizedTime);
                if (log.isTraceEnabled())
                    log.trace("[ " + lDatetime + ", " + lMinDate + ", " + lNormalizedTime
                            + "] normalized time = " + datetime);
            }

            series.add(new Second(datetime), value);
        }

        if (computeMovingAverage) {
            TimeSeries movingAvg = MovingAverage.createPointMovingAverage(series,
                    methodName + " moving average", numPointsInAvg);
            tsc.addSeries(movingAvg);
        } else {
            tsc.addSeries(series);
        }

    }
    return tsc;
}