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.Map;
7 import java.util.Set;
8 import java.util.SortedMap;
9 import java.util.TreeMap;
10 import java.util.function.Supplier;
11
12 import javax.naming.NamingException;
13
14 import org.djunits.unit.DurationUnit;
15 import org.djunits.unit.LengthUnit;
16 import org.djunits.unit.SpeedUnit;
17 import org.djunits.unit.util.UNITS;
18 import org.djunits.value.vdouble.scalar.Direction;
19 import org.djunits.value.vdouble.scalar.Duration;
20 import org.djunits.value.vdouble.scalar.Length;
21 import org.djunits.value.vdouble.scalar.Speed;
22 import org.djutils.draw.curve.OffsetCurve2d;
23 import org.djutils.draw.curve.Straight2d;
24 import org.djutils.draw.function.ContinuousPiecewiseLinearFunction;
25 import org.djutils.draw.point.DirectedPoint2d;
26 import org.djutils.draw.point.Point2d;
27 import org.djutils.event.Event;
28 import org.djutils.event.EventListener;
29 import org.djutils.event.EventType;
30 import org.opentrafficsim.base.logger.Logger;
31 import org.opentrafficsim.base.parameters.ParameterException;
32 import org.opentrafficsim.core.definitions.DefaultsNl;
33 import org.opentrafficsim.core.distributions.FrequencyAndObject;
34 import org.opentrafficsim.core.distributions.ObjectDistribution;
35 import org.opentrafficsim.core.dsol.AbstractOtsModel;
36 import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
37 import org.opentrafficsim.core.gtu.Gtu;
38 import org.opentrafficsim.core.gtu.GtuException;
39 import org.opentrafficsim.core.gtu.GtuType;
40 import org.opentrafficsim.core.idgenerator.IdSupplier;
41 import org.opentrafficsim.core.network.Network;
42 import org.opentrafficsim.core.network.NetworkException;
43 import org.opentrafficsim.core.network.Node;
44 import org.opentrafficsim.core.network.route.FixedRouteGenerator;
45 import org.opentrafficsim.core.network.route.ProbabilisticRouteGenerator;
46 import org.opentrafficsim.core.network.route.Route;
47 import org.opentrafficsim.core.parameters.ParameterFactory;
48 import org.opentrafficsim.core.units.distributions.ContinuousDistDoubleScalar;
49 import org.opentrafficsim.road.definitions.DefaultsRoadNl;
50 import org.opentrafficsim.road.gtu.generator.CfRoomChecker;
51 import org.opentrafficsim.road.gtu.generator.GeneratorPositions;
52 import org.opentrafficsim.road.gtu.generator.LaneBasedGtuGenerator;
53 import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedGtuTemplate;
54 import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedGtuTemplateDistribution;
55 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.Lmrs;
56 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.LmrsFactory;
57 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlannerFactory;
58 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalRoutePlannerFactory;
59 import org.opentrafficsim.road.network.RoadNetwork;
60 import org.opentrafficsim.road.network.factory.LaneFactory;
61 import org.opentrafficsim.road.network.lane.CrossSectionGeometry;
62 import org.opentrafficsim.road.network.lane.CrossSectionLink;
63 import org.opentrafficsim.road.network.lane.Lane;
64 import org.opentrafficsim.road.network.lane.LanePosition;
65 import org.opentrafficsim.road.network.lane.LaneType;
66 import org.opentrafficsim.road.network.lane.object.detector.SinkDetector;
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 Speed speedLimit = new Speed(60, 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.speedLimit, this.simulator, DefaultsNl.VEHICLE);
230 LaneFactory.makeMultiLaneBezier(this.network, "From2b to FirstVia", from2a, from2b, firstVia, secondVia,
231 lanesOnBranch, lanesOnCommon - lanesOnBranch, lanesOnCommon - lanesOnBranch, laneType, this.speedLimit,
232 this.simulator, DefaultsNl.VEHICLE);
233 }
234 else
235 {
236 LaneFactory.makeMultiLaneBezier(this.network, "SecondVia to end2a", firstVia, secondVia, end2a, end2b,
237 lanesOnBranch, lanesOnCommon - lanesOnBranch, lanesOnCommon - lanesOnBranch, laneType, this.speedLimit,
238 this.simulator, DefaultsNl.VEHICLE);
239 setupSink(LaneFactory.makeMultiLane(this.network, "end2a to end2b", end2a, end2b, null, lanesOnBranch,
240 lanesOnCommon - lanesOnBranch, 0, laneType, this.speedLimit, this.simulator, DefaultsNl.VEHICLE),
241 laneType);
242 }
243
244 Lane[] startLanes = LaneFactory.makeMultiLane(this.network, "From to FirstVia", from, firstVia, null,
245 merge ? lanesOnMain : lanesOnCommonCompressed, laneType, this.speedLimit, this.simulator,
246 DefaultsNl.VEHICLE);
247 Lane[] common = LaneFactory.makeMultiLane(this.network, "FirstVia to SecondVia", firstVia, secondVia, null,
248 lanesOnCommon, laneType, this.speedLimit, this.simulator, DefaultsNl.VEHICLE);
249 setupSink(LaneFactory.makeMultiLane(this.network, "SecondVia to end", secondVia, end, null,
250 merge ? lanesOnCommonCompressed : lanesOnMain, laneType, this.speedLimit, this.simulator,
251 DefaultsNl.VEHICLE), laneType);
252
253 if (merge)
254 {
255
256 ArrayList<Node> mainRouteNodes = new ArrayList<>();
257 mainRouteNodes.add(from);
258 mainRouteNodes.add(firstVia);
259 mainRouteNodes.add(secondVia);
260 mainRouteNodes.add(end);
261 Route mainRoute = new Route("main", car, mainRouteNodes);
262 this.routeSupplierMain = new FixedRouteGenerator(mainRoute);
263
264 ArrayList<Node> rampRouteNodes = new ArrayList<>();
265 rampRouteNodes.add(from2a);
266 rampRouteNodes.add(from2b);
267 rampRouteNodes.add(firstVia);
268 rampRouteNodes.add(secondVia);
269 rampRouteNodes.add(end);
270 Route rampRoute = new Route("ramp", car, rampRouteNodes);
271 this.routeSupplierRamp = new FixedRouteGenerator(rampRoute);
272 }
273 else
274 {
275
276 List<FrequencyAndObject<Route>> routeProbabilities = new ArrayList<>();
277
278 ArrayList<Node> mainRouteNodes = new ArrayList<>();
279 mainRouteNodes.add(from);
280 mainRouteNodes.add(firstVia);
281 mainRouteNodes.add(secondVia);
282 mainRouteNodes.add(end);
283 Route mainRoute = new Route("main", car, mainRouteNodes);
284 routeProbabilities.add(new FrequencyAndObject<>(lanesOnMain, mainRoute));
285
286 ArrayList<Node> sideRouteNodes = new ArrayList<>();
287 sideRouteNodes.add(from);
288 sideRouteNodes.add(firstVia);
289 sideRouteNodes.add(secondVia);
290 sideRouteNodes.add(end2a);
291 sideRouteNodes.add(end2b);
292 Route sideRoute = new Route("side", car, sideRouteNodes);
293 routeProbabilities.add(new FrequencyAndObject<>(lanesOnBranch, sideRoute));
294 this.routeSupplierMain = new ProbabilisticRouteGenerator(routeProbabilities, new MersenneTwister(1234));
295 }
296
297 if (merge)
298 {
299 setupSupplier(rampLanes);
300 }
301 setupSupplier(startLanes);
302
303 for (int index = 0; index < lanesOnCommon; index++)
304 {
305 this.paths.add(new ArrayList<Lane>());
306 Lane lane = common[index];
307
308 while (lane.prevLanes(car).size() > 0)
309 {
310 if (lane.prevLanes(car).size() > 1)
311 {
312 throw new NetworkException("This network should not have lane merge points");
313 }
314 lane = lane.prevLanes(car).iterator().next();
315 }
316
317 while (true)
318 {
319 this.paths.get(index).add(lane);
320 int branching = lane.nextLanes(car).size();
321 if (branching == 0)
322 {
323 break;
324 }
325 if (branching > 1)
326 {
327 throw new NetworkException("This network should not have lane split points");
328 }
329 lane = lane.nextLanes(car).iterator().next();
330 }
331 }
332 }
333 catch (SimRuntimeException | NetworkException | InputParameterException | GtuException | ParameterException
334 | NamingException exception)
335 {
336 exception.printStackTrace();
337 }
338 }
339
340
341
342
343
344
345
346
347
348
349 private Lane[] setupSupplier(final Lane[] lanes)
350 throws SimRuntimeException, GtuException, ParameterException, NetworkException
351 {
352 for (Lane lane : lanes)
353 {
354 makeSupplier(lane);
355 }
356 return lanes;
357 }
358
359
360
361
362
363
364
365
366
367
368 private LaneBasedGtuGenerator makeSupplier(final Lane lane)
369 throws GtuException, SimRuntimeException, ParameterException, NetworkException
370 {
371 ObjectDistribution<LaneBasedGtuTemplate> distribution = new ObjectDistribution<>(this.stream);
372 Length initialPosition = new Length(16, METER);
373 Set<LanePosition> initialPositions = new LinkedHashSet<>(1);
374 initialPositions.add(new LanePosition(lane, initialPosition));
375
376 LaneBasedGtuTemplate template = makeTemplate(this.stream, lane,
377 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 3, 6), METER),
378 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 1.6, 2.0), METER),
379 new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 140, 180), KM_PER_HOUR),
380 initialPositions, this.strategicalPlannerFactoryCars);
381 distribution.add(new FrequencyAndObject<>(this.carProbability, template));
382 template = makeTemplate(this.stream, lane,
383 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 8, 14), METER),
384 new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 2.0, 2.5), METER),
385 new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 100, 140), KM_PER_HOUR),
386 initialPositions, this.strategicalPlannerFactoryTrucks);
387 distribution.add(new FrequencyAndObject<>(1.0 - this.carProbability, template));
388 LaneBasedGtuTemplateDistribution templateDistribution = new LaneBasedGtuTemplateDistribution(distribution);
389 LaneBasedGtuGenerator.RoomChecker roomChecker = new CfRoomChecker();
390 return new LaneBasedGtuGenerator(lane.getId(), new Supplier<Duration>()
391 {
392 @SuppressWarnings("synthetic-access")
393 @Override
394 public Duration get()
395 {
396 return new Duration(NetworksModel.this.headwaySupplier.draw(), DurationUnit.SI);
397 }
398 }, templateDistribution, GeneratorPositions.create(initialPositions, this.stream), this.network, this.simulator,
399 roomChecker, this.idSupplier);
400 }
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415 LaneBasedGtuTemplate makeTemplate(final StreamInterface randStream, final Lane lane,
416 final ContinuousDistDoubleScalar.Rel<Length, LengthUnit> lengthDistribution,
417 final ContinuousDistDoubleScalar.Rel<Length, LengthUnit> widthDistribution,
418 final ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit> maximumSpeedDistribution,
419 final Set<LanePosition> initialPositions, final LaneBasedStrategicalPlannerFactory<?> strategicalPlannerFactory)
420 throws GtuException
421 {
422 return new LaneBasedGtuTemplate(DefaultsNl.CAR, new Supplier<Length>()
423 {
424 @Override
425 public Length get()
426 {
427 return lengthDistribution.get();
428 }
429 }, new Supplier<Length>()
430 {
431 @Override
432 public Length get()
433 {
434 return widthDistribution.get();
435 }
436 }, new Supplier<Speed>()
437 {
438 @Override
439 public Speed get()
440 {
441 return maximumSpeedDistribution.get();
442 }
443 }, strategicalPlannerFactory,
444 lane.getLink().getStartNode().getId().equals("From") ? this.routeSupplierMain : this.routeSupplierRamp);
445
446 }
447
448
449
450
451
452
453
454
455 private Lane[] setupSink(final Lane[] lanes, final LaneType laneType) throws NetworkException
456 {
457 CrossSectionLink link = lanes[0].getLink();
458 Node to = (Node) link.getEndNode();
459 Node from = (Node) link.getStartNode();
460 double endLinkLength = 50;
461 double endX = to.getPoint().x + (endLinkLength / link.getLength().getSI()) * (to.getPoint().x - from.getPoint().x);
462 double endY = to.getPoint().y + (endLinkLength / link.getLength().getSI()) * (to.getPoint().y - from.getPoint().y);
463 Node end = new Node(this.network, link.getId() + "END", new Point2d(endX, endY),
464 Direction.ofSI(Math.atan2(to.getPoint().y - from.getPoint().y, to.getPoint().x - from.getPoint().x)));
465 double dir = Math.atan2(to.getPoint().y - from.getPoint().y, to.getPoint().x - from.getPoint().x);
466 DirectedPoint2d startPoint = new DirectedPoint2d(to.getPoint().x, to.getPoint().y, dir);
467 OffsetCurve2d designLine = new Straight2d(startPoint, endLinkLength);
468 CrossSectionLink endLink = LaneFactory.makeLink(this.network, link.getId() + "endLink", to, end, null, this.simulator);
469
470 for (Lane lane : lanes)
471 {
472 ContinuousPiecewiseLinearFunction offset = ContinuousPiecewiseLinearFunction.of(0.0,
473 lane.getLateralCenterPosition(1.0).si, 1.0, lane.getLateralCenterPosition(1.0).si);
474 ContinuousPiecewiseLinearFunction width =
475 ContinuousPiecewiseLinearFunction.of(0.0, lane.getWidth(1.0).si, 1.0, lane.getWidth(1.0).si);
476
477 Lane sinkLane =
478 new Lane(endLink, lane.getId() + "." + "sinkLane", CrossSectionGeometry.of(designLine, null, offset, width),
479 laneType, Map.of(DefaultsNl.VEHICLE, this.speedLimit));
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 final Length getMinimumDistance()
534 {
535 return this.minimumDistance;
536 }
537
538
539
540
541
542 public final Length getMaximumDistance()
543 {
544 return this.maximumDistance;
545 }
546
547 }