Example usage for org.jfree.data.time RegularTimePeriod getFirstMillisecond

List of usage examples for org.jfree.data.time RegularTimePeriod getFirstMillisecond

Introduction

In this page you can find the example usage for org.jfree.data.time RegularTimePeriod getFirstMillisecond.

Prototype

public abstract long getFirstMillisecond();

Source Link

Document

Returns the first millisecond of the time period.

Usage

From source file:org.jfree.chart.demo.XYBarChartDemo7.java

private static void addItem(XYIntervalSeries xyintervalseries, RegularTimePeriod regulartimeperiod,
        RegularTimePeriod regulartimeperiod1, int i) {
    xyintervalseries.add(regulartimeperiod.getFirstMillisecond(), regulartimeperiod.getFirstMillisecond(),
            regulartimeperiod1.getLastMillisecond(), i, (double) i - 0.45000000000000001D,
            (double) i + 0.45000000000000001D);
}

From source file:com.dreikraft.axbo.timeseries.TimeSeriesUtil.java

/**
 * Create a moving average time series from a given source series.
 *
 * @param source the source timeseries/*w w w  . j  a v a2  s. c o  m*/
 * @param preLen number of timeperiods before current time period included in
 * moving average calculation
 * @param postLen number of timeperiods after current time period included in
 * moving average calculation
 * @return a moving average time series
 */
public static TimeSeries createMovingAverage(final TimeSeries source, final int preLen, final int postLen) {

    final int len = preLen + postLen + 1;
    final TimeSeries result = new TimeSeries(source.getKey());
    final RegularTimePeriod lastTimePeriod = source.getTimePeriod(source.getItemCount() - 1);

    // process all timeperiods including empty ones
    RegularTimePeriod t = source.getTimePeriod(0);
    while (!(t.getFirstMillisecond() > lastTimePeriod.getFirstMillisecond())) {

        // calculate the moving avg value for the current time period
        double value = getValue(source, t);
        RegularTimePeriod ti = t;
        for (int i = 0; i < preLen; i++) {
            ti = ti.previous();
            value += getValue(source, ti);
        }
        ti = t;
        for (int i = 0; i < postLen; i++) {
            ti = ti.next();
            value += getValue(source, ti);
        }

        // add the moving avg value to the included time periods
        result.addOrUpdate(t, value / len);
        t = t.next();
    }

    return result;
}

From source file:com.dreikraft.axbo.timeseries.TimeSeriesUtil.java

/**
 * Create a XYZ dataset from a time series with Y.
 *
 * @param source//w ww .  j a  va  2s. c o  m
 * @return
 */
public static final XYZDataset createXYZTimeSeries(final TimeSeries source) {

    final RegularTimePeriod lastTimePeriod = source.getTimePeriod(source.getItemCount() - 1);
    // process all timeperiods including empty ones
    RegularTimePeriod t = source.getTimePeriod(0);
    final List<Double> zValuesList = new LinkedList<>();
    while (!(t.getFirstMillisecond() > lastTimePeriod.getFirstMillisecond())) {
        zValuesList.add(getValue(source, t));
        t = t.next();
    }
    final double[] xValues = new double[zValuesList.size()];
    final double[] yValues = new double[zValuesList.size()];
    final double[] zValues = new double[zValuesList.size()];
    t = source.getTimePeriod(0);
    for (int i = 0; i < zValuesList.size(); i++) {
        xValues[i] = t.getFirstMillisecond();
        yValues[i] = 0;
        zValues[i] = zValuesList.get(i);
        t = t.next();
    }
    final DefaultXYZDataset target = new DefaultXYZDataset();
    target.addSeries(0, new double[][] { xValues, yValues, zValues });

    return target;
}

From source file:edu.fullerton.viewerplugin.PluginSupport.java

public static void getRangeLimits(TimeSeriesCollection mtds, Double rng[]) {
    Double minx, miny, maxx, maxy;

    minx = miny = Double.MAX_VALUE;

    maxx = maxy = -Double.MAX_VALUE;
    for (Iterator it = mtds.getSeries().iterator(); it.hasNext();) {
        TimeSeries ds = (TimeSeries) it.next();
        for (int item = 1; item < ds.getItemCount() - 1; item++) {
            TimeSeriesDataItem dataItem = ds.getDataItem(item);
            RegularTimePeriod period = dataItem.getPeriod();

            double y = dataItem.getValue().doubleValue();
            double x = period.getFirstMillisecond();

            minx = Math.min(minx, x);
            miny = Math.min(miny, y);
            maxx = Math.max(maxx, x);
            maxy = Math.max(maxy, y);
        }/*from  w  w w . j a  v a 2  s.c  o  m*/
    }
    rng[0] = minx;
    rng[1] = miny;
    rng[2] = maxx;
    rng[3] = maxy;
}

