001    /* ===========================================================
002     * JFreeChart : a free chart library for the Java(tm) platform
003     * ===========================================================
004     *
005     * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
006     *
007     * Project Info:  http://www.jfree.org/jfreechart/index.html
008     *
009     * This library is free software; you can redistribute it and/or modify it 
010     * under the terms of the GNU Lesser General Public License as published by 
011     * the Free Software Foundation; either version 2.1 of the License, or 
012     * (at your option) any later version.
013     *
014     * This library is distributed in the hope that it will be useful, but 
015     * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
016     * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
017     * License for more details.
018     *
019     * You should have received a copy of the GNU Lesser General Public
020     * License along with this library; if not, write to the Free Software
021     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
022     * USA.  
023     *
024     * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
025     * in the United States and other countries.]
026     *
027     * -------------
028     * XYSeries.java
029     * -------------
030     * (C) Copyright 2001-2005, Object Refinery Limited and Contributors.
031     *
032     * Original Author:  David Gilbert (for Object Refinery Limited);
033     * Contributor(s):   Aaron Metzger;
034     *                   Jonathan Gabbai;
035     *                   Richard Atkinson;
036     *                   Michel Santos;
037     *
038     * $Id: XYSeries.java,v 1.13.2.1 2005/10/25 21:36:51 mungady Exp $
039     *
040     * Changes
041     * -------
042     * 15-Nov-2001 : Version 1 (DG);
043     * 03-Apr-2002 : Added an add(double, double) method (DG);
044     * 29-Apr-2002 : Added a clear() method (ARM);
045     * 06-Jun-2002 : Updated Javadoc comments (DG);
046     * 29-Aug-2002 : Modified to give user control over whether or not duplicate 
047     *               x-values are allowed (DG);
048     * 07-Oct-2002 : Fixed errors reported by Checkstyle (DG);
049     * 11-Nov-2002 : Added maximum item count, code contributed by Jonathan 
050     *               Gabbai (DG);
051     * 26-Mar-2003 : Implemented Serializable (DG);
052     * 04-Aug-2003 : Added getItems() method (DG);
053     * 15-Aug-2003 : Changed 'data' from private to protected, added new add() 
054     *               methods with a 'notify' argument (DG);
055     * 22-Sep-2003 : Added getAllowDuplicateXValues() method (RA);
056     * 29-Jan-2004 : Added autoSort attribute, based on a contribution by 
057     *               Michel Santos - see patch 886740 (DG);
058     * 03-Feb-2004 : Added indexOf() method (DG);
059     * 16-Feb-2004 : Added remove() method (DG);
060     * 18-Aug-2004 : Moved from org.jfree.data --> org.jfree.data.xy (DG);
061     * 21-Feb-2005 : Added update(Number, Number) and addOrUpdate(Number, Number) 
062     *               methods (DG);
063     * 03-May-2005 : Added a new constructor, fixed the setMaximumItemCount() 
064     *               method to remove items (and notify listeners) if necessary, 
065     *               fixed the add() and addOrUpdate() methods to handle unsorted 
066     *               series (DG);
067     *
068     */
069    
070    package org.jfree.data.xy;
071    
072    import java.io.Serializable;
073    import java.util.Collections;
074    import java.util.List;
075    
076    import org.jfree.data.general.Series;
077    import org.jfree.data.general.SeriesChangeEvent;
078    import org.jfree.data.general.SeriesException;
079    import org.jfree.util.ObjectUtilities;
080    
081    /**
082     * Represents a sequence of zero or more data items in the form (x, y).  By 
083     * default, items in the series will be sorted into ascending order by x-value,
084     * and duplicate x-values are permitted.  Both the sorting and duplicate 
085     * defaults can be changed in the constructor.  Y-values can be 
086     * <code>null</code> to represent missing values.
087     */
088    public class XYSeries extends Series implements Cloneable, Serializable {
089    
090        /** For serialization. */
091        static final long serialVersionUID = -5908509288197150436L;
092        
093        // In version 0.9.12, in response to several developer requests, I changed 
094        // the 'data' attribute from 'private' to 'protected', so that others can 
095        // make subclasses that work directly with the underlying data structure.
096    
097        /** Storage for the data items in the series. */
098        protected List data;
099    
100        /** The maximum number of items for the series. */
101        private int maximumItemCount = Integer.MAX_VALUE;
102    
103        /** A flag that controls whether the items are automatically sorted. */
104        private boolean autoSort;
105        
106        /** A flag that controls whether or not duplicate x-values are allowed. */
107        private boolean allowDuplicateXValues;
108    
109        /**
110         * Creates a new empty series.  By default, items added to the series will 
111         * be sorted into ascending order by x-value, and duplicate x-values will 
112         * be allowed (these defaults can be modified with another constructor.
113         *
114         * @param key  the series key (<code>null</code> not permitted).
115         */
116        public XYSeries(Comparable key) {
117            this(key, true, true);
118        }
119    
120        /**
121         * Constructs a new empty series, with the auto-sort flag set as requested,
122         * and duplicate values allowed.  
123         * 
124         * @param key  the series key (<code>null</code> not permitted).
125         * @param autoSort  a flag that controls whether or not the items in the 
126         *                  series are sorted.
127         */
128        public XYSeries(Comparable key, boolean autoSort) {
129            this(key, autoSort, true);
130        }
131    
132        /**
133         * Constructs a new xy-series that contains no data.  You can specify 
134         * whether or not duplicate x-values are allowed for the series.
135         *
136         * @param key  the series key (<code>null</code> not permitted).
137         * @param autoSort  a flag that controls whether or not the items in the 
138         *                  series are sorted.
139         * @param allowDuplicateXValues  a flag that controls whether duplicate 
140         *                               x-values are allowed.
141         */
142        public XYSeries(Comparable key, 
143                        boolean autoSort, 
144                        boolean allowDuplicateXValues) {
145            super(key);
146            this.data = new java.util.ArrayList();
147            this.autoSort = autoSort;
148            this.allowDuplicateXValues = allowDuplicateXValues;
149        }
150    
151        /**
152         * Returns the flag that controls whether the items in the series are 
153         * automatically sorted.  There is no setter for this flag, it must be 
154         * defined in the series constructor.
155         * 
156         * @return A boolean.
157         */
158        public boolean getAutoSort() {
159            return this.autoSort;
160        }
161        
162        /**
163         * Returns a flag that controls whether duplicate x-values are allowed.  
164         * This flag can only be set in the constructor.
165         *
166         * @return A boolean.
167         */
168        public boolean getAllowDuplicateXValues() {
169            return this.allowDuplicateXValues;
170        }
171    
172        /**
173         * Returns the number of items in the series.
174         *
175         * @return The item count.
176         */
177        public int getItemCount() {
178            return this.data.size();
179        }
180    
181        /**
182         * Returns the list of data items for the series (the list contains 
183         * {@link XYDataItem} objects and is unmodifiable).
184         * 
185         * @return The list of data items.
186         */
187        public List getItems() {
188            return Collections.unmodifiableList(this.data);    
189        }
190        
191        /**
192         * Returns the maximum number of items that will be retained in the series.
193         * The default value is <code>Integer.MAX_VALUE</code>.
194         *
195         * @return The maximum item count.
196         * @see #setMaximumItemCount(int)
197         */
198        public int getMaximumItemCount() {
199            return this.maximumItemCount;
200        }
201    
202        /**
203         * Sets the maximum number of items that will be retained in the series.  
204         * If you add a new item to the series such that the number of items will 
205         * exceed the maximum item count, then the first element in the series is 
206         * automatically removed, ensuring that the maximum item count is not 
207         * exceeded.
208         * <p>
209         * Typically this value is set before the series is populated with data,
210         * but if it is applied later, it may cause some items to be removed from
211         * the series (in which case a {@link SeriesChangeEvent} will be sent to
212         * all registered listeners.
213         *
214         * @param maximum  the maximum number of items for the series.
215         */
216        public void setMaximumItemCount(int maximum) {
217            this.maximumItemCount = maximum;
218            boolean dataRemoved = false;
219            while (this.data.size() > maximum) {
220                this.data.remove(0);   
221                dataRemoved = true;
222            }
223            if (dataRemoved) {
224                fireSeriesChanged();
225            }
226        }
227    
228        /**
229         * Adds a data item to the series and sends a {@link SeriesChangeEvent} to 
230         * all registered listeners.
231         *
232         * @param item  the (x, y) item (<code>null</code> not permitted).
233         */
234        public void add(XYDataItem item) {
235            // argument checking delegated...
236            add(item, true);
237        }
238        
239        /**
240         * Adds a data item to the series and sends a {@link SeriesChangeEvent} to 
241         * all registered listeners.
242         *
243         * @param x  the x value.
244         * @param y  the y value.
245         */
246        public void add(double x, double y) {
247            add(new Double(x), new Double(y), true);
248        }
249    
250        /**
251         * Adds a data item to the series and, if requested, sends a 
252         * {@link SeriesChangeEvent} to all registered listeners.
253         *
254         * @param x  the x value.
255         * @param y  the y value.
256         * @param notify  a flag that controls whether or not a 
257         *                {@link SeriesChangeEvent} is sent to all registered 
258         *                listeners.
259         */
260        public void add(double x, double y, boolean notify) {
261            add(new Double(x), new Double(y), notify);
262        }
263    
264        /**
265         * Adds a data item to the series and sends a {@link SeriesChangeEvent} to 
266         * all registered listeners.  The unusual pairing of parameter types is to 
267         * make it easier to add <code>null</code> y-values.
268         *
269         * @param x  the x value.
270         * @param y  the y value (<code>null</code> permitted).
271         */
272        public void add(double x, Number y) {
273            add(new Double(x), y);
274        }
275    
276        /**
277         * Adds a data item to the series and, if requested, sends a 
278         * {@link SeriesChangeEvent} to all registered listeners.  The unusual 
279         * pairing of parameter types is to make it easier to add null y-values.
280         *
281         * @param x  the x value.
282         * @param y  the y value (<code>null</code> permitted).
283         * @param notify  a flag that controls whether or not a 
284         *                {@link SeriesChangeEvent} is sent to all registered 
285         *                listeners.
286         */
287        public void add(double x, Number y, boolean notify) {
288            add(new Double(x), y, notify);
289        }
290    
291        /**
292         * Adds new data to the series and sends a {@link SeriesChangeEvent} to 
293         * all registered listeners.
294         * <P>
295         * Throws an exception if the x-value is a duplicate AND the 
296         * allowDuplicateXValues flag is false.
297         *
298         * @param x  the x-value (<code>null</code> not permitted).
299         * @param y  the y-value (<code>null</code> permitted).
300         */
301        public void add(Number x, Number y) {
302            // argument checking delegated...
303            add(x, y, true);
304        }
305        
306        /**
307         * Adds new data to the series and, if requested, sends a 
308         * {@link SeriesChangeEvent} to all registered listeners.
309         * <P>
310         * Throws an exception if the x-value is a duplicate AND the 
311         * allowDuplicateXValues flag is false.
312         *
313         * @param x  the x-value (<code>null</code> not permitted).
314         * @param y  the y-value (<code>null</code> permitted).
315         * @param notify  a flag the controls whether or not a 
316         *                {@link SeriesChangeEvent} is sent to all registered 
317         *                listeners.
318         */
319        public void add(Number x, Number y, boolean notify) {
320            if (x == null) {
321                throw new IllegalArgumentException("Null 'x' argument.");
322            }
323            XYDataItem item = new XYDataItem(x, y);
324            add(item, notify);
325        }
326    
327        /**
328         * Adds a data item to the series and, if requested, sends a 
329         * {@link SeriesChangeEvent} to all registered listeners.
330         *
331         * @param item  the (x, y) item (<code>null</code> not permitted).
332         * @param notify  a flag that controls whether or not a 
333         *                {@link SeriesChangeEvent} is sent to all registered 
334         *                listeners.
335         */
336        public void add(XYDataItem item, boolean notify) {
337    
338            if (item == null) {
339                throw new IllegalArgumentException("Null 'item' argument.");
340            }
341    
342            if (this.autoSort) {
343                int index = Collections.binarySearch(this.data, item);
344                if (index < 0) {
345                    this.data.add(-index - 1, item);
346                }
347                else {
348                    if (this.allowDuplicateXValues) {
349                        // need to make sure we are adding *after* any duplicates
350                        int size = this.data.size();
351                        while (index < size 
352                               && item.compareTo(this.data.get(index)) == 0) {
353                            index++;
354                        }
355                        if (index < this.data.size()) {
356                            this.data.add(index, item);
357                        }
358                        else {
359                            this.data.add(item);
360                        }
361                    }
362                    else {
363                        throw new SeriesException("X-value already exists.");
364                    }
365                }
366            }
367            else {
368                if (!this.allowDuplicateXValues) {
369                    // can't allow duplicate values, so we need to check whether
370                    // there is an item with the given x-value already
371                    int index = indexOf(item.getX());
372                    if (index >= 0) {
373                        throw new SeriesException("X-value already exists.");      
374                    }
375                }
376                this.data.add(item);
377            }
378            if (getItemCount() > this.maximumItemCount) {
379                this.data.remove(0);
380            }                    
381            if (notify) {
382                fireSeriesChanged();
383            }
384        }
385    
386        /**
387         * Deletes a range of items from the series and sends a 
388         * {@link SeriesChangeEvent} to all registered listeners.
389         *
390         * @param start  the start index (zero-based).
391         * @param end  the end index (zero-based).
392         */
393        public void delete(int start, int end) {
394            for (int i = start; i <= end; i++) {
395                this.data.remove(start);
396            }
397            fireSeriesChanged();
398        }
399    
400        /**
401         * Removes the item at the specified index and sends a 
402         * {@link SeriesChangeEvent} to all registered listeners.
403         * 
404         * @param index  the index.
405         * 
406         * @return The item removed.
407         */
408        public XYDataItem remove(int index) {
409            XYDataItem result = (XYDataItem) this.data.remove(index);
410            fireSeriesChanged();
411            return result;
412        }
413        
414        /**
415         * Removes the item with the specified x-value and sends a 
416         * {@link SeriesChangeEvent} to all registered listeners.
417         * 
418         * @param x  the x-value.
419    
420         * @return The item removed.
421         */
422        public XYDataItem remove(Number x) {
423            return remove(indexOf(x));
424        }
425        
426        /**
427         * Removes all data items from the series.
428         */
429        public void clear() {
430            if (this.data.size() > 0) {
431                this.data.clear();
432                fireSeriesChanged();
433            }
434        }
435    
436        /**
437         * Return the data item with the specified index.
438         *
439         * @param index  the index.
440         *
441         * @return The data item with the specified index.
442         */
443        public XYDataItem getDataItem(int index) {
444            return (XYDataItem) this.data.get(index);
445        }
446    
447        /**
448         * Returns the x-value at the specified index.
449         *
450         * @param index  the index (zero-based).
451         *
452         * @return The x-value (never <code>null</code>).
453         */
454        public Number getX(int index) {
455            return getDataItem(index).getX();
456        }
457    
458        /**
459         * Returns the y-value at the specified index.
460         *
461         * @param index  the index (zero-based).
462         *
463         * @return The y-value (possibly <code>null</code>).
464         */
465        public Number getY(int index) {
466            return getDataItem(index).getY();
467        }
468    
469        /**
470         * Updates the value of an item in the series and sends a 
471         * {@link SeriesChangeEvent} to all registered listeners.
472         *
473         * @param index  the item (zero based index).
474         * @param y  the new value (<code>null</code> permitted).
475         */
476        public void update(int index, Number y) {
477            XYDataItem item = getDataItem(index);
478            item.setY(y);
479            fireSeriesChanged();
480        }
481        
482        /**
483         * Updates an item in the series.
484         * 
485         * @param x  the x-value (<code>null</code> not permitted).
486         * @param y  the y-value (<code>null</code> permitted).
487         * 
488         * @throws SeriesException if there is no existing item with the specified
489         *         x-value.
490         */
491        public void update(Number x, Number y) {
492            int index = indexOf(x);
493            if (index < 0) {
494                throw new SeriesException("No observation for x = " + x);
495            }
496            else {
497                XYDataItem item = getDataItem(index);
498                item.setY(y);
499                fireSeriesChanged();
500            }
501        }
502        
503        /**
504         * Adds or updates an item in the series and sends a 
505         * {@link org.jfree.data.general.SeriesChangeEvent} to all registered 
506         * listeners.
507         *
508         * @param x  the x-value (<code>null</code> not permitted).
509         * @param y  the y-value (<code>null</code> permitted).
510         *
511         * @return A copy of the overwritten data item, or <code>null</code> if no 
512         *         item was overwritten.
513         */
514        public XYDataItem addOrUpdate(Number x, Number y) {
515            if (x == null) {
516                throw new IllegalArgumentException("Null 'x' argument.");   
517            }
518            XYDataItem overwritten = null;
519            int index = indexOf(x);
520            if (index >= 0) {
521                XYDataItem existing = (XYDataItem) this.data.get(index);
522                try {
523                    overwritten = (XYDataItem) existing.clone();
524                }
525                catch (CloneNotSupportedException e) {
526                    throw new SeriesException("Couldn't clone XYDataItem!");   
527                }
528                existing.setY(y);
529            }
530            else {
531                // if the series is sorted, the negative index is a result from
532                // Collections.binarySearch() and tells us where to insert the
533                // new item...otherwise it will be just -1 and we should just
534                // append the value to the list...
535                if (this.autoSort) {
536                    this.data.add(-index - 1, new XYDataItem(x, y));
537                }
538                else {
539                    this.data.add(new XYDataItem(x, y));
540                }
541                // check if this addition will exceed the maximum item count...
542                if (getItemCount() > this.maximumItemCount) {
543                    this.data.remove(0);
544                }
545            }            
546            fireSeriesChanged();
547            return overwritten;
548        }
549    
550        /**
551         * Returns the index of the item with the specified x-value, or a negative 
552         * index if the series does not contain an item with that x-value.  Be 
553         * aware that for an unsorted series, the index is found by iterating 
554         * through all items in the series.
555         * 
556         * @param x  the x-value (<code>null</code> not permitted).
557         * 
558         * @return The index.
559         */
560        public int indexOf(Number x) {
561            if (this.autoSort) {
562                return Collections.binarySearch(this.data, new XYDataItem(x, null));   
563            }
564            else {
565                for (int i = 0; i < this.data.size(); i++) {
566                    XYDataItem item = (XYDataItem) this.data.get(i);
567                    if (item.getX().equals(x)) {
568                        return i;   
569                    }
570                }
571                return -1;
572            }
573        } 
574        
575        /**
576         * Returns a clone of the series.
577         *
578         * @return A clone of the time series.
579         * 
580         * @throws CloneNotSupportedException if there is a cloning problem.
581         */
582        public Object clone() throws CloneNotSupportedException {
583            Object clone = createCopy(0, getItemCount() - 1);
584            return clone;
585        }
586    
587        /**
588         * Creates a new series by copying a subset of the data in this time series.
589         *
590         * @param start  the index of the first item to copy.
591         * @param end  the index of the last item to copy.
592         *
593         * @return A series containing a copy of this series from start until end.
594         * 
595         * @throws CloneNotSupportedException if there is a cloning problem.
596         */
597        public XYSeries createCopy(int start, int end) 
598            throws CloneNotSupportedException {
599    
600            XYSeries copy = (XYSeries) super.clone();
601            copy.data = new java.util.ArrayList();
602            if (this.data.size() > 0) {
603                for (int index = start; index <= end; index++) {
604                    XYDataItem item = (XYDataItem) this.data.get(index);
605                    XYDataItem clone = (XYDataItem) item.clone();
606                    try {
607                        copy.add(clone);
608                    }
609                    catch (SeriesException e) {
610                        System.err.println("Unable to add cloned data item.");
611                    }
612                }
613            }
614            return copy;
615    
616        }
617    
618        /**
619         * Tests this series for equality with an arbitrary object.
620         *
621         * @param obj  the object to test against for equality 
622         *             (<code>null</code> permitted).
623         *
624         * @return A boolean.
625         */
626        public boolean equals(Object obj) {
627            if (obj == this) {
628                return true;
629            }
630            if (!(obj instanceof XYSeries)) {
631                return false;
632            }
633            if (!super.equals(obj)) {
634                return false;
635            }
636            XYSeries that = (XYSeries) obj;
637            if (this.maximumItemCount != that.maximumItemCount) {
638                return false;
639            }
640            if (this.autoSort != that.autoSort) {
641                return false;
642            }
643            if (this.allowDuplicateXValues != that.allowDuplicateXValues) {
644                return false;
645            }
646            if (!ObjectUtilities.equal(this.data, that.data)) {
647                return false;
648            }
649            return true;
650        }
651        
652        /**
653         * Returns a hash code.
654         * 
655         * @return A hash code.
656         */
657        public int hashCode() {
658            int result = super.hashCode();
659            result = 29 * result + (this.data != null ? this.data.hashCode() : 0);
660            result = 29 * result + this.maximumItemCount;
661            result = 29 * result + (this.autoSort ? 1 : 0);
662            result = 29 * result + (this.allowDuplicateXValues ? 1 : 0);
663            return result;
664        }
665    
666    }
667