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