View Javadoc
1   package org.opentrafficsim.demo.conflictAndControl;
2   
3   import static org.opentrafficsim.core.gtu.GTUType.CAR;
4   import static org.opentrafficsim.core.gtu.GTUType.VEHICLE;
5   
6   import java.awt.BorderLayout;
7   import java.awt.geom.Rectangle2D;
8   import java.awt.geom.Rectangle2D.Double;
9   import java.net.URL;
10  import java.rmi.RemoteException;
11  import java.util.ArrayList;
12  import java.util.HashSet;
13  import java.util.LinkedHashSet;
14  import java.util.Set;
15  
16  import javax.naming.NamingException;
17  import javax.swing.JPanel;
18  import javax.swing.JScrollPane;
19  import javax.swing.SwingUtilities;
20  
21  import org.djunits.unit.AccelerationUnit;
22  import org.djunits.unit.DurationUnit;
23  import org.djunits.unit.LengthUnit;
24  import org.djunits.value.vdouble.scalar.Acceleration;
25  import org.djunits.value.vdouble.scalar.Duration;
26  import org.djunits.value.vdouble.scalar.Length;
27  import org.djunits.value.vdouble.scalar.Speed;
28  import org.djunits.value.vdouble.scalar.Time;
29  import org.opentrafficsim.base.modelproperties.Property;
30  import org.opentrafficsim.base.modelproperties.PropertyException;
31  import org.opentrafficsim.base.parameters.Parameters;
32  import org.opentrafficsim.core.compatibility.Compatible;
33  import org.opentrafficsim.core.dsol.OTSModelInterface;
34  import org.opentrafficsim.core.geometry.OTSGeometryException;
35  import org.opentrafficsim.core.gtu.GTUDirectionality;
36  import org.opentrafficsim.core.gtu.GTUException;
37  import org.opentrafficsim.core.gtu.GTUType;
38  import org.opentrafficsim.core.gtu.RelativePosition;
39  import org.opentrafficsim.core.gtu.animation.GTUColorer;
40  import org.opentrafficsim.core.network.NetworkException;
41  import org.opentrafficsim.core.network.OTSNetwork;
42  import org.opentrafficsim.demo.carFollowing.DefaultsFactory;
43  import org.opentrafficsim.road.animation.AnimationToggles;
44  import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
45  import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
46  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
47  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
48  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
49  import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
50  import org.opentrafficsim.road.network.factory.xml.XmlNetworkLaneParser;
51  import org.opentrafficsim.road.network.lane.CrossSectionLink;
52  import org.opentrafficsim.road.network.lane.CrossSectionLink.Priority;
53  import org.opentrafficsim.road.network.lane.DirectedLanePosition;
54  import org.opentrafficsim.road.network.lane.Lane;
55  import org.opentrafficsim.road.network.lane.conflict.ConflictBuilder;
56  import org.opentrafficsim.road.network.lane.object.sensor.TrafficLightSensor;
57  import org.opentrafficsim.road.network.lane.object.trafficlight.SimpleTrafficLight;
58  import org.opentrafficsim.road.network.lane.object.trafficlight.TrafficLight;
59  import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
60  import org.opentrafficsim.simulationengine.OTSSimulationException;
61  import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
62  import org.opentrafficsim.trafficcontrol.TrafficController;
63  import org.opentrafficsim.trafficcontrol.trafcod.TrafCOD;
64  
65  import nl.tudelft.simulation.dsol.SimRuntimeException;
66  import nl.tudelft.simulation.dsol.simtime.SimTimeDoubleUnit;
67  import nl.tudelft.simulation.dsol.simulators.DEVSSimulator;
68  import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
69  import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
70  import nl.tudelft.simulation.event.EventInterface;
71  import nl.tudelft.simulation.event.EventListenerInterface;
72  import nl.tudelft.simulation.event.EventProducer;
73  import nl.tudelft.simulation.event.EventType;
74  import nl.tudelft.simulation.language.io.URLResource;
75  
76  /**
77   * <p>
78   * Copyright (c) 2013-2018 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
79   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
80   * <p>
81   * @version $Revision: 4006 $, $LastChangedDate: 2018-09-19 13:55:45 +0200 (Wed, 19 Sep 2018) $, by $Author: averbraeck $,
82   *          initial version Dec 06, 2016 <br>
83   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
84   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
85   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
86   */
87  public class DemoTrafcodAndTurbo extends AbstractWrappableAnimation
88  {
89  
90      /** */
91      private static final long serialVersionUID = 20161118L;
92  
93      /**
94       * Main program.
95       * @param args String[]; the command line arguments (not used)
96       * @throws SimRuntimeException should never happen
97       */
98      public static void main(final String[] args) throws SimRuntimeException
99      {
100         SwingUtilities.invokeLater(new Runnable()
101         {
102             @Override
103             public void run()
104             {
105                 try
106                 {
107                     DemoTrafcodAndTurbo model = new DemoTrafcodAndTurbo();
108                     // 1 hour simulation run for testing
109                     model.buildAnimator(Time.ZERO, Duration.ZERO, new Duration(60.0, DurationUnit.MINUTE),
110                             new ArrayList<Property<?>>(), null, true);
111                 }
112                 catch (SimRuntimeException | NamingException | OTSSimulationException | PropertyException exception)
113                 {
114                     exception.printStackTrace();
115                 }
116             }
117         });
118     }
119 
120     /** TrafCOD controller display. */
121     private JPanel controllerDisplayPanel = new JPanel(new BorderLayout());
122 
123     /** The TrafCOD controller. */
124     TrafCOD trafCOD;
125 
126     /** {@inheritDoc} */
127     @Override
128     public final String shortName()
129     {
130         return "TrafCOD demonstration 2";
131     }
132 
133     /** {@inheritDoc} */
134     @Override
135     public final String description()
136     {
137         return "TrafCOD demonstration";
138     }
139 
140     /** {@inheritDoc} */
141     @Override
142     protected final void addTabs(final SimpleSimulatorInterface simulator) throws OTSSimulationException, PropertyException
143     {
144         JScrollPane scrollPane = new JScrollPane(DemoTrafcodAndTurbo.this.controllerDisplayPanel);
145         JPanel wrapper = new JPanel(new BorderLayout());
146         wrapper.add(scrollPane);
147         addTab(getTabCount() - 1, this.trafCOD.getId(), wrapper);
148     }
149 
150     /** {@inheritDoc} */
151     @Override
152     protected final OTSModelInterface makeModel() throws OTSSimulationException
153     {
154         return new TrafCODModel();
155     }
156 
157     /** {@inheritDoc} */
158     @Override
159     protected final void addAnimationToggles()
160     {
161         AnimationToggles.setTextAnimationTogglesStandard(this);
162     }
163 
164     /** {@inheritDoc} */
165     @Override
166     protected final Double makeAnimationRectangle()
167     {
168         return new Rectangle2D.Double(-200, -200, 400, 400);
169     }
170 
171     /**
172      * The simulation model.
173      */
174     class TrafCODModel extends EventProducer implements OTSModelInterface, EventListenerInterface
175     {
176         /** */
177         private static final long serialVersionUID = 20161020L;
178 
179         /** The network. */
180         private OTSNetwork network;
181 
182         @SuppressWarnings("synthetic-access")
183         @Override
184         public void constructModel(final SimulatorInterface<Time, Duration, SimTimeDoubleUnit> theSimulator)
185                 throws SimRuntimeException
186         {
187             try
188             {
189                 URL url = URLResource.getResource("/conflictAndControl/TurboRoundaboutAndSignal.xml");
190                 XmlNetworkLaneParser nlp = new XmlNetworkLaneParser((DEVSSimulatorInterface.TimeDoubleUnit) theSimulator);
191                 this.network = nlp.build(url, true);
192                 // add conflicts
193                 ((CrossSectionLink) this.network.getLink("EBNA")).setPriority(Priority.PRIORITY);
194                 ((CrossSectionLink) this.network.getLink("NBWA")).setPriority(Priority.PRIORITY);
195                 ((CrossSectionLink) this.network.getLink("WBSA")).setPriority(Priority.PRIORITY);
196                 ((CrossSectionLink) this.network.getLink("SBEA")).setPriority(Priority.PRIORITY);
197                 ConflictBuilder.buildConflicts(this.network, VEHICLE, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
198                         new ConflictBuilder.FixedWidthGenerator(new Length(2.0, LengthUnit.SI)));
199 
200                 // CrossSectionLink csLink = ((CrossSectionLink)
201                 // this.network.getLink("WWW"));
202                 // Lane lane = (Lane) csLink.getCrossSectionElement("RIGHT");
203                 // GTUColorer gtuColorer = null;
204                 // setupBlock(lane, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
205                 // gtuColorer );
206 
207                 String[] directions = { "E", "S", "W", "N" };
208                 // Add the traffic lights and the detectors
209                 Set<TrafficLight> trafficLights = new HashSet<>();
210                 Set<TrafficLightSensor> sensors = new HashSet<>();
211                 Length stopLineMargin = new Length(0.1, LengthUnit.METER);
212                 Length headDetectorLength = new Length(1, LengthUnit.METER);
213                 Length headDetectorMargin = stopLineMargin.plus(headDetectorLength).plus(new Length(3, LengthUnit.METER));
214                 Length longDetectorLength = new Length(30, LengthUnit.METER);
215                 Length longDetectorMargin = stopLineMargin.plus(longDetectorLength).plus(new Length(10, LengthUnit.METER));
216                 int stream = 1;
217                 for (String direction : directions)
218                 {
219                     for (int laneNumber = 3; laneNumber >= 1; laneNumber--)
220                     {
221                         Lane lane = (Lane) ((CrossSectionLink) this.network.getLink(direction + "S", direction + "C"))
222                                 .getCrossSectionElement("FORWARD" + laneNumber);
223                         if (lane != null)
224                         {
225                             if (stream != 7)
226                             {
227                                 trafficLights.add(new SimpleTrafficLight(String.format("TL%02d", stream), lane,
228                                         lane.getLength().minus(stopLineMargin), (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator));
229                                 sensors.add(new TrafficLightSensor(String.format("D%02d1", stream), lane,
230                                         lane.getLength().minus(headDetectorMargin), lane,
231                                         lane.getLength().minus(headDetectorMargin).plus(headDetectorLength), null,
232                                         RelativePosition.FRONT, RelativePosition.REAR, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
233                                         Compatible.EVERYTHING));
234                                 sensors.add(new TrafficLightSensor(String.format("D%02d2", stream), lane,
235                                         lane.getLength().minus(longDetectorMargin), lane,
236                                         lane.getLength().minus(longDetectorMargin).plus(longDetectorLength), null,
237                                         RelativePosition.FRONT, RelativePosition.REAR, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
238                                         Compatible.EVERYTHING));
239                             }
240                             else
241                             {
242                                 lane = (Lane) ((CrossSectionLink) this.network.getLink("ESS1", "ESS"))
243                                         .getCrossSectionElement("FORWARD");
244                                 trafficLights.add(new SimpleTrafficLight(String.format("TL%02d", stream), lane,
245                                         lane.getLength().minus(stopLineMargin), (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator));
246                                 sensors.add(new TrafficLightSensor(String.format("D%02d1", stream), lane,
247                                         lane.getLength().minus(headDetectorMargin), lane,
248                                         lane.getLength().minus(headDetectorMargin).plus(headDetectorLength), null,
249                                         RelativePosition.FRONT, RelativePosition.REAR, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
250                                         Compatible.EVERYTHING));
251                                 sensors.add(new TrafficLightSensor(String.format("D%02d2", stream), lane,
252                                         lane.getLength().minus(longDetectorMargin), lane,
253                                         lane.getLength().minus(longDetectorMargin).plus(longDetectorLength), null,
254                                         RelativePosition.FRONT, RelativePosition.REAR, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
255                                         Compatible.EVERYTHING));
256 
257                             }
258 
259                         }
260                         stream++;
261                     }
262                 }
263                 String controllerName = "Not so simple TrafCOD controller";
264                 DemoTrafcodAndTurbo.this.trafCOD =
265                         new TrafCOD(controllerName, URLResource.getResource("/conflictAndControl/Intersection12Dir.tfc"),
266                                 trafficLights, sensors, (DEVSSimulator<Time, Duration, SimTimeDoubleUnit>) theSimulator,
267                                 DemoTrafcodAndTurbo.this.controllerDisplayPanel);
268                 DemoTrafcodAndTurbo.this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING);
269                 DemoTrafcodAndTurbo.this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING);
270                 DemoTrafcodAndTurbo.this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED);
271                 DemoTrafcodAndTurbo.this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_STATE_CHANGED);
272                 DemoTrafcodAndTurbo.this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_VARIABLE_CREATED);
273                 DemoTrafcodAndTurbo.this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED);
274                 // Subscribe the TrafCOD machine to trace command events that we
275                 // emit
276                 addListener(DemoTrafcodAndTurbo.this.trafCOD, TrafficController.TRAFFICCONTROL_SET_TRACING);
277                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new
278                 // Object[] {controllerName, "TGX", 8, true});
279                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new
280                 // Object[] {controllerName, "XR1", 11, true});
281                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new
282                 // Object[] {controllerName, "TD1", 11, true});
283                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new
284                 // Object[] {controllerName, "TGX", 11, true});
285                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new
286                 // Object[] {controllerName, "TL", 11, true});
287                 // System.out.println("demo: emitting a SET TRACING event for
288                 // all variables related to stream 11");
289                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new
290                 // Object[] { controllerName, "", 11, true });
291 
292                 // TrafCODDemo2.this.trafCOD.traceVariablesOfStream(TrafficController.NO_STREAM,
293                 // true);
294                 // TrafCODDemo2.this.trafCOD.traceVariablesOfStream(11, true);
295                 // TrafCODDemo2.this.trafCOD.traceVariable("MRV", 11, true);
296             }
297             catch (Exception exception)
298             {
299                 exception.printStackTrace();
300             }
301         }
302 
303         @Override
304         public SimulatorInterface<Time, Duration, SimTimeDoubleUnit> getSimulator()
305         {
306             return DemoTrafcodAndTurbo.this.trafCOD.getSimulator();
307         }
308 
309         /** {@inheritDoc} */
310         @Override
311         public final OTSNetwork getNetwork()
312         {
313             return this.network;
314         }
315 
316         /** {@inheritDoc} */
317         @Override
318         public void notify(final EventInterface event) throws RemoteException
319         {
320             EventType type = event.getType();
321             Object[] payload = (Object[]) event.getContent();
322             if (TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING.equals(type))
323             {
324                 // System.out.println("Evaluation starts at " +
325                 // getSimulator().getSimulatorTime());
326                 return;
327             }
328             else if (TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED.equals(type))
329             {
330                 System.out.println("Conflict group changed from " + ((String) payload[1]) + " to " + ((String) payload[2]));
331             }
332             else if (TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED.equals(type))
333             {
334                 System.out.println(String.format("Variable changed %s <- %d   %s", payload[1], payload[4], payload[5]));
335             }
336             else if (TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING.equals(type))
337             {
338                 System.out.println("Warning " + payload[1]);
339             }
340             else
341             {
342                 System.out.print("TrafCODDemo received event of type " + event.getType() + ", payload [");
343                 String separator = "";
344                 for (Object o : payload)
345                 {
346                     System.out.print(separator + o);
347                     separator = ",";
348                 }
349                 System.out.println("]");
350             }
351         }
352 
353         /**
354          * Put a block at the end of a Lane.
355          * @param lane Lane; the lane on which the block is placed
356          * @param theSimulator the simulator
357          * @param gtuColorer the gtu colorer to use
358          * @return Lane; the lane
359          * @throws NamingException on ???
360          * @throws NetworkException on network inconsistency
361          * @throws SimRuntimeException on ???
362          * @throws GTUException when construction of the GTU (the block is a GTU) fails
363          * @throws OTSGeometryException when the initial path is wrong
364          */
365         private Lane setupBlock(final Lane lane, final DEVSSimulatorInterface.TimeDoubleUnit theSimulator, final GTUColorer gtuColorer)
366                 throws NamingException, NetworkException, SimRuntimeException, GTUException, OTSGeometryException
367         {
368             Length initialPosition = lane.getLength();
369             Duration tSafe = new Duration(0, DurationUnit.SECOND);
370             Acceleration ac1 = new Acceleration(1.0, AccelerationUnit.METER_PER_SECOND_2);
371             Length l = new Length(1.0, LengthUnit.METER);
372             IDMPlusOld carFollowingModelCars = new IDMPlusOld(ac1, ac1, l, tSafe, 1.0);
373             Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
374             initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS));
375             GTUType gtuType = CAR;
376             Parameters parameters = DefaultsFactory.getDefaultParameters();
377             LaneBasedIndividualGTU block = new LaneBasedIndividualGTU("999999", gtuType, new Length(1, LengthUnit.METER),
378                     lane.getWidth(1), Speed.ZERO, Length.createSI(0.5), theSimulator, this.network);
379             LaneBasedStrategicalPlanner strategicalPlanner = new LaneBasedStrategicalRoutePlanner(
380                     new LaneBasedGTUFollowingTacticalPlanner(carFollowingModelCars, block), block);
381             block.setParameters(parameters);
382             block.initWithAnimation(strategicalPlanner, initialPositions, Speed.ZERO, DefaultCarAnimation.class, gtuColorer);
383             return lane;
384         }
385 
386     }
387 
388 }