From source file:com.appnativa.rare.ui.chart.jfreechart.ChartHelper.java

public static IntervalMarker createIntervalMarker(ChartDataItem item, ChartAxis.TimeUnit tm) {
    RegularTimePeriod lower = getTimePeriod((Date) item.getValue(), tm);
    RegularTimePeriod upper = getTimePeriod((Date) item.getDomainValue(), tm);
    IntervalMarker marker = new IntervalMarker(lower.getFirstMillisecond(), upper.getFirstMillisecond());
    String s = item.getTitle();/*www  .  j ava2 s . c om*/

    if (s != null) {
        marker.setLabel(s);
    }

    marker.setLabelAnchor(getRectangleAnchor(item));
    marker.setLabelTextAnchor(getTextAnchor(item));
    updateMarker(marker, item);

    return marker;
}

From source file:org.jfree.data.time.Millisecond.java

/**
 * Returns an integer indicating the order of this Millisecond object
 * relative to the specified object://from  w  w  w.j  ava 2s  . c o m
 *
 * negative == before, zero == same, positive == after.
 *
 * @param obj  the object to compare
 *
 * @return negative == before, zero == same, positive == after.
 */
@Override
public int compareTo(TimePeriod obj) {
    int result;
    long difference;

    // CASE 1 : Comparing to another Second object
    // -------------------------------------------
    if (obj instanceof Millisecond) {
        Millisecond ms = (Millisecond) obj;
        difference = getFirstMillisecond() - ms.getFirstMillisecond();
        if (difference > 0) {
            result = 1;
        } else {
            if (difference < 0) {
                result = -1;
            } else {
                result = 0;
            }
        }
    }

    // CASE 2 : Comparing to another TimePeriod object
    // -----------------------------------------------
    else {
        RegularTimePeriod rtp = (RegularTimePeriod) obj;
        final long thisVal = this.getFirstMillisecond();
        final long anotherVal = rtp.getFirstMillisecond();
        result = (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
    }

    return result;
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.blockcharts.TimeBlockChart.java

@Override
public DatasetMap calculateValue() throws Exception {
    logger.debug("IN");
    super.calculateValue();
    DatasetMap datasetMap = new DatasetMap();
    String res = DataSetAccessFunctions.getDataSetResultFromId(profile, getData(), parametersObject);

    ArrayList<Activity> activities = new ArrayList<Activity>();

    RegularTimePeriod timePeriod = null;

    SourceBean sbRows = SourceBean.fromXMLString(res);
    List listAtts = sbRows.getAttributeAsList("ROW");
    // Run all rows
    if (listAtts == null) {
        logger.error("Null rows retrieved from dataset");
        return null;
    }/*  w w  w  . j  a  v a 2 s.c om*/
    int j = 0;
    // for each activity
    logger.debug("retrieved number rows: " + listAtts.size());
    for (Iterator iterator = listAtts.iterator(); iterator.hasNext();) {
        SourceBean row = (SourceBean) iterator.next();
        Activity activity = new Activity(row, beginDateFormat, beginHourFormat);
        activities.add(activity);
        logger.debug(
                "Activity built from " + activity.getBeginDate() + " minutes" + activity.getMinutes() != null
                        ? activity.getMinutes().toString()
                        : "");
        if (maxDateFound != null && !activity.getBeginDate().after(maxDateFound)) {
        } else {
            maxDateFound = activity.getBeginDate();
        }

        if (minDateFound != null && !activity.getBeginDate().before(minDateFound)) {
        } else {
            minDateFound = activity.getBeginDate();
        }
    }

    //      count days
    long daysBetween;
    if (dateMin != null && dateMax != null) {
        logger.debug(
                "use date limit defined in template: from " + dateMin.toString() + " to " + dateMax.toString());
        daysBetween = daysBetween(dateMin, dateMax);
    } else {
        logger.debug(
                "use date limit found: from " + minDateFound.toString() + " to " + maxDateFound.toString());
        daysBetween = daysBetween(minDateFound, maxDateFound);
    }
    logger.debug("Days between the two dates " + daysBetween);
    // add a date to include extremis
    long minutesBetweenLong = daysBetween * 24 * 60 * 2; // raddoppio in caso di sovrapposizioni
    int mbl = Long.valueOf(minutesBetweenLong).intValue();

    DefaultXYZDataset dataset = new DefaultXYZDataset();

    ArrayList<Long> xValuesList = new ArrayList<Long>();
    ArrayList<Double> yValuesList = new ArrayList<Double>();
    ArrayList<Double> zValuesList = new ArrayList<Double>();

    annotations = new HashMap<String, AnnotationBlock>();
    // run all the activities
    for (Iterator iterator = activities.iterator(); iterator.hasNext();) {
        Activity activity = (Activity) iterator.next();

        // insert only if activty falls inside the min and max Range (idf defined)
        if (dateMin != null && dateMax != null
                && (activity.getBeginDate().after(dateMax) || activity.getBeginDate().before(dateMin))) {
            logger.debug(
                    "Activity discarde because starting out of selected bounds in " + activity.getBeginDate());
        } else {
            logger.debug("Inserting activity with begin date " + activity.getBeginDate() + " adn pattern "
                    + activity.getPattern());
            RegularTimePeriod rtp = new Day(activity.getBeginDate());
            long secondmills = rtp.getFirstMillisecond();

            Minute minute = activity.getMinutes();
            for (int i = 0; i < activity.getDuration(); i++) {
                // convert from hour to number axis (da sessantesimi a centesimi!)
                Integer hour = Integer.valueOf(minute.getHourValue());
                Integer minuteValue = Integer.valueOf(minute.getMinute());
                Double doubleMinuteValue = Double.valueOf(((double) minuteValue.intValue()));
                // minuteValue : 60 = x :100
                double convertedMinuteValue = (doubleMinuteValue * 100) / 60.0;
                double convertedMinuteValueCent = convertedMinuteValue / 100;

                double hourD = (double) hour.intValue();
                double converted = hourD + convertedMinuteValueCent;

                String yVal = Double.valueOf(converted).toString();

                xValuesList.add(new Long(secondmills));
                yValuesList.add(Double.valueOf(yVal));

                Object cosa = patternRangeIndex.get(activity.getPattern());

                if (cosa != null) {
                    zValuesList.add(
                            Double.valueOf(patternRangeIndex.get(activity.getPattern())).doubleValue() + 0.5);
                } else {
                    zValuesList.add(-1.0);
                }
                //               xvalues[j]=secondmills;
                //               yvalues[j]=Double.valueOf(yVal);
                //               zvalues[j]=patternRangeIndex.get(activity.getPattern())+0.5;

                //System.out.println("Date: "+activity.getBeginDate()+":"+Double.valueOf(xvalues[j]).toString()+", Hour: "+Double.valueOf(yvalues[j]).toString()+", Value: "+Double.valueOf(zvalues[j]).toString());
                if (annotations.get(activity.getCode()) == null) {
                    AnnotationBlock annotation = new AnnotationBlock(activity.getCode());
                    annotation.setXPosition(xValuesList.get(j).doubleValue());
                    annotation.setYPosition(yValuesList.get(j).doubleValue());
                    annotations.put(annotation.getAnnotation(), annotation);
                }
                minute = (Minute) minute.next();
                j++;
            }
        }

    }
    //      create arrays
    double[] xvalues = new double[xValuesList.size()];
    double[] yvalues = new double[yValuesList.size()];
    double[] zvalues = new double[zValuesList.size()];

    for (int i = 0; i < zValuesList.size(); i++) {
        Long l = xValuesList.get(i);
        xvalues[i] = l;
        Double d2 = yValuesList.get(i);
        yvalues[i] = d2;
        Double d = zValuesList.get(i);
        zvalues[i] = d;
    }

    logger.debug("adding the serie");
    dataset.addSeries("Series 1", new double[][] { xvalues, yvalues, zvalues });

    datasetMap.getDatasets().put("1", dataset);
    logger.debug("OUT");
    return datasetMap;
}

From source file:org.jfree.data.time.ohlc.OHLCSeriesCollection.java

/**
 * Returns the x-value for a time period.
 *
 * @param period  the time period (<code>null</code> not permitted).
 *
 * @return The x-value./*from   w  w w.j a  v a 2  s . c  om*/
 */
protected synchronized long getX(RegularTimePeriod period) {
    long result = 0L;
    if (this.xPosition == TimePeriodAnchor.START) {
        result = period.getFirstMillisecond();
    } else if (this.xPosition == TimePeriodAnchor.MIDDLE) {
        result = period.getMiddleMillisecond();
    } else if (this.xPosition == TimePeriodAnchor.END) {
        result = period.getLastMillisecond();
    }
    return result;
}

From source file:org.operamasks.faces.render.graph.ChartRenderer.java

private XYTextAnnotation createTimeSeriesTextAnnotation(UITextAnnotation at, Class timePeriodClass) {
    Date time = ChartUtils.convertDate(at.getxValue());
    if (time == null) {
        return null; // FIXME
    }/*from   w w  w .jav  a  2  s  .com*/

    RegularTimePeriod timePeriod = RegularTimePeriod.createInstance(timePeriodClass, time,
            RegularTimePeriod.DEFAULT_TIME_ZONE);

    double x = timePeriod.getFirstMillisecond();
    double y = Coercion.coerceToDouble(at.getyValue());
    return createXYTextAnnotation(at, x, y);
}

From source file:ucar.unidata.idv.control.chart.TimeSeriesChart.java

/**
 * Make the plot//from  w  w  w  .j  a  va  2 s.c o  m
 *
 * @return The plot_
 */
public Plot doMakePlot() {

    IdvPreferenceManager pref = control.getControlContext().getIdv().getPreferenceManager();
    TimeZone timeZone = pref.getDefaultTimeZone();
    NumberAxis valueAxis = new FixedWidthNumberAxis("");
    final SimpleDateFormat sdf = new SimpleDateFormat(
            ((dateFormat != null) ? dateFormat : pref.getDefaultDateFormat()));
    sdf.setTimeZone(timeZone);
    DateAxis timeAxis = new DateAxis("Time (" + timeZone.getID() + ")", timeZone) {

        protected List xxxxxrefreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {

            List ticks = super.refreshTicksHorizontal(g2, dataArea, edge);

            List<Tick> result = new java.util.ArrayList<Tick>();

            Font tickLabelFont = getTickLabelFont();
            g2.setFont(tickLabelFont);

            if (isAutoTickUnitSelection()) {
                selectAutoTickUnit(g2, dataArea, edge);
            }

            DateTickUnit unit = getTickUnit();
            Date tickDate = calculateLowestVisibleTickValue(unit);
            Date upperDate = getMaximumDate();

            Date firstDate = null;
            while (tickDate.before(upperDate)) {

                if (!isHiddenValue(tickDate.getTime())) {
                    // work out the value, label and position
                    String tickLabel;
                    DateFormat formatter = getDateFormatOverride();
                    if (firstDate == null) {
                        if (formatter != null) {
                            tickLabel = formatter.format(tickDate);
                        } else {
                            tickLabel = getTickUnit().dateToString(tickDate);
                        }
                        firstDate = tickDate;
                    } else {
                        double msdiff = tickDate.getTime() - firstDate.getTime();
                        int hours = (int) (msdiff / 1000 / 60 / 60);
                        tickLabel = hours + "H";
                    }
                    //                tickLabel = tickLabel;
                    TextAnchor anchor = null;
                    TextAnchor rotationAnchor = null;
                    double angle = 0.0;
                    if (isVerticalTickLabels()) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                        if (edge == RectangleEdge.TOP) {
                            angle = Math.PI / 2.0;
                        } else {
                            angle = -Math.PI / 2.0;
                        }
                    } else {
                        if (edge == RectangleEdge.TOP) {
                            anchor = TextAnchor.BOTTOM_CENTER;
                            rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        } else {
                            anchor = TextAnchor.TOP_CENTER;
                            rotationAnchor = TextAnchor.TOP_CENTER;
                        }
                    }

                    Tick tick = new DateTick(tickDate, tickLabel, anchor, rotationAnchor, angle);
                    result.add(tick);
                    tickDate = unit.addToDate(tickDate, getTimeZone());
                } else {
                    tickDate = unit.rollDate(tickDate, getTimeZone());

                    continue;
                }

                // could add a flag to make the following correction optional...
                switch (unit.getUnit()) {

                case (DateTickUnit.MILLISECOND):
                case (DateTickUnit.SECOND):
                case (DateTickUnit.MINUTE):
                case (DateTickUnit.HOUR):
                case (DateTickUnit.DAY):
                    break;

                case (DateTickUnit.MONTH):
                    tickDate = calculateDateForPositionX(new Month(tickDate, getTimeZone()),
                            getTickMarkPosition());

                    break;

                case (DateTickUnit.YEAR):
                    tickDate = calculateDateForPositionX(new Year(tickDate, getTimeZone()),
                            getTickMarkPosition());

                    break;

                default:
                    break;

                }

            }

            return result;

        }

        private Date calculateDateForPositionX(RegularTimePeriod period, DateTickMarkPosition position) {

            if (position == null) {
                throw new IllegalArgumentException("Null 'position' argument.");
            }
            Date result = null;
            if (position == DateTickMarkPosition.START) {
                result = new Date(period.getFirstMillisecond());
            } else if (position == DateTickMarkPosition.MIDDLE) {
                result = new Date(period.getMiddleMillisecond());
            } else if (position == DateTickMarkPosition.END) {
                result = new Date(period.getLastMillisecond());
            }

            return result;

        }

    };
    timeAxis.setDateFormatOverride(sdf);

    final XYPlot[] xyPlotHolder = { null };

    xyPlotHolder[0] = new MyXYPlot(new TimeSeriesCollection(), timeAxis, valueAxis, null) {
        public void drawBackground(Graphics2D g2, Rectangle2D area) {
            super.drawBackground(g2, area);
            drawSunriseSunset(g2, xyPlotHolder[0], area);
        }
    };

    if (animationTimeAnnotation != null) {
        xyPlotHolder[0].addAnnotation(animationTimeAnnotation);
    }

    return xyPlotHolder[0];

}