1 package org.opentrafficsim.demo.carFollowing;
2
3 import java.awt.Container;
4 import java.awt.Frame;
5 import java.awt.geom.Rectangle2D;
6 import java.rmi.RemoteException;
7 import java.util.ArrayList;
8 import java.util.Iterator;
9 import java.util.LinkedHashMap;
10 import java.util.List;
11 import java.util.Map;
12 import java.util.Random;
13
14 import javax.naming.NamingException;
15 import javax.swing.JPanel;
16
17 import nl.tudelft.simulation.dsol.SimRuntimeException;
18 import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
19 import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
20 import nl.tudelft.simulation.jstats.distributions.DistContinuous;
21 import nl.tudelft.simulation.jstats.distributions.DistErlang;
22 import nl.tudelft.simulation.jstats.streams.MersenneTwister;
23
24 import org.djunits.unit.AccelerationUnit;
25 import org.djunits.unit.TimeUnit;
26 import org.djunits.value.vdouble.scalar.DoubleScalar;
27 import org.djunits.value.vdouble.scalar.DoubleScalar.Abs;
28 import org.opentrafficsim.core.OTS_SCALAR;
29 import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
30 import org.opentrafficsim.core.dsol.OTSModelInterface;
31 import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
32 import org.opentrafficsim.core.geometry.OTSGeometryException;
33 import org.opentrafficsim.core.geometry.OTSPoint3D;
34 import org.opentrafficsim.core.gtu.GTUException;
35 import org.opentrafficsim.core.gtu.GTUType;
36 import org.opentrafficsim.core.gtu.animation.GTUColorer;
37 import org.opentrafficsim.core.network.LongitudinalDirectionality;
38 import org.opentrafficsim.core.network.NetworkException;
39 import org.opentrafficsim.core.network.Node;
40 import org.opentrafficsim.core.network.OTSNode;
41 import org.opentrafficsim.core.network.route.CompleteRoute;
42 import org.opentrafficsim.graphs.LaneBasedGTUSampler;
43 import org.opentrafficsim.graphs.TrajectoryPlot;
44 import org.opentrafficsim.road.car.LaneBasedIndividualCar;
45 import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
46 import org.opentrafficsim.road.gtu.following.FixedAccelerationModel;
47 import org.opentrafficsim.road.gtu.following.GTUFollowingModel;
48 import org.opentrafficsim.road.gtu.following.IDM;
49 import org.opentrafficsim.road.gtu.following.IDMPlus;
50 import org.opentrafficsim.road.gtu.lane.changing.AbstractLaneChangeModel;
51 import org.opentrafficsim.road.gtu.lane.changing.Egoistic;
52 import org.opentrafficsim.road.gtu.lane.changing.FixedLaneChangeModel;
53 import org.opentrafficsim.road.gtu.lane.changing.LaneChangeModel;
54 import org.opentrafficsim.road.network.factory.LaneFactory;
55 import org.opentrafficsim.road.network.lane.CrossSectionLink;
56 import org.opentrafficsim.road.network.lane.Lane;
57 import org.opentrafficsim.road.network.lane.LaneType;
58 import org.opentrafficsim.road.network.lane.Sensor;
59 import org.opentrafficsim.road.network.lane.SinkSensor;
60 import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
61 import org.opentrafficsim.road.network.route.CompleteLaneBasedRouteNavigator;
62 import org.opentrafficsim.road.network.route.FixedLaneBasedRouteGenerator;
63 import org.opentrafficsim.road.network.route.LaneBasedRouteGenerator;
64 import org.opentrafficsim.road.network.route.ProbabilisticLaneBasedRouteGenerator;
65 import org.opentrafficsim.road.network.route.ProbabilisticLaneBasedRouteGenerator.LaneBasedRouteProbability;
66 import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
67 import org.opentrafficsim.simulationengine.properties.AbstractProperty;
68 import org.opentrafficsim.simulationengine.properties.CompoundProperty;
69 import org.opentrafficsim.simulationengine.properties.ContinuousProperty;
70 import org.opentrafficsim.simulationengine.properties.IDMPropertySet;
71 import org.opentrafficsim.simulationengine.properties.ProbabilityDistributionProperty;
72 import org.opentrafficsim.simulationengine.properties.SelectionProperty;
73
74
75
76
77
78
79
80
81
82
83
84 public class XMLNetworks extends AbstractWrappableAnimation
85 {
86
87 private XMLNetworkModel model;
88
89
90
91
92 public XMLNetworks()
93 {
94 this.properties.add(new SelectionProperty("Network", "Network", new String[]{"Merge 1 plus 1 into 1",
95 "Merge 2 plus 1 into 2", "Merge 2 plus 2 into 4", "Split 1 into 1 plus 1", "Split 2 into 1 plus 2",
96 "Split 4 into 2 plus 2"}, 0, false, 0));
97 this.properties.add(new ContinuousProperty("Flow per input lane", "Traffic flow per input lane", 500d, 0d,
98 3000d, "%.0f veh/h", false, 1));
99 }
100
101
102 @Override
103 public final void stopTimersThreads()
104 {
105 super.stopTimersThreads();
106 this.model = null;
107 }
108
109
110 @Override
111 protected final Rectangle2D.Double makeAnimationRectangle()
112 {
113 return new Rectangle2D.Double(-50, -300, 1300, 600);
114 }
115
116
117 @Override
118 protected final OTSModelInterface makeModel(final GTUColorer colorer)
119 {
120 this.model = new XMLNetworkModel(this.savedUserModifiedProperties, colorer);
121 return this.model;
122 }
123
124
125 @Override
126 protected final JPanel makeCharts()
127 {
128 int graphCount = this.model.pathCount();
129 int columns = 1;
130 int rows = 0 == columns ? 0 : (int) Math.ceil(graphCount * 1.0 / columns);
131 TablePanel charts = new TablePanel(columns, rows);
132 for (int graphIndex = 0; graphIndex < graphCount; graphIndex++)
133 {
134 TrajectoryPlot tp =
135 new TrajectoryPlot("Trajectories on lane " + (graphIndex + 1), new Time.Rel(0.5, SECOND), this.model
136 .getPath(graphIndex));
137 tp.setTitle("Trajectory Graph");
138 tp.setExtendedState(Frame.MAXIMIZED_BOTH);
139 LaneBasedGTUSampler graph = tp;
140 Container container = tp.getContentPane();
141 charts.setCell(container, graphIndex % columns, graphIndex / columns);
142 this.model.getPlots().add(graph);
143 }
144 return charts;
145 }
146
147
148 @Override
149 public final String shortName()
150 {
151 return "Test networks";
152 }
153
154
155 @Override
156 public final String description()
157 {
158 return "<html><h1>Test Networks</h1>Prove that the test networks can be constructed and rendered on screen "
159 + "and that a mix of cars and trucks can run on them.<br>On the statistics tab, a trajectory plot "
160 + "is generated for each lane.</html>";
161 }
162
163 }
164
165
166
167
168
169
170
171
172
173
174
175 class XMLNetworkModel implements OTSModelInterface, OTS_SCALAR
176 {
177
178 private static final long serialVersionUID = 20150304L;
179
180
181 private OTSDEVSSimulatorInterface simulator;
182
183
184 private ArrayList<LaneBasedGTUSampler> plots = new ArrayList<LaneBasedGTUSampler>();
185
186
187 private ArrayList<AbstractProperty<?>> properties = null;
188
189
190 private ArrayList<List<Lane>> paths = new ArrayList<List<Lane>>();
191
192
193 private Time.Rel averageHeadway;
194
195
196 private Time.Rel minimumHeadway;
197
198
199 private DistContinuous headwayGenerator;
200
201
202 private Speed.Abs speedLimit = new Speed.Abs(60, KM_PER_HOUR);
203
204
205 private int carsCreated = 0;
206
207
208 private GTUType gtuType = GTUType.makeGTUType("Car");
209
210
211 private GTUFollowingModel carFollowingModelCars;
212
213
214 private GTUFollowingModel carFollowingModelTrucks;
215
216
217 private AbstractLaneChangeModel laneChangeModel = new Egoistic();
218
219
220 private double carProbability;
221
222
223 private Random randomGenerator = new Random(12346);
224
225
226 private LaneBasedRouteGenerator routeGenerator;
227
228
229 private final GTUColorer gtuColorer;
230
231
232
233
234
235 public XMLNetworkModel(final ArrayList<AbstractProperty<?>> userModifiedProperties, final GTUColorer gtuColorer)
236 {
237 this.properties = userModifiedProperties;
238 this.gtuColorer = gtuColorer;
239 }
240
241
242
243
244
245 public final List<Lane> getPath(final int index)
246 {
247 return this.paths.get(index);
248 }
249
250
251
252
253
254 public final int pathCount()
255 {
256 return this.paths.size();
257 }
258
259
260
261
262 public final ArrayList<LaneBasedGTUSampler> getPlots()
263 {
264 return this.plots;
265 }
266
267
268 @Override
269 public final
270 void
271 constructModel(
272 final SimulatorInterface<DoubleScalar.Abs<TimeUnit>, DoubleScalar.Rel<TimeUnit>, OTSSimTimeDouble> theSimulator)
273 throws SimRuntimeException, RemoteException
274 {
275 this.simulator = (OTSDEVSSimulatorInterface) theSimulator;
276 this.simulator = (OTSDEVSSimulatorInterface) theSimulator;
277 OTSNode from = new OTSNode("From", new OTSPoint3D(0, 0, 0));
278 OTSNode end = new OTSNode("End", new OTSPoint3D(1200, 0, 0));
279 OTSNode from2 = new OTSNode("From2", new OTSPoint3D(0, -50, 0));
280 OTSNode firstVia = new OTSNode("Via1", new OTSPoint3D(800, 0, 0));
281 OTSNode end2 = new OTSNode("End2", new OTSPoint3D(1200, -50, 0));
282 OTSNode secondVia = new OTSNode("Via2", new OTSPoint3D(1000, 0, 0));
283 CompoundProperty cp = new CompoundProperty("", "", this.properties, false, 0);
284 String networkType = (String) cp.findByShortName("Network").getValue();
285 boolean merge = networkType.startsWith("M");
286 int lanesOnMain = Integer.parseInt(networkType.split(" ")[merge ? 1 : 5]);
287 int lanesOnBranch = Integer.parseInt(networkType.split(" ")[3]);
288 int lanesOnCommon = lanesOnMain + lanesOnBranch;
289 int lanesOnCommonCompressed = Integer.parseInt(networkType.split(" ")[merge ? 5 : 1]);
290
291 LaneType laneType = new LaneType("CarLane");
292 laneType.addCompatibility(this.gtuType);
293 try
294 {
295 String carFollowingModelName = null;
296 CompoundProperty propertyContainer = new CompoundProperty("", "", this.properties, false, 0);
297 AbstractProperty<?> cfmp = propertyContainer.findByShortName("Car following model");
298 if (null == cfmp)
299 {
300 throw new Error("Cannot find \"Car following model\" property");
301 }
302 if (cfmp instanceof SelectionProperty)
303 {
304 carFollowingModelName = ((SelectionProperty) cfmp).getValue();
305 }
306 else
307 {
308 throw new Error("\"Car following model\" property has wrong type");
309 }
310 Iterator<AbstractProperty<ArrayList<AbstractProperty<?>>>> iterator =
311 new CompoundProperty("", "", this.properties, false, 0).iterator();
312 while (iterator.hasNext())
313 {
314 AbstractProperty<?> ap = iterator.next();
315 if (ap instanceof SelectionProperty)
316 {
317 SelectionProperty sp = (SelectionProperty) ap;
318 if ("Car following model".equals(sp.getShortName()))
319 {
320 carFollowingModelName = sp.getValue();
321 }
322 }
323 else if (ap instanceof ProbabilityDistributionProperty)
324 {
325 ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) ap;
326 String modelName = ap.getShortName();
327 if (modelName.equals("Traffic composition"))
328 {
329 this.carProbability = pdp.getValue()[0];
330 }
331 }
332 else if (ap instanceof ContinuousProperty)
333 {
334 ContinuousProperty contP = (ContinuousProperty) ap;
335 if (contP.getShortName().startsWith("Flow "))
336 {
337 this.averageHeadway = new Time.Rel(3600.0 / contP.getValue(), SECOND);
338 this.minimumHeadway = new Time.Rel(3, SECOND);
339 this.headwayGenerator =
340 new DistErlang(new MersenneTwister(1234), 4, DoubleScalar.minus(this.averageHeadway,
341 this.minimumHeadway).getSI());
342 }
343 }
344 else if (ap instanceof CompoundProperty)
345 {
346 CompoundProperty compoundProperty = (CompoundProperty) ap;
347 if (ap.getShortName().equals("Output"))
348 {
349 continue;
350 }
351 if (ap.getShortName().contains("IDM"))
352 {
353 Acceleration.Abs a = IDMPropertySet.getA(compoundProperty);
354 Acceleration.Abs b = IDMPropertySet.getB(compoundProperty);
355 Length.Rel s0 = IDMPropertySet.getS0(compoundProperty);
356 Time.Rel tSafe = IDMPropertySet.getTSafe(compoundProperty);
357 GTUFollowingModel gtuFollowingModel = null;
358 if (carFollowingModelName.equals("IDM"))
359 {
360 gtuFollowingModel = new IDM(a, b, s0, tSafe, 1.0);
361 }
362 else if (carFollowingModelName.equals("IDM+"))
363 {
364 gtuFollowingModel = new IDMPlus(a, b, s0, tSafe, 1.0);
365 }
366 else
367 {
368 throw new Error("Unknown gtu following model: " + carFollowingModelName);
369 }
370 if (ap.getShortName().contains(" Car "))
371 {
372 this.carFollowingModelCars = gtuFollowingModel;
373 }
374 else if (ap.getShortName().contains(" Truck "))
375 {
376 this.carFollowingModelTrucks = gtuFollowingModel;
377 }
378 else
379 {
380 throw new Error("Cannot determine gtu type for " + ap.getShortName());
381 }
382 }
383 }
384 }
385
386 setupGenerator(LaneFactory.makeMultiLane("From to FirstVia", from, firstVia, null, merge ? lanesOnMain
387 : lanesOnCommonCompressed, laneType, this.speedLimit, this.simulator));
388 Lane[] common =
389 LaneFactory.makeMultiLane("FirstVia to SecondVia", firstVia, secondVia, null, lanesOnCommon, laneType,
390 this.speedLimit, this.simulator);
391 if (merge)
392 {
393 for (int i = lanesOnCommonCompressed; i < lanesOnCommon; i++)
394 {
395 setupBlock(common[i]);
396 }
397 }
398 setupSink(LaneFactory.makeMultiLane("SecondVia to end", secondVia, end, null, merge
399 ? lanesOnCommonCompressed : lanesOnMain, laneType, this.speedLimit, this.simulator), laneType);
400 if (merge)
401 {
402 setupGenerator(LaneFactory.makeMultiLane("From2 to FirstVia", from2, firstVia, null, lanesOnBranch, 0,
403 lanesOnCommon - lanesOnBranch, laneType, this.speedLimit, this.simulator));
404 this.routeGenerator = new FixedLaneBasedRouteGenerator(new CompleteRoute(""));
405 }
406 else
407 {
408 setupSink(LaneFactory.makeMultiLane("SecondVia to end2", secondVia, end2, null, lanesOnBranch,
409 lanesOnCommon - lanesOnBranch, 0, laneType, this.speedLimit, this.simulator), laneType);
410 List<LaneBasedRouteProbability> routeProbabilities = new ArrayList<>();
411 ArrayList<Node> mainRoute = new ArrayList<Node>();
412 mainRoute.add(end);
413 routeProbabilities.add(new LaneBasedRouteProbability(new CompleteLaneBasedRouteNavigator(
414 new CompleteRoute("main", mainRoute)), new java.lang.Double(lanesOnMain)));
415 ArrayList<Node> sideRoute = new ArrayList<Node>();
416 sideRoute.add(end2);
417 routeProbabilities.add(new LaneBasedRouteProbability(new CompleteLaneBasedRouteNavigator(
418 new CompleteRoute("side", sideRoute)), new java.lang.Double(lanesOnBranch)));
419 this.routeGenerator =
420 new ProbabilisticLaneBasedRouteGenerator(routeProbabilities, new MersenneTwister(1234));
421 }
422 for (int index = 0; index < lanesOnCommon; index++)
423 {
424 this.paths.add(new ArrayList<Lane>());
425 Lane lane = common[index];
426
427 while (lane.prevLanes(this.gtuType).size() > 0)
428 {
429 if (lane.prevLanes(this.gtuType).size() > 1)
430 {
431 throw new NetworkException("This network should not have lane merge points");
432 }
433 lane = lane.prevLanes(this.gtuType).iterator().next();
434 }
435
436 while (true)
437 {
438 this.paths.get(index).add(lane);
439 int branching = lane.nextLanes(this.gtuType).size();
440 if (branching == 0)
441 {
442 break;
443 }
444 if (branching > 1)
445 {
446 throw new NetworkException("Thisnetwork should not have lane split points");
447 }
448 lane = lane.nextLanes(this.gtuType).iterator().next();
449 }
450 }
451 this.simulator.scheduleEventAbs(new DoubleScalar.Abs<TimeUnit>(0.999, SECOND), this, this, "drawGraphs",
452 null);
453 }
454 catch (NamingException | NetworkException | GTUException | OTSGeometryException exception1)
455 {
456 exception1.printStackTrace();
457 }
458 }
459
460
461
462
463
464
465
466 private Lane[] setupGenerator(final Lane[] lanes) throws SimRuntimeException
467 {
468 for (Lane lane : lanes)
469 {
470 Object[] arguments = new Object[1];
471 arguments[0] = lane;
472 this.simulator.scheduleEventAbs(new Time.Abs(0.0, SECOND), this, this, "generateCar", arguments);
473 }
474 return lanes;
475 }
476
477
478
479
480
481
482
483
484
485 private Lane[] setupSink(final Lane[] lanes, final LaneType laneType) throws NetworkException, OTSGeometryException
486 {
487 CrossSectionLink link = lanes[0].getParentLink();
488 OTSNode to = (OTSNode) link.getEndNode();
489 OTSNode from = (OTSNode) link.getStartNode();
490 double endLinkLength = 50;
491 double endX =
492 to.getPoint().x + (endLinkLength / link.getLength().getSI()) * (to.getPoint().x - from.getPoint().x);
493 double endY =
494 to.getPoint().y + (endLinkLength / link.getLength().getSI()) * (to.getPoint().y - from.getPoint().y);
495 OTSNode end = new OTSNode("END", new OTSPoint3D(endX, endY, to.getPoint().z));
496 CrossSectionLink endLink = LaneFactory.makeLink("endLink", to, end, null);
497 for (Lane lane : lanes)
498 {
499
500 Lane sinkLane =
501 new Lane(endLink, lane.getId() + "." + "sinkLane", lane.getLateralCenterPosition(1.0), lane
502 .getLateralCenterPosition(1.0), lane.getWidth(1.0), lane.getWidth(1.0), laneType,
503 LongitudinalDirectionality.FORWARD, this.speedLimit, new OvertakingConditions.LeftAndRight());
504 Sensor sensor = new SinkSensor(sinkLane, new Length.Rel(10.0, METER), this.simulator);
505 sinkLane.addSensor(sensor, GTUType.ALL);
506 }
507 return lanes;
508 }
509
510
511
512
513
514
515
516
517
518
519 private Lane setupBlock(final Lane lane) throws NamingException, NetworkException, SimRuntimeException,
520 GTUException
521 {
522 Length.Rel initialPosition = lane.getLength();
523 Map<Lane, Length.Rel> initialPositions = new LinkedHashMap<Lane, Length.Rel>();
524 initialPositions.put(lane, initialPosition);
525 GTUFollowingModel gfm =
526 new FixedAccelerationModel(new Acceleration.Abs(0, AccelerationUnit.SI), new Time.Rel(
527 java.lang.Double.MAX_VALUE, TimeUnit.SI));
528 LaneChangeModel lcm = new FixedLaneChangeModel(null);
529 new LaneBasedIndividualCar("999999", this.gtuType, gfm, lcm, initialPositions, new Speed.Abs(0, KM_PER_HOUR),
530 new Length.Rel(1, METER), lane.getWidth(1), new Speed.Abs(0, KM_PER_HOUR),
531 new CompleteLaneBasedRouteNavigator(new CompleteRoute("")), this.simulator);
532 return lane;
533 }
534
535
536
537
538 protected final void drawGraphs()
539 {
540 for (LaneBasedGTUSampler plot : this.plots)
541 {
542 plot.reGraph();
543 }
544
545 try
546 {
547 this.simulator.scheduleEventAbs(new Time.Abs(this.simulator.getSimulatorTime().get().getSI() + 1, SECOND),
548 this, this, "drawGraphs", null);
549 }
550 catch (SimRuntimeException exception)
551 {
552 exception.printStackTrace();
553 }
554
555 }
556
557
558
559
560
561 protected final void generateCar(final Lane lane)
562 {
563 boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
564 Length.Rel initialPosition = new Length.Rel(0, METER);
565 Speed.Abs initialSpeed = new Speed.Abs(50, KM_PER_HOUR);
566 Map<Lane, Length.Rel> initialPositions = new LinkedHashMap<Lane, Length.Rel>();
567 initialPositions.put(lane, initialPosition);
568 try
569 {
570 Length.Rel vehicleLength = new Length.Rel(generateTruck ? 15 : 4, METER);
571 GTUFollowingModel gtuFollowingModel =
572 generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
573 new LaneBasedIndividualCar("" + (++this.carsCreated), this.gtuType, gtuFollowingModel,
574 this.laneChangeModel, initialPositions, initialSpeed, vehicleLength, new Length.Rel(1.8, METER),
575 new Speed.Abs(200, KM_PER_HOUR), this.routeGenerator.generateRouteNavigator(), this.simulator,
576 DefaultCarAnimation.class, this.gtuColorer);
577 Object[] arguments = new Object[1];
578 arguments[0] = lane;
579 this.simulator.scheduleEventRel(new Time.Rel(this.headwayGenerator.draw(), SECOND), this, this,
580 "generateCar", arguments);
581 }
582 catch (SimRuntimeException | NamingException | NetworkException | GTUException exception)
583 {
584 exception.printStackTrace();
585 }
586 }
587
588
589 @Override
590 public SimulatorInterface<Abs<TimeUnit>, DoubleScalar.Rel<TimeUnit>, OTSSimTimeDouble> getSimulator()
591 throws RemoteException
592 {
593 return this.simulator;
594 }
595
596 }