View Javadoc
1   package org.opentrafficsim.road.gtu;
2   
3   import static org.junit.jupiter.api.Assertions.assertEquals;
4   import static org.junit.jupiter.api.Assertions.assertTrue;
5   import static org.junit.jupiter.api.Assertions.fail;
6   
7   import java.util.ArrayList;
8   import java.util.LinkedHashSet;
9   import java.util.List;
10  import java.util.Map;
11  import java.util.Set;
12  
13  import org.djunits.unit.DurationUnit;
14  import org.djunits.unit.LengthUnit;
15  import org.djunits.unit.TimeUnit;
16  import org.djunits.unit.util.UNITS;
17  import org.djunits.value.vdouble.scalar.Acceleration;
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.Time;
23  import org.djutils.draw.point.Point2d;
24  import org.junit.jupiter.api.Test;
25  import org.opentrafficsim.base.parameters.Parameters;
26  import org.opentrafficsim.core.definitions.DefaultsNl;
27  import org.opentrafficsim.core.dsol.AbstractOtsModel;
28  import org.opentrafficsim.core.dsol.OtsModelInterface;
29  import org.opentrafficsim.core.dsol.OtsSimulator;
30  import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
31  import org.opentrafficsim.core.gtu.GtuException;
32  import org.opentrafficsim.core.gtu.GtuType;
33  import org.opentrafficsim.core.gtu.RelativePosition;
34  import org.opentrafficsim.core.network.Node;
35  import org.opentrafficsim.core.network.route.Route;
36  import org.opentrafficsim.road.DefaultTestParameters;
37  import org.opentrafficsim.road.definitions.DefaultsRoadNl;
38  import org.opentrafficsim.road.gtu.lane.LaneBasedGtu;
39  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedCfLcTacticalPlanner;
40  import org.opentrafficsim.road.gtu.lane.tactical.following.FixedAccelerationModel;
41  import org.opentrafficsim.road.gtu.lane.tactical.following.GtuFollowingModelOld;
42  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.FixedLaneChangeModel;
43  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.LaneChangeModel;
44  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
45  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalRoutePlanner;
46  import org.opentrafficsim.road.network.RoadNetwork;
47  import org.opentrafficsim.road.network.factory.LaneFactory;
48  import org.opentrafficsim.road.network.lane.Lane;
49  import org.opentrafficsim.road.network.lane.LanePosition;
50  import org.opentrafficsim.road.network.lane.LaneType;
51  
52  import nl.tudelft.simulation.dsol.SimRuntimeException;
53  
54  /**
55   * Test the various methods of an AbstractLaneBasedGtu.<br>
56   * As abstract classes cannot be directly
57   * <p>
58   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
59   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
60   * </p>
61   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
62   * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
63   */
64  public class AbstractLaneBasedGtuTest implements UNITS
65  {
66      /**
67       * Test that the constructor puts the supplied values in the correct fields, then check the motion of the GTU.
68       * @throws Exception when something goes wrong (should not happen)
69       */
70      @Test
71      public final void abstractLaneBasedGtuTest() throws Exception
72      {
73          // This initialization code should probably be moved to a helper method that will be used in several tests.
74          // First we need a set of Lanes
75          // To create Lanes we need Nodes and a LaneType
76          // And a simulator, but for that we first need something that implements OtsModelInterface
77          OtsSimulatorInterface simulator = new OtsSimulator("abstractLaneBasedGtuTest");
78          RoadNetwork network = new RoadNetwork("lane base gtu test network", simulator);
79          OtsModelInterface model = new DummyModel(simulator);
80          simulator.initialize(Time.ZERO, Duration.ZERO, new Duration(1, DurationUnit.HOUR), model);
81          Node nodeAFrom = new Node(network, "AFrom", new Point2d(0, 0), Direction.ZERO);
82          Node nodeATo = new Node(network, "ATo", new Point2d(1000, 0), Direction.ZERO);
83          GtuType gtuType = DefaultsNl.CAR;
84          LaneType laneType = DefaultsRoadNl.TWO_WAY_LANE;
85  
86          Lane[] lanesGroupA = LaneFactory.makeMultiLane(network, "A", nodeAFrom, nodeATo, null, 3, laneType,
87                  new Speed(100, KM_PER_HOUR), simulator, DefaultsNl.VEHICLE);
88          // A GTU can exist on several lanes at once; create another lane group to test that
89          Node nodeBFrom = new Node(network, "BFrom", new Point2d(10, 0), Direction.ZERO);
90          Node nodeBTo = new Node(network, "BTo", new Point2d(1000, 0), Direction.ZERO);
91          Lane[] lanesGroupB = LaneFactory.makeMultiLane(network, "B", nodeBFrom, nodeBTo, null, 3, laneType,
92                  new Speed(100, KM_PER_HOUR), simulator, DefaultsNl.VEHICLE);
93          Set<LanePosition> initialLongitudinalPositions = new LinkedHashSet<>(2);
94  
95          Length positionA = new Length(100, METER);
96          initialLongitudinalPositions.add(new LanePosition(lanesGroupA[1], positionA));
97          Length positionB = new Length(90, METER);
98          initialLongitudinalPositions.add(new LanePosition(lanesGroupB[1], positionB));
99          // A Car needs a CarFollowingModel
100         Acceleration acceleration = new Acceleration(2, METER_PER_SECOND_2);
101         Duration validFor = new Duration(10, SECOND);
102         GtuFollowingModelOld gfm = new FixedAccelerationModel(acceleration, validFor);
103         // A Car needs a lane change model
104         // AbstractLaneChangeModel laneChangeModel = new Egoistic();
105         LaneChangeModel laneChangeModel = new FixedLaneChangeModel(null);
106         // A Car needs an initial speed
107         Speed initialSpeed = new Speed(50, KM_PER_HOUR);
108         // Length of the Car
109         Length carLength = new Length(4, METER);
110         // Width of the Car
111         Length carWidth = new Length(1.8, METER);
112         // Maximum speed of the Car
113         Speed maximumSpeed = new Speed(200, KM_PER_HOUR);
114         // ID of the Car
115         String carID = "theCar";
116         // List of Nodes visited by the Car
117         List<Node> nodeList = new ArrayList<Node>();
118         nodeList.add(nodeAFrom);
119         nodeList.add(nodeATo);
120         // Route of the Car
121         Route route = new Route("Route", gtuType, nodeList);
122         // Now we can make a GTU
123         Parameters parameters = DefaultTestParameters.create(); // new
124                                                                 // BehavioralCharacteristics();
125         // LaneBasedBehavioralCharacteristics drivingCharacteristics =
126         // new LaneBasedBehavioralCharacteristics(gfm, laneChangeModel);
127         LaneBasedGtu car = new LaneBasedGtu(carID, gtuType, carLength, carWidth, maximumSpeed, carLength.times(0.5), network);
128         LaneBasedStrategicalPlanner strategicalPlanner =
129                 new LaneBasedStrategicalRoutePlanner(new LaneBasedCfLcTacticalPlanner(gfm, laneChangeModel, car), car);
130         car.setParameters(parameters);
131         car.init(strategicalPlanner, new LanePosition(lanesGroupA[1], positionA), initialSpeed);
132         // Now we can verify the various fields in the newly created Car
133         assertEquals(carID, car.getId(), "ID of the car should be identical to the provided one");
134         // TODO: Test with gfm as part of tactical planner
135         // assertEquals("GTU following model should be identical to the provided one", gfm, car
136         // .getBehavioralCharacteristics().getGtuFollowingModel());
137         assertEquals(carWidth, car.getWidth(), "Width should be identical to the provided width");
138         assertEquals(carLength, car.getLength(), "Length should be identical to the provided length");
139         assertEquals(gtuType, car.getType(), "GTU type should be identical to the provided one");
140         assertEquals(positionA.getSI(), car.position(lanesGroupA[1], car.getReference()).getSI(),
141                 0.0001, "front in lanesGroupA[1] is positionA");
142         // assertEquals("acceleration is 0", 0, car.getAcceleration().getSI(), 0.00001);
143         // edit wouter schakel: fixed acceleration model has a=2.0m/s^2, first plan is made during initialization
144         assertEquals(2.0, car.getAcceleration().getSI(), 0.00001, "acceleration is 2");
145         assertEquals(initialSpeed.getSI(), car.getSpeed().getSI(), 0.00001, "longitudinal speed is " + initialSpeed);
146         assertEquals(0, car.getOperationalPlan().getStartTime().getSI(), 0.00001, "lastEvaluation time is 0");
147         // Test the position(Lane, RelativePosition) method
148         // WS: Removed as null check has been removed from position(...)
149         // try
150         // {
151         // car.position(null, car.getFront());
152         // fail("position on null lane should have thrown a NetworkException");
153         // }
154         // catch (GTUException ne)
155         // {
156         // // Ignore
157         // }
158         for (Lane[] laneGroup : new Lane[][] {lanesGroupA})//, lanesGroupB})
159         {
160             for (int laneIndex = 0; laneIndex < laneGroup.length; laneIndex++)
161             {
162                 Lane lane = laneGroup[laneIndex];
163                 boolean expectException = 1 != laneIndex;
164                 for (RelativePosition relativePosition : new RelativePosition[] {car.getFront(), car.getReference(),
165                         car.getRear()})
166                 {
167                     // System.out.println("lane:" + lane + ", expectedException: " + expectException
168                     // + ", relativePostion: " + relativePosition);
169                     try
170                     {
171                         Length position = car.position(lane, relativePosition);
172                         if (expectException)
173                         {
174                             // System.out.println("position: " + position);
175                             fail("Calling position on lane that the car is NOT on should have thrown a NetworkException");
176                         }
177                         else
178                         {
179                             Length expectedPosition = laneGroup == lanesGroupA ? positionA : positionB;
180                             expectedPosition = expectedPosition.plus(relativePosition.dx());
181                             // System.out.println("reported position: " + position);
182                             // System.out.println("expected position: " + expectedPosition);
183                             assertEquals(expectedPosition.getSI(), position.getSI(), 0.0001,
184                                     "Position should match initial position");
185                         }
186                     }
187                     catch (GtuException ne)
188                     {
189                         if (!expectException)
190                         {
191                             System.out.println(ne);
192                             fail("Calling position on lane that the car is on should NOT have thrown a NetworkException");
193                         }
194                     }
195                 }
196             }
197         }
198         // Assign a movement to the car (10 seconds of acceleration of 2 m/s/s)
199         // scheduled event that moves the car at t=0
200         assertEquals(0, car.getOperationalPlan().getStartTime().getSI(), 0.00001, "lastEvaluation time is 0");
201         // assertEquals("nextEvaluation time is 0", 0, car.getOperationalPlan().getEndTime().getSI(), 0.00001);
202         // edit wouter schakel: fixed acceleration model has t=10s, first plan is made during initialization
203         assertEquals(10.0, car.getOperationalPlan().getEndTime().getSI(), 0.00001, "nextEvaluation time is 10");
204         // Increase the simulator clock in small steps and verify the both positions on all lanes at each step
205         double step = 0.01d;
206         for (int i = 0;; i++)
207         {
208             Time stepTime = new Time(i * step, TimeUnit.BASE_SECOND);
209             if (stepTime.getSI() > validFor.getSI())
210             {
211                 break;
212             }
213             if (stepTime.getSI() > 0.5)
214             {
215                 step = 0.1; // Reduce testing time by increasing the step size
216             }
217             // System.out.println("Simulating until " + stepTime.getSI());
218             simulator.runUpTo(stepTime);
219             while (simulator.isStartingOrRunning())
220             {
221                 try
222                 {
223                     Thread.sleep(1);
224                 }
225                 catch (InterruptedException ie)
226                 {
227                     ie = null; // ignore
228                 }
229             }
230             // Debugging code that helped locate a problem in the DSOL runUpTo code.
231             // System.out.println("stepTime is " + stepTime);
232             // System.out.println("Car simulator time " + car.getSimulator().getSimulatorTime());
233             // System.out.println("Simulator time is now " + simulator.getSimulatorTime());
234             // if (simulator != car.getSimulator())
235             // {
236             // System.err.println("Car runs on a different simulator!");
237             // }
238             // System.out.println("operational plan is " + car.getOperationalPlan());
239             // System.out.println("operational plan end time is " + car.getOperationalPlan().getEndTime());
240             // car.getOperationalPlan().getEndTime();
241             // if (stepTime.getSI() > 0)
242             // {
243             // assertEquals("nextEvaluation time is " + validFor, validFor.getSI(),
244             // car.getOperationalPlan().getEndTime().getSI(), 0.0001);
245             // assertEquals("acceleration is " + acceleration, acceleration.getSI(), car.getAcceleration().getSI(), 0.00001);
246             // }
247             Speed longitudinalSpeed = car.getSpeed();
248             double expectedLongitudinalSpeed = initialSpeed.getSI() + stepTime.getSI() * acceleration.getSI();
249             assertEquals(expectedLongitudinalSpeed, longitudinalSpeed.getSI(),
250                     0.00001, "longitudinal speed is " + expectedLongitudinalSpeed);
251             for (RelativePosition relativePosition : new RelativePosition[] {car.getFront(), car.getRear()})
252             {
253                 Map<Lane, Double> positions = car.fractionalPositions(relativePosition);
254                 assertEquals(1, positions.size(), "Car should be in one lane");
255                 Double pos = positions.get(lanesGroupA[1]);
256                 // System.out.println("Fractional positions: " + positions);
257                 assertTrue(null != pos, "Car should be in lane 1 of lane group A");
258                 assertEquals(pos, car.fractionalPosition(lanesGroupA[1], relativePosition),
259                         0.0000001, "fractional position should be equal to result of fractionalPosition(lane, ...)");
260             }
261             for (Lane[] laneGroup : new Lane[][] {lanesGroupA})//, lanesGroupB})
262             {
263                 for (int laneIndex = 0; laneIndex < laneGroup.length; laneIndex++)
264                 {
265                     Lane lane = laneGroup[laneIndex];
266                     boolean expectException = 1 != laneIndex;
267                     for (RelativePosition relativePosition : new RelativePosition[] {car.getFront(), car.getReference(),
268                             car.getRear()})
269                     {
270                         // System.out.println("lane:" + lane + ", expectedException: " + expectException
271                         // + ", relativePostion: " + relativePosition);
272                         try
273                         {
274                             Length position = car.position(lane, relativePosition);
275                             if (expectException)
276                             {
277                                 // System.out.println("position: " + position);
278                                 fail("Calling position on lane that the car is NOT on should have thrown a "
279                                         + "NetworkException");
280                             }
281                             else
282                             {
283                                 Length expectedPosition = laneGroup == lanesGroupA ? positionA : positionB;
284                                 expectedPosition = expectedPosition
285                                         .plus(new Length(stepTime.getSI() * initialSpeed.getSI(), LengthUnit.SI));
286                                 expectedPosition = expectedPosition.plus(new Length(
287                                         0.5 * acceleration.getSI() * stepTime.getSI() * stepTime.getSI(), LengthUnit.SI));
288                                 expectedPosition = expectedPosition.plus(relativePosition.dx());
289                                 // System.out.println("reported position: " + position);
290                                 // System.out.println("expected position: " + expectedPosition);
291                                 assertEquals(expectedPosition.getSI(), position.getSI(),
292                                         0.0001, "Position should match initial position");
293                             }
294                         }
295                         catch (GtuException ne)
296                         {
297                             if (!expectException)
298                             {
299                                 System.out.println(ne);
300                                 fail("Calling position on lane that the car is on should NOT have thrown a NetworkException");
301                             }
302                         }
303                         try
304                         {
305                             double fractionalPosition = car.fractionalPosition(lane, relativePosition);
306                             if (expectException)
307                             {
308                                 // System.out.println("position: " + position);
309                                 fail("Calling position on lane that the car is NOT on should have thrown a NetworkException");
310                             }
311                             else
312                             {
313                                 Length expectedPosition = laneGroup == lanesGroupA ? positionA : positionB;
314                                 expectedPosition = expectedPosition
315                                         .plus(new Length(stepTime.getSI() * initialSpeed.getSI(), LengthUnit.SI));
316                                 expectedPosition = expectedPosition.plus(new Length(
317                                         0.5 * acceleration.getSI() * stepTime.getSI() * stepTime.getSI(), LengthUnit.SI));
318                                 expectedPosition = expectedPosition.plus(relativePosition.dx());
319                                 // System.out.println("reported position: " + position);
320                                 // System.out.println("expected position: " + expectedPosition);
321                                 double expectedFractionalPosition = expectedPosition.getSI() / lane.getLength().getSI();
322                                 assertEquals(expectedFractionalPosition, fractionalPosition,
323                                         0.000001, "Position should match initial position");
324                             }
325                         }
326                         catch (GtuException ne)
327                         {
328                             if (!expectException)
329                             {
330                                 System.out.println(ne);
331                                 fail("Calling fractionalPosition on lane that the car is on should NOT have thrown a "
332                                         + "NetworkException");
333                             }
334                         }
335                     }
336                 }
337             }
338         }
339         // A GTU can exist on several lanes at once; create another lane group to test that
340         Node nodeCFrom = new Node(network, "CFrom", new Point2d(10, 100), Direction.ZERO);
341         Node nodeCTo = new Node(network, "CTo", new Point2d(1000, 0), Direction.ZERO);
342         Lane[] lanesGroupC = LaneFactory.makeMultiLane(network, "C", nodeCFrom, nodeCTo, null, 3, laneType,
343                 new Speed(100, KM_PER_HOUR), simulator, DefaultsNl.VEHICLE);
344         for (RelativePosition relativePosition : new RelativePosition[] {car.getFront(), car.getRear()})
345         {
346             Map<Lane, Double> positions = car.fractionalPositions(relativePosition);
347             Double pos = positions.get(lanesGroupA[1]);
348             assertTrue(null != pos, "Car should be in lane 1 of lane group A");
349             assertEquals(pos, car.fractionalPosition(lanesGroupA[1], relativePosition),
350                     0.0000001, "fractional position should be equal to result of fractionalPosition(lane, ...)");
351             pos = positions.get(lanesGroupC[0]);
352         }
353         // TODO removeLane should throw an Error when the car is not on that lane (currently this is silently ignored)
354         // TODO figure out why the added lane has a non-zero position
355     }
356 }
357 
358 /**
359  * Dummy OtsModelInterface.
360  * <p>
361  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
362  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
363  * </p>
364  * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
365  */
366 class DummyModel extends AbstractOtsModel
367 {
368     /** */
369     private static final long serialVersionUID = 20150114L;
370 
371     /**
372      * @param simulator the simulator to use
373      */
374     DummyModel(final OtsSimulatorInterface simulator)
375     {
376         super(simulator);
377     }
378 
379     /** {@inheritDoc} */
380     @Override
381     public final void constructModel() throws SimRuntimeException
382     {
383         //
384     }
385 
386     /** {@inheritDoc} */
387     @Override
388     public final RoadNetwork getNetwork()
389     {
390         return null;
391     }
392 
393 }