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