1 package org.opentrafficsim.demo;
2
3 import java.util.ArrayList;
4 import java.util.LinkedHashSet;
5 import java.util.List;
6 import java.util.Set;
7 import java.util.SortedMap;
8 import java.util.TreeMap;
9 import java.util.function.Supplier;
10
11 import javax.naming.NamingException;
12
13 import org.djunits.unit.DurationUnit;
14 import org.djunits.unit.LengthUnit;
15 import org.djunits.unit.SpeedUnit;
16 import org.djunits.unit.util.UNITS;
17 import org.djunits.value.vdouble.scalar.Direction;
18 import org.djunits.value.vdouble.scalar.Duration;
19 import org.djunits.value.vdouble.scalar.Length;
20 import org.djunits.value.vdouble.scalar.Speed;
21 import org.djutils.draw.curve.OffsetCurve2d;
22 import org.djutils.draw.curve.Straight2d;
23 import org.djutils.draw.function.ContinuousPiecewiseLinearFunction;
24 import org.djutils.draw.point.DirectedPoint2d;
25 import org.djutils.draw.point.Point2d;
26 import org.djutils.event.Event;
27 import org.djutils.event.EventListener;
28 import org.djutils.event.EventType;
29 import org.opentrafficsim.base.logger.Logger;
30 import org.opentrafficsim.base.parameters.ParameterException;
31 import org.opentrafficsim.core.definitions.DefaultsNl;
32 import org.opentrafficsim.core.distributions.FrequencyAndObject;
33 import org.opentrafficsim.core.distributions.ObjectDistribution;
34 import org.opentrafficsim.core.dsol.AbstractOtsModel;
35 import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
36 import org.opentrafficsim.core.gtu.Gtu;
37 import org.opentrafficsim.core.gtu.GtuException;
38 import org.opentrafficsim.core.gtu.GtuType;
39 import org.opentrafficsim.core.idgenerator.IdSupplier;
40 import org.opentrafficsim.core.network.Network;
41 import org.opentrafficsim.core.network.NetworkException;
42 import org.opentrafficsim.core.network.Node;
43 import org.opentrafficsim.core.network.route.FixedRouteGenerator;
44 import org.opentrafficsim.core.network.route.ProbabilisticRouteGenerator;
45 import org.opentrafficsim.core.network.route.Route;
46 import org.opentrafficsim.core.parameters.ParameterFactory;
47 import org.opentrafficsim.core.units.distributions.ContinuousDistDoubleScalar;
48 import org.opentrafficsim.road.definitions.DefaultsRoadNl;
49 import org.opentrafficsim.road.gtu.generator.CfRoomChecker;
50 import org.opentrafficsim.road.gtu.generator.GeneratorPositions;
51 import org.opentrafficsim.road.gtu.generator.LaneBasedGtuGenerator;
52 import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedGtuTemplate;
53 import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedGtuTemplateDistribution;
54 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlannerFactory;
55 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalRoutePlannerFactory;
56 import org.opentrafficsim.road.gtu.tactical.lmrs.Lmrs;
57 import org.opentrafficsim.road.gtu.tactical.lmrs.LmrsFactory;
58 import org.opentrafficsim.road.network.CrossSectionGeometry;
59 import org.opentrafficsim.road.network.CrossSectionLink;
60 import org.opentrafficsim.road.network.Lane;
61 import org.opentrafficsim.road.network.LanePosition;
62 import org.opentrafficsim.road.network.LaneType;
63 import org.opentrafficsim.road.network.RoadNetwork;
64 import org.opentrafficsim.road.network.factory.LaneFactory;
65 import org.opentrafficsim.road.network.object.detector.SinkDetector;
66 import org.opentrafficsim.road.network.speed.LaneSpeedLimits;
67
68 import nl.tudelft.simulation.dsol.SimRuntimeException;
69 import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterDouble;
70 import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterException;
71 import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterMap;
72 import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterSelectionMap;
73 import nl.tudelft.simulation.jstats.distributions.DistContinuous;
74 import nl.tudelft.simulation.jstats.distributions.DistErlang;
75 import nl.tudelft.simulation.jstats.distributions.DistUniform;
76 import nl.tudelft.simulation.jstats.streams.MersenneTwister;
77 import nl.tudelft.simulation.jstats.streams.StreamInterface;
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98 public class NetworksModel extends AbstractOtsModel implements EventListener, UNITS
99 {
100
101 private final RoadNetwork network = new RoadNetwork("network", getSimulator());
102
103
104 private LaneBasedStrategicalPlannerFactory<?> strategicalPlannerFactoryCars = null;
105
106
107 private LaneBasedStrategicalPlannerFactory<?> strategicalPlannerFactoryTrucks = null;
108
109
110 private double carProbability;
111
112
113 private Length minimumDistance = new Length(0, METER);
114
115
116 private Length maximumDistance = new Length(5000, METER);
117
118
119 private StreamInterface stream = new MersenneTwister(12345);
120
121
122 private Supplier<Route> routeSupplierMain;
123
124
125 private Supplier<Route> routeSupplierRamp;
126
127
128 private LaneSpeedLimits speedLimits = new LaneSpeedLimits(new Speed(60, SpeedUnit.KM_PER_HOUR));
129
130
131 private List<List<Lane>> paths = new ArrayList<>();
132
133
134 private IdSupplier idSupplier = new IdSupplier("");
135
136
137 private DistContinuous headwaySupplier;
138
139
140
141
142
143 public NetworksModel(final OtsSimulatorInterface simulator)
144 {
145 super(simulator);
146 createInputParameters();
147 }
148
149
150
151
152 private void createInputParameters()
153 {
154 InputParameterHelper.makeInputParameterMapCarTruck(this.inputParameterMap, 1.0);
155 try
156 {
157 InputParameterMap genericMap = (InputParameterMap) this.inputParameterMap.get("generic");
158
159 genericMap.add(new InputParameterDouble("flow", "Flow per input lane", "Traffic flow per input lane", 500d, 0d,
160 3000d, true, true, "%.0f veh/h", 1.5));
161
162 SortedMap<String, String> networks = new TreeMap<>();
163 networks.put("Merge 1 plus 1 into 1", "M111");
164 networks.put("Merge 2 plus 1 into 2", "M212");
165 networks.put("Merge 2 plus 2 into 4", "M224");
166 networks.put("Split 1 into 1 plus 1", "S111");
167 networks.put("Split 2 into 1 plus 2", "S212");
168 networks.put("Split 4 into 2 plus 2", "S422");
169 InputParameterSelectionMap<String, String> paramSelect = new InputParameterSelectionMap<String, String>("network",
170 "Network to run simulation for", "Network to run simulaton for", networks, "M111", 2.0);
171 genericMap.add(paramSelect);
172 }
173 catch (InputParameterException exception)
174 {
175 exception.printStackTrace();
176 }
177
178 }
179
180 @Override
181 @SuppressWarnings("checkstyle:methodlength")
182 public final void constructModel() throws SimRuntimeException
183 {
184 this.network.addListener(this, Network.GTU_ADD_EVENT);
185 this.network.addListener(this, Network.GTU_REMOVE_EVENT);
186 try
187 {
188 GtuType car = DefaultsNl.CAR;
189 this.carProbability = (double) getInputParameter("generic.carProbability");
190
191 ParameterFactory params = new InputParameterHelper(getInputParameterMap());
192 this.strategicalPlannerFactoryCars =
193 new LaneBasedStrategicalRoutePlannerFactory(new LmrsFactory<>(Lmrs::new).setStream(this.stream), params);
194 this.strategicalPlannerFactoryTrucks =
195 new LaneBasedStrategicalRoutePlannerFactory(new LmrsFactory<>(Lmrs::new).setStream(this.stream), params);
196
197 Point2d pFrom2a = new Point2d(0, -50);
198 Point2d pFrom2b = new Point2d(490, -0.5);
199 Direction onrampDirection = Direction.ofSI(pFrom2a.directionTo(pFrom2b));
200 Node from = new Node(this.network, "From", new Point2d(0, 0), Direction.ZERO);
201 Node end = new Node(this.network, "End", new Point2d(2000, 0), Direction.ZERO);
202 Node from2a = new Node(this.network, "From2a", pFrom2a, onrampDirection);
203 Node from2b = new Node(this.network, "From2b", pFrom2b, onrampDirection);
204 Node firstVia = new Node(this.network, "Via1", new Point2d(500, 0), Direction.ZERO);
205 Point2d pEnd2a = new Point2d(1020, -0.5);
206 Point2d pEnd2b = new Point2d(2000, -50);
207 Direction offrampDirection = Direction.ofSI(pEnd2a.directionTo(pEnd2b));
208 Node end2a = new Node(this.network, "End2a", pEnd2a, offrampDirection);
209 Node end2b = new Node(this.network, "End2b", pEnd2b, offrampDirection);
210 Node secondVia = new Node(this.network, "Via2", new Point2d(1000, 0), Direction.ZERO);
211
212 String networkType = getInputParameter("generic.network").toString();
213 boolean merge = networkType.startsWith("M");
214 int lanesOnMain = Integer.parseInt("" + networkType.charAt(merge ? 1 : 3));
215 int lanesOnBranch = Integer.parseInt("" + networkType.charAt(2));
216 int lanesOnCommon = lanesOnMain + lanesOnBranch;
217 int lanesOnCommonCompressed = Integer.parseInt("" + networkType.charAt(merge ? 3 : 1));
218
219 double contP = (double) getInputParameter("generic.flow");
220 Duration averageHeadway = new Duration(3600.0 / contP, SECOND);
221 Duration minimumHeadway = new Duration(3, SECOND);
222 this.headwaySupplier = new DistErlang(new MersenneTwister(1234), averageHeadway.minus(minimumHeadway).getSI(), 4);
223
224 LaneType laneType = DefaultsRoadNl.TWO_WAY_LANE;
225 Lane[] rampLanes = null;
226 if (merge)
227 {
228 rampLanes = LaneFactory.makeMultiLane(this.network, "From2a to From2b", from2a, from2b, null, lanesOnBranch, 0,
229 lanesOnCommon - lanesOnBranch, laneType, this.speedLimits, this.simulator);
230 LaneFactory.makeMultiLaneBezier(this.network, "From2b to FirstVia", from2a, from2b, firstVia, secondVia,
231 lanesOnBranch, lanesOnCommon - lanesOnBranch, lanesOnCommon - lanesOnBranch, laneType, this.speedLimits,
232 this.simulator);
233 }
234 else
235 {
236 LaneFactory.makeMultiLaneBezier(this.network, "SecondVia to end2a", firstVia, secondVia, end2a, end2b,
237 lanesOnBranch, lanesOnCommon - lanesOnBranch, lanesOnCommon - lanesOnBranch, laneType, this.speedLimits,
238 this.simulator);
239 setupSink(LaneFactory.makeMultiLane(this.network, "end2a to end2b", end2a, end2b, null, lanesOnBranch,
240 lanesOnCommon - lanesOnBranch, 0, laneType, this.speedLimits, this.simulator), laneType);
241 }
242
243 Lane[] startLanes = LaneFactory.makeMultiLane(this.network, "From to FirstVia", from, firstVia, null,
244 merge ? lanesOnMain : lanesOnCommonCompressed, laneType, this.speedLimits, this.simulator);
245 Lane[] common = LaneFactory.makeMultiLane(this.network, "FirstVia to SecondVia", firstVia, secondVia, null,
246 lanesOnCommon, laneType, this.speedLimits, this.simulator);
247 setupSink(
248 LaneFactory.makeMultiLane(this.network, "SecondVia to end", secondVia, end, null,
249 merge ? lanesOnCommonCompressed : lanesOnMain, laneType, this.speedLimits, this.simulator),
250 laneType);
251
252 if (merge)
253 {
254
255 ArrayList<Node> mainRouteNodes = new ArrayList<>();
256 mainRouteNodes.add(from);
257 mainRouteNodes.add(firstVia);
258 mainRouteNodes.add(secondVia);
259 mainRouteNodes.add(end);
260 Route mainRoute = new Route("main", car, mainRouteNodes);
261 this.routeSupplierMain = new FixedRouteGenerator(mainRoute);
262
263 ArrayList<Node> rampRouteNodes = new ArrayList<>();
264 rampRouteNodes.add(from2a);
265 rampRouteNodes.add(from2b);
266 rampRouteNodes.add(firstVia);
267 rampRouteNodes.add(secondVia);
268 rampRouteNodes.add(end);
269 Route rampRoute = new Route("ramp", car, rampRouteNodes);
270 this.routeSupplierRamp = new FixedRouteGenerator(rampRoute);
271 }
272 else
273 {
274
275 List<FrequencyAndObject<Route>> routeProbabilities = new ArrayList<>();
276
277 ArrayList<Node> mainRouteNodes = new ArrayList<>();
278 mainRouteNodes.add(from);
279 mainRouteNodes.add(firstVia);
280 mainRouteNodes.add(secondVia);
281 mainRouteNodes.add(end);
282 Route mainRoute = new Route("main", car, mainRouteNodes);
283 routeProbabilities.add(new FrequencyAndObject<>(lanesOnMain, mainRoute));
284
285 ArrayList<Node> sideRouteNodes = new ArrayList<>();
286 sideRouteNodes.add(from);
287 sideRouteNodes.add(firstVia);
288 sideRouteNodes.add(secondVia);
289 sideRouteNodes.add(end2a);
290 sideRouteNodes.add(end2b);
291 Route sideRoute = new Route("side", car, sideRouteNodes);
292 routeProbabilities.add(new FrequencyAndObject<>(lanesOnBranch, sideRoute));
293 this.routeSupplierMain = new ProbabilisticRouteGenerator(routeProbabilities, new MersenneTwister(1234));
294 }
295
296 if (merge)
297 {
298 setupSupplier(rampLanes);
299 }
300 setupSupplier(startLanes);
301
302 for (int index = 0; index < lanesOnCommon; index++)
303 {
304 this.paths.add(new ArrayList<Lane>());
305 Lane lane = common[index];
306
307 while (lane.prevLanes(car).size() > 0)
308 {
309 if (lane.prevLanes(car).size() > 1)
310 {
311 throw new NetworkException("This network should not have lane merge points");
312 }
313 lane = lane.prevLanes(car).iterator().next();
314 }
315
316 while (true)
317 {
318 this.paths.get(index).add(lane);
319 int branching = lane.nextLanes(car).size();
320 if (branching == 0)
321 {
322 break;
323 }
324 if (branching > 1)
325 {
326 throw new NetworkException("This network should not have lane split points");
327 }
328 lane = lane.nextLanes(car).iterator().next();
329 }
330 }
331 }
332 catch (SimRuntimeException | NetworkException | InputParameterException | GtuException | ParameterException
333 | NamingException exception)
334 {
335 exception.printStackTrace();
336 }
337 }
338
339
340
341
342
343
344
345
346
347
348 private Lane[] setupSupplier(final Lane[] lanes)
349 throws SimRuntimeException, GtuException, ParameterException, NetworkException
350 {
351 for (Lane lane : lanes)
352 {
353 makeSupplier(lane);
354 }
355 return lanes;
356 }
357
358
359
360
361
362
363
364
365
366
367 private LaneBasedGtuGenerator makeSupplier(final Lane lane)
368 throws GtuException, SimRuntimeException, ParameterException, NetworkException
369 {
370 ObjectDistribution<LaneBasedGtuTemplate> distribution = new ObjectDistribution<>(this.stream);
371 Length initialPosition = new Length(16, METER);
372 Set<LanePosition> initialPositions = new LinkedHashSet<>(1);
373 initialPositions.add(new LanePosition(lane, initialPosition));
374
375 LaneBasedGtuTemplate template = makeTemplate(this.stream, lane,
376 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 3, 6), METER),
377 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 1.6, 2.0), METER),
378 new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 140, 180), KM_PER_HOUR),
379 initialPositions, this.strategicalPlannerFactoryCars);
380 distribution.add(new FrequencyAndObject<>(this.carProbability, template));
381 template = makeTemplate(this.stream, lane,
382 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 8, 14), METER),
383 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 2.0, 2.5), METER),
384 new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 100, 140), KM_PER_HOUR),
385 initialPositions, this.strategicalPlannerFactoryTrucks);
386 distribution.add(new FrequencyAndObject<>(1.0 - this.carProbability, template));
387 LaneBasedGtuTemplateDistribution templateDistribution = new LaneBasedGtuTemplateDistribution(distribution);
388 LaneBasedGtuGenerator.RoomChecker roomChecker = new CfRoomChecker();
389 LaneBasedGtuGenerator generator = new LaneBasedGtuGenerator(lane.getId(), new Supplier<Duration>()
390 {
391 @SuppressWarnings("synthetic-access")
392 @Override
393 public Duration get()
394 {
395 return new Duration(NetworksModel.this.headwaySupplier.draw(), DurationUnit.SI);
396 }
397 }, templateDistribution, GeneratorPositions.create(initialPositions, this.stream), this.network, this.simulator,
398 roomChecker, this.idSupplier);
399 generator.setNoLaneChangeDistance(Length.ofSI(100.0));
400 return generator;
401 }
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416 LaneBasedGtuTemplate makeTemplate(final StreamInterface randStream, final Lane lane,
417 final ContinuousDistDoubleScalar.Rel<Length, LengthUnit> lengthDistribution,
418 final ContinuousDistDoubleScalar.Rel<Length, LengthUnit> widthDistribution,
419 final ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit> maximumSpeedDistribution,
420 final Set<LanePosition> initialPositions, final LaneBasedStrategicalPlannerFactory<?> strategicalPlannerFactory)
421 throws GtuException
422 {
423 return new LaneBasedGtuTemplate(DefaultsNl.CAR, new Supplier<Length>()
424 {
425 @Override
426 public Length get()
427 {
428 return lengthDistribution.get();
429 }
430 }, new Supplier<Length>()
431 {
432 @Override
433 public Length get()
434 {
435 return widthDistribution.get();
436 }
437 }, new Supplier<Speed>()
438 {
439 @Override
440 public Speed get()
441 {
442 return maximumSpeedDistribution.get();
443 }
444 }, strategicalPlannerFactory,
445 lane.getLink().getStartNode().getId().equals("From") ? this.routeSupplierMain : this.routeSupplierRamp);
446
447 }
448
449
450
451
452
453
454
455
456 private Lane[] setupSink(final Lane[] lanes, final LaneType laneType) throws NetworkException
457 {
458 CrossSectionLink link = lanes[0].getLink();
459 Node to = (Node) link.getEndNode();
460 Node from = (Node) link.getStartNode();
461 double endLinkLength = 50;
462 double endX = to.getPoint().x + (endLinkLength / link.getLength().getSI()) * (to.getPoint().x - from.getPoint().x);
463 double endY = to.getPoint().y + (endLinkLength / link.getLength().getSI()) * (to.getPoint().y - from.getPoint().y);
464 Node end = new Node(this.network, link.getId() + "END", new Point2d(endX, endY),
465 Direction.ofSI(Math.atan2(to.getPoint().y - from.getPoint().y, to.getPoint().x - from.getPoint().x)));
466 double dir = Math.atan2(to.getPoint().y - from.getPoint().y, to.getPoint().x - from.getPoint().x);
467 DirectedPoint2d startPoint = new DirectedPoint2d(to.getPoint().x, to.getPoint().y, dir);
468 OffsetCurve2d designLine = new Straight2d(startPoint, endLinkLength);
469 CrossSectionLink endLink = LaneFactory.makeLink(this.network, link.getId() + "endLink", to, end, null, this.simulator);
470
471 for (Lane lane : lanes)
472 {
473 ContinuousPiecewiseLinearFunction offset = ContinuousPiecewiseLinearFunction.of(0.0,
474 lane.getLateralCenterPosition(1.0).si, 1.0, lane.getLateralCenterPosition(1.0).si);
475 ContinuousPiecewiseLinearFunction width =
476 ContinuousPiecewiseLinearFunction.of(0.0, lane.getWidth(1.0).si, 1.0, lane.getWidth(1.0).si);
477
478 Lane sinkLane = new Lane(endLink, lane.getId() + "." + "sinkLane",
479 CrossSectionGeometry.of(designLine, null, offset, width), laneType, this.speedLimits);
480 new SinkDetector(sinkLane, new Length(10.0, METER), DefaultsNl.ROAD_USERS);
481 }
482 return lanes;
483 }
484
485
486 private Set<Gtu> knownGTUs = new LinkedHashSet<>();
487
488 @Override
489 public void notify(final Event event)
490 {
491 EventType eventType = event.getType();
492 if (Network.GTU_ADD_EVENT.equals(eventType))
493 {
494 Logger.ots().trace("A GTU was created (id " + (String) event.getContent() + ")");
495 this.network.getGTU((String) event.getContent()).ifPresent((g) -> this.knownGTUs.add(g));
496 }
497 else if (Network.GTU_REMOVE_EVENT.equals(eventType))
498 {
499 Logger.ots().trace("A GTU was removed (id " + ((String) event.getContent()) + ")");
500 this.network.getGTU((String) event.getContent()).ifPresent((g) -> this.knownGTUs.remove(g));
501 }
502 }
503
504 @Override
505 public RoadNetwork getNetwork()
506 {
507 return this.network;
508 }
509
510
511
512
513
514
515 public final List<Lane> getPath(final int index)
516 {
517 return this.paths.get(index);
518 }
519
520
521
522
523
524 public final int pathCount()
525 {
526 return this.paths.size();
527 }
528
529
530
531
532
533 public List<List<Lane>> getPaths()
534 {
535 return this.paths;
536 }
537
538
539
540
541
542 public final Length getMinimumDistance()
543 {
544 return this.minimumDistance;
545 }
546
547
548
549
550
551 public final Length getMaximumDistance()
552 {
553 return this.maximumDistance;
554 }
555
556 }