View Javadoc
1   package org.opentrafficsim.draw.graphs;
2   
3   import java.awt.BasicStroke;
4   import java.awt.Color;
5   import java.awt.Paint;
6   import java.awt.Shape;
7   import java.awt.Stroke;
8   import java.awt.geom.CubicCurve2D;
9   import java.awt.geom.Line2D;
10  import java.util.ArrayList;
11  import java.util.LinkedHashMap;
12  import java.util.List;
13  import java.util.Map;
14  
15  import org.djunits.value.vdouble.scalar.Duration;
16  import org.djunits.value.vdouble.scalar.Length;
17  import org.djunits.value.vdouble.scalar.Time;
18  import org.djutils.exceptions.Try;
19  import org.jfree.chart.JFreeChart;
20  import org.jfree.chart.LegendItem;
21  import org.jfree.chart.LegendItemCollection;
22  import org.jfree.chart.axis.NumberAxis;
23  import org.jfree.chart.entity.EntityCollection;
24  import org.jfree.chart.entity.XYItemEntity;
25  import org.jfree.chart.labels.XYToolTipGenerator;
26  import org.jfree.chart.plot.XYPlot;
27  import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
28  import org.jfree.data.DomainOrder;
29  import org.jfree.data.xy.XYDataset;
30  import org.opentrafficsim.core.animation.gtu.colorer.IDGTUColorer;
31  import org.opentrafficsim.core.dsol.OTSSimulatorInterface;
32  import org.opentrafficsim.draw.core.BoundsPaintScale;
33  import org.opentrafficsim.draw.graphs.GraphPath.Section;
34  import org.opentrafficsim.kpi.sampling.KpiLaneDirection;
35  import org.opentrafficsim.kpi.sampling.SamplerData;
36  import org.opentrafficsim.kpi.sampling.SamplingException;
37  import org.opentrafficsim.kpi.sampling.Trajectory;
38  import org.opentrafficsim.kpi.sampling.TrajectoryGroup;
39  
40  /**
41   * Plot of trajectories along a path.
42   * <p>
43   * Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
44   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
45   * <p>
46   * @version $Revision$, $LastChangedDate$, by $Author$, initial version 13 okt. 2018 <br>
47   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
48   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
49   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
50   */
51  public class TrajectoryPlot extends AbstractSamplerPlot implements XYDataset
52  {
53      /** Single shape to provide due to non-null requirement, but actually not used. */
54      private static final Shape NO_SHAPE = new Line2D.Float(0, 0, 0, 0);
55  
56      /** Color map. */
57      private static final Color[] COLORMAP;
58  
59      /** Strokes. */
60      private static final BasicStroke[] STROKES;
61  
62      /** Shape for the legend entries to draw the line over. */
63      private static final Shape LEGEND_LINE = new CubicCurve2D.Float(-20, 7, -10, -7, 0, 7, 20, -7);
64  
65      /** Updater for update times. */
66      private final GraphUpdater<Time> graphUpdater;
67  
68      /** Counter of the number of trajectories imported per lane. */
69      private final Map<KpiLaneDirection, Integer> knownTrajectories = new LinkedHashMap<>();
70  
71      /** Per lane, mapping from series rank number to trajectory. */
72      private List<List<OffsetTrajectory>> curves = new ArrayList<>();
73  
74      /** Stroke per series. */
75      private List<List<Stroke>> strokes = new ArrayList<>();
76  
77      /** Number of curves per lane. This may be less than the length of {@code List<OffsetTrajectory>} due to concurrency. */
78      private List<Integer> curvesPerLane = new ArrayList<>();
79  
80      /** Legend to change text color to indicate visibility. */
81      private LegendItemCollection legend;
82  
83      /** Whether each lane is visible or not. */
84      private final List<Boolean> laneVisible = new ArrayList<>();
85  
86      static
87      {
88          Color[] c = BoundsPaintScale.hue(6);
89          COLORMAP = new Color[] {c[0], c[4], c[2], c[1], c[3], c[5]};
90          float lw = 0.4f;
91          STROKES = new BasicStroke[] {new BasicStroke(lw, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f, null, 0.0f),
92                  new BasicStroke(lw, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 1.0f, new float[] {13f, 4f}, 0.0f),
93                  new BasicStroke(lw, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 1.0f, new float[] {11f, 3f, 2f, 3f}, 0.0f)};
94      }
95  
96      /**
97       * Constructor.
98       * @param caption String; caption
99       * @param updateInterval Duration; regular update interval (simulation time)
100      * @param simulator OTSSimulatorInterface; simulator
101      * @param samplerData SamplerData&lt;?&gt;; sampler data
102      * @param path GraphPath&lt;KpiLaneDirection&gt;; path
103      */
104     public TrajectoryPlot(final String caption, final Duration updateInterval, final OTSSimulatorInterface simulator,
105             final SamplerData<?> samplerData, final GraphPath<KpiLaneDirection> path)
106     {
107         super(caption, updateInterval, simulator, samplerData, path, Duration.ZERO);
108         for (int i = 0; i < path.getNumberOfSeries(); i++)
109         {
110             this.curves.add(new ArrayList<>());
111             this.strokes.add(new ArrayList<>());
112             this.curvesPerLane.add(0);
113             this.laneVisible.add(true);
114         }
115         setChart(createChart());
116 
117         // setup updater to do the actual work in another thread
118         this.graphUpdater = new GraphUpdater<>("Trajectories worker", Thread.currentThread(), (t) ->
119         {
120             for (Section<KpiLaneDirection> section : path.getSections())
121             {
122                 Length startDistance = path.getStartDistance(section);
123                 for (int i = 0; i < path.getNumberOfSeries(); i++)
124                 {
125                     KpiLaneDirection lane = section.getSource(i);
126                     if (lane == null)
127                     {
128                         continue; // lane is not part of this section, e.g. after a lane-drop
129                     }
130                     TrajectoryGroup<?> trajectoryGroup = getSamplerData().getTrajectoryGroup(lane);
131                     int from = this.knownTrajectories.getOrDefault(lane, 0);
132                     int to = trajectoryGroup.size();
133                     double scaleFactor = section.getLength().si / lane.getLaneData().getLength().si;
134                     for (Trajectory<?> trajectory : trajectoryGroup.getTrajectories().subList(from, to))
135                     {
136                         if (getPath().getNumberOfSeries() > 1)
137                         {
138                             // assign a stroke with random offset, otherwise it will look artificial
139                             BasicStroke stroke = STROKES[i % STROKES.length];
140                             if (stroke.getDashArray() != null)
141                             {
142                                 float dashLength = 0.0f;
143                                 for (float d : stroke.getDashArray())
144                                 {
145                                     dashLength += d;
146                                 }
147                                 stroke = new BasicStroke(stroke.getLineWidth(), stroke.getEndCap(), stroke.getLineJoin(),
148                                         stroke.getMiterLimit(), stroke.getDashArray(), (float) (Math.random() * dashLength));
149                             }
150                             this.strokes.get(i).add(stroke);
151                         }
152                         this.curves.get(i).add(
153                                 new OffsetTrajectory(trajectory, startDistance, scaleFactor, lane.getLaneData().getLength()));
154                     }
155                     this.knownTrajectories.put(lane, to);
156                 }
157             }
158         });
159     }
160 
161     /**
162      * Create a chart.
163      * @return JFreeChart; chart
164      */
165     private JFreeChart createChart()
166     {
167         NumberAxis xAxis = new NumberAxis("Time [s] \u2192");
168         NumberAxis yAxis = new NumberAxis("Distance [m] \u2192");
169         XYLineAndShapeRendererID renderer = new XYLineAndShapeRendererID();
170         XYPlot plot = new XYPlot(this, xAxis, yAxis, renderer);
171         boolean showLegend;
172         if (getPath().getNumberOfSeries() < 2)
173         {
174             plot.setFixedLegendItems(null);
175             showLegend = false;
176         }
177         else
178         {
179             this.legend = new LegendItemCollection();
180             for (int i = 0; i < getPath().getNumberOfSeries(); i++)
181             {
182                 LegendItem li = new LegendItem(getPath().getName(i));
183                 li.setSeriesKey(i); // lane series, not curve series
184                 li.setShape(STROKES[i & STROKES.length].createStrokedShape(LEGEND_LINE));
185                 li.setFillPaint(COLORMAP[i % COLORMAP.length]);
186                 this.legend.add(li);
187             }
188             plot.setFixedLegendItems(this.legend);
189             showLegend = true;
190         }
191         return new JFreeChart(getCaption(), JFreeChart.DEFAULT_TITLE_FONT, plot, showLegend);
192     }
193 
194     /** {@inheritDoc} */
195     @Override
196     public GraphType getGraphType()
197     {
198         return GraphType.TRAJECTORY;
199     }
200 
201     /** {@inheritDoc} */
202     @Override
203     public String getStatusLabel(final double domainValue, final double rangeValue)
204     {
205         return String.format("time %.0fs, distance %.0fm", domainValue, rangeValue);
206     }
207 
208     /** {@inheritDoc} */
209     @Override
210     protected void increaseTime(final Time time)
211     {
212         if (this.graphUpdater != null) // null during construction
213         {
214             this.graphUpdater.offer(time);
215         }
216     }
217 
218     /** {@inheritDoc} */
219     @Override
220     public int getSeriesCount()
221     {
222         int n = 0;
223         for (int i = 0; i < this.curves.size(); i++)
224         {
225             List<OffsetTrajectory> list = this.curves.get(i);
226             int m = list.size();
227             this.curvesPerLane.set(i, m);
228             n += m;
229         }
230         return n;
231     }
232 
233     /** {@inheritDoc} */
234     @Override
235     public Comparable<Integer> getSeriesKey(final int series)
236     {
237         return series;
238     }
239 
240     /** {@inheritDoc} */
241     @SuppressWarnings("rawtypes")
242     @Override
243     public int indexOf(final Comparable seriesKey)
244     {
245         return 0;
246     }
247 
248     /** {@inheritDoc} */
249     @Override
250     public DomainOrder getDomainOrder()
251     {
252         return DomainOrder.ASCENDING;
253     }
254 
255     /** {@inheritDoc} */
256     @Override
257     public int getItemCount(final int series)
258     {
259         OffsetTrajectory trajectory = getTrajectory(series);
260         return trajectory == null ? 0 : trajectory.size();
261     }
262 
263     /** {@inheritDoc} */
264     @Override
265     public Number getX(final int series, final int item)
266     {
267         return getXValue(series, item);
268     }
269 
270     /** {@inheritDoc} */
271     @Override
272     public double getXValue(final int series, final int item)
273     {
274         return getTrajectory(series).getT(item);
275     }
276 
277     /** {@inheritDoc} */
278     @Override
279     public Number getY(final int series, final int item)
280     {
281         return getYValue(series, item);
282     }
283 
284     /** {@inheritDoc} */
285     @Override
286     public double getYValue(final int series, final int item)
287     {
288         return getTrajectory(series).getX(item);
289     }
290 
291     /**
292      * Get the trajectory of the series number.
293      * @param series int; series
294      * @return OffsetTrajectory; trajectory of the series number
295      */
296     private OffsetTrajectory getTrajectory(final int series)
297     {
298         int[] n = getLaneAndSeriesNumber(series);
299         return this.curves.get(n[0]).get(n[1]);
300     }
301 
302     /**
303      * Returns the lane number, and series number within the lane data.
304      * @param series int; overall series number
305      * @return int[]; lane number, and series number within the lane data
306      */
307     private int[] getLaneAndSeriesNumber(final int series)
308     {
309         int n = series;
310         for (int i = 0; i < this.curves.size(); i++)
311         {
312             int m = this.curvesPerLane.get(i);
313             if (n < m)
314             {
315                 return new int[] {i, n};
316             }
317             n -= m;
318         }
319         throw new RuntimeException("Discrepancy between series number and available data.");
320     }
321 
322     /**
323      * Extension of a line renderer to select a color based on GTU ID, and to overrule an unused shape to save memory.
324      * <p>
325      * Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
326      * <br>
327      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
328      * <p>
329      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 14 okt. 2018 <br>
330      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
331      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
332      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
333      */
334     private final class XYLineAndShapeRendererID extends XYLineAndShapeRenderer
335     {
336         /** */
337         private static final long serialVersionUID = 20181014L;
338 
339         /**
340          * Constructor.
341          */
342         XYLineAndShapeRendererID()
343         {
344             super(false, true);
345             setDefaultLinesVisible(true);
346             setDefaultShapesVisible(false);
347             setDrawSeriesLineAsPath(true);
348         }
349 
350         /** {@inheritDoc} */
351         @SuppressWarnings("synthetic-access")
352         @Override
353         public boolean isSeriesVisible(final int series)
354         {
355             int[] n = getLaneAndSeriesNumber(series);
356             return TrajectoryPlot.this.laneVisible.get(n[0]);
357         }
358 
359         /** {@inheritDoc} */
360         @SuppressWarnings("synthetic-access")
361         @Override
362         public Stroke getSeriesStroke(final int series)
363         {
364             if (TrajectoryPlot.this.curves.size() == 1)
365             {
366                 return STROKES[0];
367             }
368             int[] n = getLaneAndSeriesNumber(series);
369             return TrajectoryPlot.this.strokes.get(n[0]).get(n[1]);
370         }
371 
372         /** {@inheritDoc} */
373         @SuppressWarnings("synthetic-access")
374         @Override
375         public Paint getSeriesPaint(final int series)
376         {
377             if (TrajectoryPlot.this.curves.size() == 1)
378             {
379                 String gtuId = getTrajectory(series).getGtuId();
380                 for (int pos = gtuId.length(); --pos >= 0;)
381                 {
382                     Character c = gtuId.charAt(pos);
383                     if (Character.isDigit(c))
384                     {
385                         return IDGTUColorer.LEGEND.get(c - '0').getColor();
386                     }
387                 }
388             }
389             int[] n = getLaneAndSeriesNumber(series);
390             return COLORMAP[n[0] % COLORMAP.length];
391         }
392 
393         /**
394          * {@inheritDoc} Largely based on the super implementation, but returns a dummy shape for markers to save memory and as
395          * markers are not used.
396          */
397         @SuppressWarnings("synthetic-access")
398         @Override
399         protected void addEntity(final EntityCollection entities, final Shape hotspot, final XYDataset dataset,
400                 final int series, final int item, final double entityX, final double entityY)
401         {
402 
403             if (!getItemCreateEntity(series, item))
404             {
405                 return;
406             }
407 
408             // if not hotspot is provided, we create a default based on the
409             // provided data coordinates (which are already in Java2D space)
410             Shape hotspot2 = hotspot == null ? NO_SHAPE : hotspot;
411             String tip = null;
412             XYToolTipGenerator generator = getToolTipGenerator(series, item);
413             if (generator != null)
414             {
415                 tip = generator.generateToolTip(dataset, series, item);
416             }
417             String url = null;
418             if (getURLGenerator() != null)
419             {
420                 url = getURLGenerator().generateURL(dataset, series, item);
421             }
422             XYItemEntity entity = new XYItemEntity(hotspot2, dataset, series, item, tip, url);
423             entities.add(entity);
424         }
425 
426         /** {@inheritDoc} */
427         @Override
428         public String toString()
429         {
430             return "XYLineAndShapeRendererID []";
431         }
432 
433     }
434 
435     /**
436      * Class containing a trajectory with an offset. Takes care of bits that are before and beyond the lane without affecting
437      * the trajectory itself.
438      * <p>
439      * Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
440      * <br>
441      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
442      * <p>
443      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 14 okt. 2018 <br>
444      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
445      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
446      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
447      */
448     private class OffsetTrajectory
449     {
450         /** The trajectory. */
451         private final Trajectory<?> trajectory;
452 
453         /** The offset. */
454         private final double offset;
455 
456         /** Scale factor for space dimension. */
457         private final double scaleFactor;
458 
459         /** First index of the trajectory to include, possibly cutting some measurements before the lane. */
460         private int first;
461 
462         /** Size of the trajectory to consider starting at first, possibly cutting some measurements beyond the lane. */
463         private int size;
464 
465         /** Length of the lane to determine {@code size}. */
466         private final Length laneLength;
467 
468         /**
469          * Construct a new TrajectoryAndLengthOffset object.
470          * @param trajectory Trajectory&lt;?&gt;; the trajectory
471          * @param offset Length; the length from the beginning of the sampled path to the start of the lane to which the
472          *            trajectory belongs
473          * @param scaleFactor double; scale factor for space dimension
474          * @param laneLength Length; length of the lane
475          */
476         OffsetTrajectory(final Trajectory<?> trajectory, final Length offset, final double scaleFactor, final Length laneLength)
477         {
478             this.trajectory = trajectory;
479             this.offset = offset.si;
480             this.scaleFactor = scaleFactor;
481             this.laneLength = laneLength;
482         }
483 
484         /**
485          * Returns the number of measurements in the trajectory.
486          * @return int; number of measurements in the trajectory
487          */
488         public final int size()
489         {
490             // as trajectories grow, this calculation needs to be done on each request
491             try
492             {
493                 /*
494                  * Note on overlap:
495                  * 
496                  * Suppose a GTU crosses a lane boundary producing the following events, where distance e->| is the front, and
497                  * |->l is the tail, relative to the reference point of the GTU.
498                  * @formatter:off
499                  * -------------------------------------------  o) regular move event
500                  *  o     e   o         o |  l    o         o   e) lane enter event on next lane
501                  * -------------------------------------------  l) lane leave event on previous lane
502                  *  o         o         o   (l)                 measurements on previous lane
503                  *       (e) (o)       (o)        o         o   measurements on next lane
504                  * @formatter:on
505                  * Trajectories of a particular GTU are not explicitly tied together. Not only would this involve quite some
506                  * work, it is also impossible to distinguish a lane change near the start or end of a lane, from moving
507                  * longitudinally on to the next lane. The basic idea to minimize overlap is to remove all positions on the
508                  * previous lane beyond the lane length, and all negative positions on the next lane, i.e. all between ( ). This
509                  * would however create a gap at the lane boundary '|'. Allowing one event beyond the lane length may still
510                  * result in a gap, l->o in this case. Allowing one event before the lane would work in this case, but 'e' could
511                  * also fall between an 'o' and '|'. At one trajectory it is thus not known whether the other trajectory
512                  * continues from, or is continued from, the extra point. Hence we require an extra point before the lane and
513                  * one beyond the lane to assure there is no gap. The resulting overlap can be as large as a move, but this is
514                  * better than occasional gaps.
515                  */
516                 int f = 0;
517                 while (f < this.trajectory.size() - 1 && this.trajectory.getX(f + 1) < 0.0)
518                 {
519                     f++;
520                 }
521                 this.first = f;
522                 int s = this.trajectory.size() - 1;
523                 while (s > 1 && this.trajectory.getX(s - 1) > this.laneLength.si)
524                 {
525                     s--;
526                 }
527                 this.size = s - f + 1;
528             }
529             catch (SamplingException exception)
530             {
531                 throw new RuntimeException("Unexpected exception while obtaining location value from trajectory for plotting.",
532                         exception);
533             }
534             return this.size;
535         }
536 
537         /**
538          * Returns the location, including offset, of an item.
539          * @param item int; item (sample) number
540          * @return double; location, including offset, of an item
541          */
542         public final double getX(final int item)
543         {
544             return Try.assign(() -> this.offset + this.trajectory.getX(this.first + item) * this.scaleFactor,
545                     "Unexpected exception while obtaining location value from trajectory for plotting.");
546         }
547 
548         /**
549          * Returns the time of an item.
550          * @param item int; item (sample) number
551          * @return double; time of an item
552          */
553         public final double getT(final int item)
554         {
555             return Try.assign(() -> (double) this.trajectory.getT(this.first + item),
556                     "Unexpected exception while obtaining time value from trajectory for plotting.");
557         }
558 
559         /**
560          * Returns the ID of the GTU of this trajectory.
561          * @return String; the ID of the GTU of this trajectory
562          */
563         public final String getGtuId()
564         {
565             return this.trajectory.getGtuId();
566         }
567 
568         /** {@inheritDoc} */
569         @Override
570         public final String toString()
571         {
572             return "OffsetTrajectory [trajectory=" + this.trajectory + ", offset=" + this.offset + "]";
573         }
574 
575     }
576 
577     /** {@inheritDoc} */
578     @Override
579     public String toString()
580     {
581         return "TrajectoryPlot [graphUpdater=" + this.graphUpdater + ", knownTrajectories=" + this.knownTrajectories
582                 + ", curves=" + this.curves + ", strokes=" + this.strokes + ", curvesPerLane=" + this.curvesPerLane
583                 + ", legend=" + this.legend + ", laneVisible=" + this.laneVisible + "]";
584     }
585 
586     /**
587      * Retrieve the legend.
588      * @return LegendItemCollection; the legend
589      */
590     public LegendItemCollection getLegend()
591     {
592         return this.legend;
593     }
594 
595     /**
596      * Retrieve the lane visibility flags.
597      * @return List&lt;Boolean&gt;; the lane visibility flags
598      */
599     public List<Boolean> getLaneVisible()
600     {
601         return this.laneVisible;
602     }
603 
604 }